Repository navigation
Expand file tree
/
Copy pathchainsol.js
More file actions
1397 lines (1276 loc) · 66.9 KB
/
Copy pathchainsol.js
File metadata and controls
1397 lines (1276 loc) · 66.9 KB
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
#!/usr/bin/env node
/* Extract the transactions against a smart contract that has been deployed on
the Ethereum mainnet into a truffle test suite for the contract.
Arguments:
-c name of the contract (no default, mandatory argument)
-a address of the deployed contract, which must be one of the verified contracts
on etherscan.io. (no default, mandatory argument)
-nt number of transactions (default 100)
-na number of addresses (default 1000)
-v compiler version (default 0.4.24)
-d debug flag
Output:
The output is a shell script that writes the neccessary files in a directory
prepared by "truffle init", including the contract itself, the configuration,
the migration and the test scripts.
Examples:
mkdir PonziTokenV4
cd PonziTokenV4
truffle init
chainsol PonziTokenV4 0xe923dD860176d3ef69D7852257cC773900807f7C 15 > shar.sh
sh -x shar.sh
truffle test
Description:
chainsol tool extracts the source of the contract, the abi, the transactions,
the event logs, and the balances of the addresses involved after each
transaction.
The tool pauses regularly for a few seconds to comply with the rate limiting
policies of etherscan.io.
The central data type is what is called here the "Prototype" format, which is
the same as the decoded ABI format. The etherscan.io api provides a variety
of information in different formats, all of which is converted into
prototypes. The code generation converts prototypes into javascript code.
Each test script begins by deploying the contract with its constructor
aguments, asserting that this has succeeded.
Then each external transaction as it has been extracted from the mainnet
chain is replayed in a truffle test. The test checks that the the events
emitted on the mainnet are also emitted in the replay.
Any internal transactions are assumed to be triggerd by the contract code.
Finally, all constant functions from the contract are called once with random
arguments to simulate the behaviour of the Dapp that we do not have access
to. The output of the constant functions and the emitted events represent the
output of a contract.
The tests generate a variety of useful data in JSON format for further
processing.
Limitations & assumptions:
The account addresses used by the transactions on the mainnet are replaced by
account addresses generated by ganache. Since these are generously stocked
with Ether, it is possible that some of the replayed transactions succeeed
where the transaction on the mainnet failed due to insufficient ether.
The maximum number of addresses that can be used in the code and the
transactions is 100. If the source of a contract contains more than 100
addresses, chainsol aborts.
The list of transactions will be reduced such that in total no more than 100
addresses occur in the source code + the transactions.
Most Dapps use a variety of pure functions to extract information from the
contract. Calls to such function calls are not stored in the block chain and
are therefore unavailable for test generation. To compensate for this, after
each transaction all pure functions of the contract are called once, with
randomly selected arguments.
The internal transactions generated by a contract on the mainnet are assumed
to be replayed by the contract code when it is run on the truffle network.
The internal transactions are not monitored.
Some transactions on the mainnet use the maximum amount of gas. For
example 0xfce53dfe8685a98045aea202d9a3421bcdd1a0640b2fc746de23d22ba01ccb96.
In this case any assertion on the maximum amount of gas raises a fase
positive.
Some contracts make assumptions on the present, past or future by comparing
specific block numbers to the current block number. Such test may fail on
the test network. For example "require (block.number > 100000)" on truffle
will probably fail as each test run starts at block 0.
Some contracts call service contracts that are assumed to have been deployed
already. Such service contracts are not present on the truffle network and are
therefore not supported. For example Etheroll (
0xddf0d0b9914d530e0b743808249d9af901f1bd0 ) uses Oraclize (
https://github.com/oraclize/ethereum-api ).
If a contract consists of multiple source files, these have to be concatenated
and offered as one input file. This is how etherscan.io collects the sources
of verified contracts in one file. The name of the source file is normally also
the name of the contract to be deployed, but not always. An example is Leverage
at address 0xEf6da6E6E72e3381a1F97EA520d2844582d85eDbs, which should really
be WinEthFree at address 0x2ae9d68295F8B6c3A12eE5279271980830775F30.
*/
// Replace this etherscan.io API key by your own please
const APIKey = "WN...Q" ;
const randomSeed = 0 ;
const maxRandom = 10 ;
const abiDecoder = require( "abi-decoder" ) ;
const child_process = require( "child_process" ) ;
const etherscanApi = require( "etherscan-api" ).init( APIKey ) ;
const fetch = require( "node-fetch" ) ;
const fs = require( "fs" ) ;
const nodeFetch = require( "node-fetch" ) ;
const random = require( "random-seed" ).create( randomSeed ) ;
const sleep = require( "sleep" ) ;
const stringifyObject = require( "stringify-object" ) ;
const web3Utils = require( "web3-utils" ) ;
// Seconds to sleep before a request to etherscan.io
const shortSleep = 7 ;
const longSleep = 500 ;
// Set by main
var debug = false ;
// Default compiler version
const defaultVersion = '0.4.24' ;
// Provide access to the locally stored emscripten versions of the solidity compiler.
const soljson = require( './soljson.js' ) ;
// The emscripten binaries of the compiler versions are stored here
const soljsonDirectory = 'soljson' ;
// The first 100 accounts generated by "ganache-cli -a 100 -d" to be used to
// replace hard coded addresses in the source.
// "address(this)" represents the address of the deployed contract.
const ganacheList = [
"0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1", "0xffcf8fdee72ac11b5c542428b35eef5769c409f0", "0x22d491bde2303f2f43325b2108d26f1eaba1e32b", "0xe11ba2b4d45eaed5996cd0823791e0c93114882d",
"0xd03ea8624c8c5987235048901fb614fdca89b117", "0x95ced938f7991cd0dfcb48f0a06a40fa1af46ebc", "0x3e5e9111ae8eb78fe1cc3bb8915d5d461f3ef9a9", "0x28a8746e75304c0780e011bed21c72cd78cd535e",
"0xaca94ef8bd5ffee41947b4585a84bda5a3d3da6e", "0x1df62f291b2e969fb0849d99d9ce41e2f137006e", "0x610bb1573d1046fcb8a70bbbd395754cd57c2b60", "0x855fa758c77d68a04990e992aa4dcdef899f654a",
"0xfa2435eacf10ca62ae6787ba2fb044f8733ee843", "0x64e078a8aa15a41b85890265648e965de686bae6", "0x2f560290fef1b3ada194b6aa9c40aa71f8e95598", "0xf408f04f9b7691f7174fa2bb73ad6d45fd5d3cbe",
"0x66fc63c2572bf3add0fe5d44b97c2e614e35e9a3", "0xf0d5bc18421fa04d0a2a2ef540ba5a9f04014be3", "0x325a621dea613bcfb5b1a69a7aced0ea4afbd73a", "0x3fd652c93dfa333979ad762cf581df89baba6795",
"0x73eb6d82cfb20ba669e9c178b718d770c49bb52f", "0x9d8e5fac117b15daced7c326ae009dfe857621f1", "0x982a8cbe734cb8c29a6a7e02a3b0e4512148f6f9", "0xcdc1e53bdc74bbf5b5f715d6327dca5785e228b4",
"0xf5d1eaf516ef3b0582609622a221656872b82f78", "0xf8ea26c3800d074a11bf814db9a0735886c90197", "0x2647116f9304abb9f0b7ac29abc0d9ad540506c8", "0x80a32a0e5ca81b5a236168c21532b32e3cbc95e2",
"0x47f55a2ace3b84b0f03717224dbb7d0df4351658", "0xc817898296b27589230b891f144dd71a892b0c18", "0x0d38e653ec28bdea5a2296fd5940aab2d0b8875c", "0x1b569e8f1246907518ff3386d523dcf373e769b6",
"0xcbb025e7933fadfc7c830ae520fb2fd6d28c1065", "0xddeea4839bbed92bdad8ec79ae4f4bc2be1a3974", "0xbc2cf859f671b78ba42ebb65deb31cc7fec07019", "0xf75588126126ddf76bdc8aba91a08f31d2567ca5",
"0x369109c74ea7159e77e180f969f7d48c2bf19b4c", "0xa2a628f4eee25f5b02b0688ad9c1290e2e9a3d9e", "0x693d718ccfade6f4a1379051d6ab998146f3173f", "0x845a0f9441081779110fee40e6d5d8b90ce676ef",
"0xc7739909e08a9a0f303a010d46658bdb4d5a6786", "0x99cce66d3a39c2c2b83afceff04c5ec56e9b2a58", "0x4b930e7b3e491e37eab48ecc8a667c59e307ef20", "0x02233b22860f810e32fb0751f368fe4ef21a1c05",
"0x89c1d413758f8339ade263e6e6bc072f1d429f32", "0x61bbb5135b43f03c96570616d6d3f607b7103111", "0x8c4ce7a10a4e38ee96fed47c628be1ffa57ab96e", "0x25c1230c7efc00cfd2fcaa3a44f30948853824bc",
"0x709f7ae06fe93be48fbb90ffddd69e2746fa8506", "0xc0514c03d097fcbb77a74b4da5b594ba473b6ce1", "0x103b31135d99417a22684ed93cbbcd4ccd208046", "0xf8856d473639e40f60db8979f5752a9c15903bb2",
"0x753897706061fde347465055fcac4bd040745624", "0x7cd15a5d345558a203655e40b1afb14f936c73f7", "0x7d8ae65273b9d1e6b239b36af9adea0414d189b7", "0x05a561f51a2d8a092b11e20c72b5df15a9d82278",
"0x80030beca8292f416e7906535668475c75d9c47e", "0xeda51422804340e3dc0dd9b6d441125b5c7cf3ff", "0xe21812faa737ff0eeec268f509acb306bc735fec", "0x4d85247717cf8621d7894f36de35e8b6b6d384bc",
"0x19b2d46091dd332f0753dabf0cf8304cf61ed1c5", "0x42c7c045729a84f8e65239308ca8279d6fb21c89", "0xeed15bb091bf3f615400f6f8160ac423eaf6a413", "0x0f6f0ecfab78f8e54b130e3b3ebd88b3613c97d1",
"0x33a053885a8232ed78d688b43a405587ba446e5e", "0x4397655ddd031043eb0859ad7a90c3c889e12a4d", "0x6e57514b1997029500c13007a59fb6da1ceac7c4", "0x85c38d25744f02619047b76195ecf835554f70bc",
"0x69901c8c4263a0368c19d3cd9dc51b09bec4c4b1", "0x256dd44a34478acec9a7da479dbcf0c3c599ad55", "0x61f41c87113e04b32eb8fbaa4946b1ef98479756", "0xa8ba9dea29234be7504fae477d2f6b1fd1078d46",
"0x831c50ac59c3794185fabae289d3a5ba8b09403c", "0xc8f2d6111bc7207c25eb4f944cb29f0e851a8541", "0xbca6ebd43dcb10851f398b4cb8fbade3133b2c45", "0x856c1365488375d21875f80d6045c956e47ed5ec",
"0x356780865cd279e4d2dc6d99b32eda8fd8e8a39c", "0x1baec60a021c5e26a1071776a1549c45c79951d5", "0x8155eb275ea6ebd0d572a44087c948b02d794013", "0x6a8bbdb024861739b0dcd1700c8b8f603f1cf7c6",
"0xb890c74caa6c052db376837e67f0476589991922", "0xd5b6d6b730b1c1be10b82a0a1c89f1db24f752c3", "0x2a828adcc1a3647dba43ed05375a4d0b00eea789", "0x624a97293d8cea5ca78d538ac6599e4051a19174",
"0xe7a3ebba0647fb07d0b21927305aa95284316993", "0xd74485a6600d8de95d84d5e1747480c528df1f9a", "0x3b1cb706e5fff494da8873ad9c1a30aa802f4522", "0xfbdb66ae3fa6f1b37a02c82751117fc3aad4572b",
"0x4f92c13cacf198eb25698709e3d225e6a2e22dd8", "0x18282ec61c35bef47698c3e65314c9a0ff617b3c", "0xafa5e9d58e245b7f3efecc9e706b06d52cd28da1", "0xd32115d6e4a4dfdf0807544723d514e3f293d3b6",
"0x56fa56dc28081f6353737061e2278631b2659598", "0x3fae75cce89a972fa1b6d87bb080fb2c6060f0b3", "0xa9f913312b7ec75f755c4f3edb6e2bbd3526b918", "0x1f627b7fb483e5b8d59aa191fec94d01753c7d24",
"0xb45de3796b206793e8ad3509202da91d35e9a6d9", "0x17332dd7f9bd584e2e83f4cffdca0a448b3b903a", "0x9d7822d5bb9f7b9b655669550095d2f14afac469", "0x4c0408db276ef793333baf5b226d8b180c3d0a89"
] ;
function convertAddress( theAddress ) {
if( theAddress === 0 || theAddress.match( /^0x0*$/ ) ) {
return addressZero ;
} else if( theAddress === 1 || theAddress.match( /^0x0*1$/ ) ) {
return addressOne ;
} else if( theAddress === addressThis ) {
return addressThis ;
} else {
try {
return web3Utils.toChecksumAddress( theAddress ) ;
} catch( error ) {
return theAddress ;
}
}
}
const addressZero = "0x0000000000000000000000000000000000000000" ;
const addressZeroIndex = 0 ;
const addressOne = "0x0000000000000000000000000000000000000001" ;
const addressOneIndex = 1 ;
const addressThis = "address(this)" ;
const addressThisIndex = 2 ;
const addressList = [ addressZero, addressOne, addressThis ].concat( ganacheList.map( item => convertAddress( item ) ) ) ;
// Stringify an object into single line java script source with quotes
function codify( object ) {
return stringifyObject( object, {
singleQuotes: false,
inlineCharacterLimit: Number.MAX_SAFE_INTEGER
} ) ;
}
// Stringify an object into single line java script source with quotes, except for "value" properties
function codify_value( object ) {
return stringifyObject( object, {
singleQuotes: false,
inlineCharacterLimit: Number.MAX_SAFE_INTEGER,
transform: ( obj, prop, originalResult ) => {
if( prop === "value" ) {
return obj.value ;
} else {
return originalResult ;
}
}
} ) ;
}
// Generate the truffle migration scripts
function generateMigrations( compilerVersion ) {
console.log( "cat > contracts/Migrations.sol << 'END-of-contracts/Migrations.sol'" ) ;
if( compilerVersion.match( /^0\.[0-3].*/ ) ) {
console.log( "// pragma solidity %s;", compilerVersion ) ;
console.log( "\ncontract Migrations {" ) ;
console.log( "\taddress public owner;" ) ;
console.log( "\tuint public last_completed_migration;" ) ;
console.log( "" ) ;
console.log( "\n\tmodifier restricted( ) {" ) ;
console.log( "\t\tif( msg.sender == owner ) _" ) ;
console.log( "\t}" ) ;
console.log( "" ) ;
console.log( "\n\tfunction Migrations( ) {" ) ;
console.log( "\t\towner = msg.sender;" ) ;
console.log( "\t}" ) ;
console.log( "" ) ;
console.log( "\n\tfunction setCompleted( uint completed ) restricted {" ) ;
console.log( "\t\tlast_completed_migration = completed;" ) ;
console.log( "\t}" ) ;
console.log( "" ) ;
console.log( "\n\tfunction upgrade( address new_address ) restricted {" ) ;
console.log( "\t\tMigrations upgraded = Migrations( new_address ) ;" ) ;
console.log( "\t\tupgraded.setCompleted( last_completed_migration ) ;" ) ;
console.log( "\t}" ) ;
console.log( "}" ) ;
} else { // For 0.4.0 and up
console.log( "pragma solidity %s;", compilerVersion ) ;
console.log( "\ncontract Migrations {" ) ;
console.log( "\taddress public owner;" ) ;
console.log( "\tuint public last_completed_migration;" ) ;
console.log( "\n\tfunction Migrations( ) public {" ) ;
console.log( "\t\towner = msg.sender;" ) ;
console.log( "\t}" ) ;
console.log( "\n\tmodifier restricted( ) {" ) ;
console.log( "\t\tif( msg.sender == owner ) _;" ) ;
console.log( "\t}" ) ;
console.log( "\n\tfunction setCompleted( uint completed ) public restricted {" ) ;
console.log( "\t\tlast_completed_migration = completed;" ) ;
console.log( "\t}" ) ;
console.log( "\n\tfunction upgrade( address new_address ) public restricted {" ) ;
console.log( "\t\tMigrations upgraded = Migrations( new_address ) ;" ) ;
console.log( "\t\tupgraded.setCompleted( last_completed_migration ) ;" ) ;
console.log( "\t}" ) ;
console.log( "}" ) ;
}
console.log( "END-of-contracts/Migrations.sol" ) ;
console.log( "cat > migrations/1_initial_migration.js << 'END-of-migrations/1_initial_migration.js'" ) ;
console.log( "var Migrations = artifacts.require( \"./Migrations.sol\" ) ;" ) ;
console.log( "\nmodule.exports = function( deployer ) {" ) ;
console.log( "\tdeployer.deploy( Migrations ) ;" ) ;
console.log( "};" ) ;
console.log( "END-of-migrations/1_initial_migration.js" ) ;
}
// Generate the configutaion and a few support functions for testing
function generateSupport( compilerVersion ) {
console.log( "cat > truffle.js << 'END-of-test/truffle.js'" ) ;
console.log( "module.exports = {" ) ;
console.log( "\tcompilers: {" ) ;
console.log( "\t\tsolc: {" ) ;
console.log( "\t\t\tversion: \"%s\",", compilerVersion ) ;
console.log( "\t\t\toptimizer: {" ) ;
console.log( "\t\t\t\tenabled: true," ) ;
console.log( "\t\t\t\truns: 200" ) ;
console.log( "\t\t\t}" ) ;
console.log( "\t\t}" ) ;
console.log( "\t}," ) ;
console.log( "\tnetworks: {" ) ;
console.log( "\t\ttest: {" ) ;
console.log( "\t\t\thost: \"127.0.0.1\"," ) ;
console.log( "\t\t\tport: 8545," ) ;
console.log( "\t\t\tnetwork_id: \"*\" // Match any network id" ) ;
console.log( "\t\t}" ) ;
console.log( "\t}" ) ;
console.log( "} ;" ) ;
console.log( "END-of-test/truffle.js" ) ;
console.log( "cat > test/support.js << 'END-of-test/support.js'" ) ;
console.log( "// Turn instamining off" ) ;
console.log( "function _minerStop( ) {" ) ;
console.log( "\treturn new Promise( ( resolve, reject ) => {" ) ;
console.log( "\t\tweb3.currentProvider.send( {" ) ;
console.log( "\t\t\tjsonrpc: '2.0'," ) ;
console.log( "\t\t\tmethod: 'miner_stop'," ) ;
console.log( "\t\t\tparams: []," ) ;
console.log( "\t\t\tid: new Date( ).getSeconds( )" ) ;
console.log( "\t\t}, ( err2, resp2 ) => {" ) ;
console.log( "\t\t\treturn err2 ? reject( err2 ) : resolve( resp2 ) ;" ) ;
console.log( "\t\t} ) ;" ) ;
console.log( "\t} ) ;" ) ;
console.log( "}" ) ;
console.log( "\n// Mine a new block with the given timestamp and sequence number" ) ;
console.log( "function _mineBlockWithTimestamp( sequence, timestamp ) {" ) ;
console.log( "\treturn new Promise( ( resolve, reject ) => {" ) ;
console.log( "\t\tweb3.currentProvider.send( {" ) ;
console.log( "\t\t\tjsonrpc: '2.0'," ) ;
console.log( "\t\t\tmethod: 'evm_mine'," ) ;
console.log( "\t\t\tevm_mine_sequence: sequence," ) ;
console.log( "\t\t\tparams: [timestamp]," ) ;
console.log( "\t\t\tid: new Date( ).getSeconds( )" ) ;
console.log( "\t\t}, ( err2, resp2 ) => {" ) ;
console.log( "\t\t\treturn err2 ? reject( err2 ) : resolve( resp2 ) ;" ) ;
console.log( "\t\t} ) ;" ) ;
console.log( "\t} ) ;" ) ;
console.log( "}" ) ;
console.log( "\n// Promisify the getBlockNumber function" ) ;
console.log( "function _getBlockNumber( ) {" ) ;
console.log( "\treturn new Promise( function( resolve, reject ) {" ) ;
console.log( "\t\tweb3.eth.getBlockNumber( function( e, result ) {" ) ;
console.log( "\t\t\tif( e !== null ) {" ) ;
console.log( "\t\t\t\t reject( e ) ;" ) ;
console.log( "\t\t\t} else {" ) ;
console.log( "\t\t\t\t resolve( result ) ;" ) ;
console.log( "\t\t\t}" ) ;
console.log( "\t\t} ) ;" ) ;
console.log( "\t} ) ;" ) ;
console.log( "}" ) ;
console.log( "\nmodule.exports = {" ) ;
console.log( "\tminerStop: _minerStop," ) ;
console.log( "\tmineBlockWithTimestamp: _mineBlockWithTimestamp," ) ;
console.log( "\tgetBlockNumber: _getBlockNumber" ) ;
console.log( "} ;" ) ;
console.log( "END-of-test/support.js" ) ;
}
// Convert a prototype to a signature of the form name( type1, type2, ... )
function prototype2signature( data ) {
return data.name + "(" + data.inputs.map( item => item.type ).join( "," ) + ")" ;
}
// Convert one argument
function prototype2argument( itemType, itemValue ) {
let index = itemType.search( /\[\d*\]$/ ) ;
if( index >= 0 ) {
return "[" + itemValue.map( item => prototype2argument( itemType.slice( 0, index ), item ) ).join( "," ) + "]" ;
} else if( itemType.match( /^address$/ ) ) {
return "addressList[" + itemValue + "]" ;
} else if( itemType.match( /^string$/ ) ) {
return "`" + itemValue + "`" ;
} else {
return codify( itemValue ) ;
}
}
// Randomise one argument
function randomiseArgument( itemType ) {
let index = itemType.search( /\[\d*\]$/ ) ;
if( index >= 0 ) {
return "[" + randomiseArgument( itemType.slice( 0, index ) ) + "]" ;
} else if( itemType.match( /^string$/ ) ) {
return "random.string( maxRandom )" ;
} else if( itemType.match( /^int\d*$/ ) ) {
return "random.intBetween( -maxRandom, maxRandom )" ;
} else if( itemType.match( /^uint\d*$/ ) ) {
return "random.range( maxRandom )" ;
} else if( itemType.match( /^bytes\d*$/ ) ) {
return "\"0x\" + random.range( maxRandom ).toString( 16 )" ;
} else if( itemType.match( /^address$/ ) ) {
return "addressList[ random.range( addressList.length - 3 ) + 3 ]" ; // Avoid addressZero addressOne, and addressThis
} else if( itemType.match( /^bool$/ ) ) {
return "( random.range( 2 ) === 0 )" ;
} else {
console.error( "chainsol:fatal: cannot decode type %s", itemType ) ;
process.exit( 1 ) ;
}
}
// Randomise the arguments of a prototype.
function randomiseProtoype( prototype ) {
var result = { inputs: null, name: prototype.name, outputs: prototype.outputs, type: prototype.type } ;
result.inputs = prototype.inputs.map( item => { return { type: item.type, name: item.name, value: randomiseArgument( item.type ) } } ) ;
return result ;
}
// Determine if this is a send transaction
function isSendTransaction( txInput ) {
return txInput === "0x" || parseInt( txInput ) === 0 ;
}
// Convert one argument, given its type and its value. All argments of type
// address are replaced by an index in the addressList
function convertArgument( itemType, itemValue, addressListOriginal ) {
let index = itemType.search( /\[\d*\]$/ ) ;
if( index >= 0 ) {
return itemValue.map( item => convertArgument( itemType.slice( 0, index ), item, addressListOriginal ) ) ;
} else if( itemType.match( /^address$/ ) ) {
return addressIndex = addressListOriginal.indexOf( convertAddress( itemValue ) ) ;
} else {
return itemValue ;
}
}
// Convert input data into a prototype
// All argments of type address are relaced by one of the addressList
function convertPrototype( txInput, addressListOriginal ) {
var result ;
if( isSendTransaction( txInput ) ) {
result = { inputs: [], name: "sendTransaction", outputs: [], type: "function" } ;
} else {
var decodedInput ;
try {
decodedInput = abiDecoder.decodeMethod( txInput ) ;
} catch( error ) {
console.error( "chainsol:fatal: cannot decode Tx input %s (error %s)", txInput, error.message ) ;
process.exit( 1 ) ;
}
if( typeof decodedInput === "undefined" || typeof decodedInput.params === "undefined" ) {
result = { inputs: [], name: "sendTransaction", outputs: [], type: "function" } ; // This is the fallback function
} else {
result = { inputs: [], name: decodedInput.name, outputs: [], type: "function" } ;
result.inputs = decodedInput.params.map( item =>
{ return { type: item.type, name: item.name, value: convertArgument( item.type, item.value, addressListOriginal ) } } ) ;
}
}
return result ;
}
// Make sure that we do not call the etherscan API too frequently. up to 5 times per second is ok
function etherscanSleep( seconds ) {
if( typeof etherscanSleep.count === "undefined" ) {
etherscanSleep.count = 0 ;
}
sleep.sleep( seconds ) ;
etherscanSleep.count ++ ;
}
// Ask etherscan.io for the encoded abi of a contract
async function etherscanGetabi( contractName, address ) {
var result ;
etherscanSleep( shortSleep ) ;
try {
result = await etherscanApi.contract.getabi( address ) ;
} catch( error ) {
console.error( "chainsol:warning: cannot get contract ABI of %s, address %s (error %s), trying again", contractName, address, error.message ) ;
etherscanSleep( longSleep ) ;
try {
result = await etherscanApi.contract.getabi( address ) ;
} catch( error ) {
console.error( "chainsol:fatal: cannot get contract ABI of %s, address %s (error %s)", contractName, address, error.message ) ;
process.exit( 1 ) ;
}
}
return result.result ;
}
// Filter all create transactions out of the traces, subtraces etc.
function parseTraceCalls( traceCalls, contractAddress ) {
for( var callIndex = 0; callIndex < traceCalls.length; callIndex++ ) {
const traceItem = traceCalls[ callIndex ] ;
if( traceItem.type === 'create' &&
typeof traceItem.result !== 'undefined' &&
typeof traceItem.result.address !== 'undefined' &&
traceItem.result.address.match( new RegExp( contractAddress, 'i' ) ) ) {
return [ traceItem ] ;
} else if( typeof traceItem.calls !== 'undefined' ) {
const result = parseTraceCalls( traceItem.calls, contractAddress ) ;
if( result.length > 0 ) {
return [ callIndex ].concat( result ) ;
}
}
}
return [] ;
}
// Fetch the traces for the given transaction and return the create transaction for the given contract
async function etherscanParityRawTrace( txHash, contractAddress ) {
var doc, result ;
const url = "https://etherscan.io/vmtrace?txhash=" + txHash + "&type=parity#raw" ;
etherscanSleep( shortSleep ) ;
try {
doc = await fetch( url ) ;
result = await doc.text( ) ;
} catch( error ) {
console.error( "chainsol:warning: cannot get contract source of %s, address %s (error %s), trying again", contractName, address, error.message ) ;
etherscanSleep( longSleep ) ;
try {
doc = await fetch( url ) ;
result = await doc.text( ) ;
} catch( error ) {
console.error( "chainsol:fatal: cannot get contract source of %s, address %s (error %s)", contractName, address, error.message ) ;
process.exit( 1 ) ;
}
}
const source = result.replace( /.*<pre id='editor'>(.*?)<\/pre>.*/s, '$1' ) ;
const traceCalls = JSON.parse( '[' + source + ']' ) ;
return parseTraceCalls( traceCalls, contractAddress ) ;
}
// Ask etherscan.io for the source code of a contract
async function etherscanCodePage( contractName, address ) {
var doc, result ;
const url = "https://etherscan.io/address/" + address + "#code" ;
etherscanSleep( shortSleep ) ;
try {
doc = await fetch( url ) ;
result = await doc.text( ) ;
} catch( error ) {
console.error( "chainsol:warning: cannot get contract source of %s, address %s (error %s), trying again", contractName, address, error.message ) ;
etherscanSleep( longSleep ) ;
try {
doc = await fetch( url ) ;
result = await doc.text( ) ;
} catch( error ) {
console.error( "chainsol:fatal: cannot get contract source of %s, address %s (error %s)", contractName, address, error.message ) ;
process.exit( 1 ) ;
}
}
const rawSource = result.replace( /.*<pre class='js-sourcecopyarea editor' id='editor' style='margin-top: 5px;'>(.*?)<\/pre><br>.*/s, '$1' ) ;
const source = rawSource
.replace( />/g, ">" )
.replace( /</g, "<" )
.replace( /"/g, "\"" )
.replace( /&/g, "&" )
.replace( /'/g, "'" )
.replace( /\r/g, "" )
.replace( /<a href="[^"]*" class="[^"]*" data-cfemail="[^"]*">[^<]*<\/a>/, 'email-protection' ) ;
const txHash = result.replace( /.*title='Creator Txn Hash' class='hash-tag text-truncate'>(0x[0-9a-fA-F]*)<\/a>.*/s, '$1' ) ;
const libSourceList = result.replace( /.*Library Used<\/h4><\/div><pre Class=[^>]*>(.*?)<br><\/pre><\/div>.*/s, '$1' ) ;
const libList = ( libSourceList.length == result.length ? [] :
libSourceList.split( '<br>' ).map( item => item.replace( /([A-Za-z0-9_]*) : <a href=[^>]*>(0x[0-9a-fA-F]*)<\/a>.*/, '$1:$2' ) ) ) ;
return {
source: source,
txHash: ( txHash.length === 66 ? txHash : "0x" ),
libList: libList
} ;
}
// Ask etherscan.io for the internal transaction list of a contract
async function etherscanTxlistInternal( contractName, address, fromBlock, toBlock ) {
var result ;
etherscanSleep( shortSleep ) ;
try {
result = await etherscanApi.account.txlistinternal( null, address, fromBlock, toBlock, 'asc' ) ;
} catch( error ) {
console.error( "chainsol:warning: cannot get transaction list of %s, address %s fromBlock %d toBlock %d (error %s), trying again",
contractName, address, fromBlock, toBlock, error.message ) ;
etherscanSleep( longSleep ) ;
try {
result = await etherscanApi.account.txlist( null, address, fromBlock, toBlock, 'asc' ) ;
} catch( error ) {
console.error( "chainsol:fatal: cannot get transaction list of %s, address %s fromBlock %d toBlock %d (error %s)",
contractName, address, fromBlock, toBlock, error.message ) ;
process.exit( 1 ) ;
}
}
return result.result ;
}
// Ask etherscan.io for the transaction list of a contract
async function etherscanTxlist( contractName, address ) {
var result ;
etherscanSleep( shortSleep ) ;
try {
result = await etherscanApi.account.txlist( address ) ;
} catch( error ) {
console.error( "chainsol:warning: cannot get transaction list of %s, address %s (error %s), trying again", contractName, address, error.message ) ;
etherscanSleep( longSleep ) ;
try {
result = await etherscanApi.account.txlist( address ) ;
} catch( error ) {
console.error( "chainsol:fatal: cannot get transaction list of %s, address %s (error %s)", contractName, address, error.message ) ;
process.exit( 1 ) ;
}
}
return result.result ;
}
// Ask etherscan.io for the block with the given number
async function etherscanBlock( number ) {
var result ;
etherscanSleep( shortSleep ) ;
try {
result = await etherscanApi.proxy.eth_getBlockByNumber( number ) ;
} catch( error ) {
console.error( "chainsol:warning: cannot get block %s, number %s (error %s), trying again", contractName, number, error.message ) ;
etherscanSleep( longSleep ) ;
try {
result = await etherscanApi.proxy.eth_getBlockByNumber( number ) ;
} catch( error ) {
console.error( "chainsol:fatal: cannot get block %s, number %s (error %s)", contractName, hash, error.message ) ;
process.exit( 1 ) ;
}
}
return result.result ;
}
// Ask etherscan.io for the transaction corresponding to the hash
async function etherscanTransaction( hash ) {
var result ;
etherscanSleep( shortSleep ) ;
try {
result = await etherscanApi.proxy.eth_getTransactionByHash( hash ) ;
} catch( error ) {
console.error( "chainsol:warning: cannot get transaction %s, hash %s (error %s), trying again", contractName, hash, error.message ) ;
etherscanSleep( longSleep ) ;
try {
result = await etherscanApi.proxy.eth_getTransactionByHash( hash ) ;
} catch( error ) {
console.error( "chainsol:fatal: cannot get transaction %s, hash %s (error %s)", contractName, hash, error.message ) ;
process.exit( 1 ) ;
}
}
return result.result ;
}
// Ask etherscan.io for the receipt corresponding to a specfic transaction hash
async function etherscanTransactionReceipt( contractName, hash ) {
var result ;
etherscanSleep( shortSleep ) ;
try {
result = await etherscanApi.proxy.eth_getTransactionReceipt( hash ) ;
} catch( error ) {
console.error( "chainsol:warning: cannot get transaction receipt of %s, hash %s (error %s), trying again", contractName, hash, error.message ) ;
etherscanSleep( longSleep ) ;
try {
result = await etherscanApi.proxy.eth_getTransactionReceipt( hash ) ;
} catch( error ) {
console.error( "chainsol:fatal: cannot get transaction receipt of %s, hash %s (error %s)", contractName, hash, error.message ) ;
process.exit( 1 ) ;
}
}
return result.result ;
}
// Ask etherscan.io for the event logs of a contract
async function etherscanGetLogs( contractName, address, blockNumber, transactionHash, topicListOriginal ) {
var result = [] ;
for( var topicIndex = 0 ; topicIndex < topicListOriginal.length; topicIndex++ ) {
etherscanSleep( shortSleep ) ;
const topic = topicListOriginal[ topicIndex ] ;
var events ;
try {
events = await etherscanApi.log.getLogs( address, blockNumber, "latest", topic ) ;
} catch( error ) {
events = { result: [] } ;
if( ! ( typeof error === "string" && error === "NOTOK" ) ) {
console.error( "chainsol:warning: no events of %s at %s with topic %s (error %s)", contractName, transactionHash, topic, error ) ;
}
}
result[ topicIndex ] = events.result.filter( item => item.transactionHash === transactionHash ) ;
if( debug ) {
console.log( "// etherscanGetLogs( address %s, blockNumber %d, transactionHash %s, topic %s ) = %s", address, blockNumber, transactionHash, topic, JSON.stringify( result[ topicIndex ] ) ) ;
}
}
return result ;
}
// Ask etherscan.io for the balance of an address in a specific block
async function etherscanBalance( contractName, address, blockNumber ) {
var result ;
etherscanSleep( shortSleep ) ;
try {
result = await etherscanApi.account.balance( address, blockNumber ) ;
} catch( error ) {
console.error( "chainsol:warning: cannot get account balance of %s, address %s (error %s), trying again ", contractName, address, error.message ) ;
etherscanSleep( longSleep ) ;
try {
result = await etherscanApi.account.balance( address, blockNumber ) ;
} catch( error ) {
console.error( "chainsol:fatal: cannot get account balance of %s, address %s (error %s)", contractName, address, error.message ) ;
process.exit( 1 ) ;
}
}
return result.result ;
}
// Ask etherscan.io for the number of constructor arguments
async function etherscanNargs( contractName, address ) {
const url ="https://etherscan.io/address/" + address + "#code" ;
var request, reply, result ;
etherscanSleep( shortSleep ) ;
try {
request = await nodeFetch( url ) ;
reply = await request.text( ) ;
} catch( error ) {
console.error( "chainsol:warning: cannot get constructor arguments of %s, address %s (error %s), trying again", contractName, address, error.message ) ;
etherscanSleep( longSleep ) ;
try {
request = await nodeFetch( url ) ;
reply = await request.text( ) ;
} catch( error ) {
console.error( "chainsol:fatal: cannot get constructor arguments of %s, address %s (error %s)", contractName, address, error.message ) ;
process.exit( 1 ) ;
}
}
const start = reply.indexOf( "-----Encoded View---------------" ) ;
if( start < 0 ) {
result = 0 ;
} else {
result = parseInt( reply.slice( start ).replace( /[^\d]*(\d+) Constructor Arguments found.*/s, "$1" ) ) ;
if( isNaN( result ) ) {
console.error( "chainsol:fatal: cannot decode constructor arguments of %s at %s", contractName, address ) ;
process.exit( 1 ) ;
}
}
return result ;
}
// Generate the AST for the source
function readASTData( contractName, contractAddressOriginal, compilerVersion, contractSource ) {
const settings = {
outputSelection: {
'*': {
'': [ 'legacyAST' ]
}
}
} ;
const output = soljson.emscriptenCompile( process.env.HOME + '/' + soljsonDirectory, compilerVersion, contractSource, settings ) ;
const ast = ( typeof output.sources !== 'undefined' &&
typeof output.sources.Task !== 'undefined' &&
typeof output.sources.Task.legacyAST !== 'undefined' ? output.sources.Task.legacyAST : [] ) ;
return ast ;
}
// Traverse an AST generated by solc and collect all hard coded addresses in the
// variable addressListOriginal
function collectAddressList( addressListOriginal, node ) {
if( node.name === "Literal" ) {
if( debug ) {
console.log( "# %s", JSON.stringify( node ) ) ;
}
if( node.attributes.type === "address" || ( node.attributes.type !== null && node.attributes.type.startsWith( "int_const" ) ) ) {
const theAddress = node.attributes.value ;
if( theAddress.length === 42 ) {
saveAddress( theAddress, addressListOriginal ) ;
}
}
}
if( typeof node.children !== "undefined" ) {
node.children.map( child => collectAddressList( addressListOriginal, child ) ) ;
}
}
// Generate the source code of the contract
async function generateSource( contractName, contractSource ) {
console.log( "cat >contracts/%s.sol << 'END-of-contracts/%s.sol'", contractName, contractName ) ;
console.log( contractSource ) ;
console.log( "END-of-contracts/%s.sol", contractName ) ;
}
// Take all of the constant functions of this contract at random, randomise
// their arguments and generate the code to all them
function generateConstantFunction( methodPrototypeListOriginal ) {
console.log( "\nfunction convertAddress( theAddress ) {" ) ;
console.log( "\tif( theAddress === 0 || theAddress.match( /^0x0*$/ ) ) {" ) ;
console.log( "\t\treturn \"%s\" ;", addressZero ) ;
console.log( "\t} else if( theAddress === 1 || theAddress.match( /^0x0*1$/ ) ) {" ) ;
console.log( "\t\treturn \"%s\" ;", addressOne ) ;
console.log( "\t} else if( theAddress === \"%s\" ) {", addressThis ) ;
console.log( "\t\treturn \"%s\" ;", addressThis ) ;
console.log( "\t} else {" ) ;
console.log( "\t\ttry {" ) ;
console.log( "\t\t\treturn web3.utils.toChecksumAddress( theAddress ) ;" ) ;
console.log( "\t\t} catch( error ) {" ) ;
console.log( "\t\t\treturn theAddress ;" ) ;
console.log( "\t\t}" ) ;
console.log( "\t}" ) ;
console.log( "}" ) ;
console.log( "\nfunction mergeEvent( call, result ) {" ) ;
console.log( "\tvar merge = { inputs: [], name: call.name, outputs: [], type: call.type } ;" ) ;
console.log( "\tfor( var i = 0; i < call.inputs.length; i++ ) {" ) ;
console.log( "\t\tconst item = result[ call.inputs[ i ].name ] ;" ) ;
console.log( "\t\tif( typeof item !== \"undefined\" ) {" ) ;
console.log( "\t\t\tmerge.outputs[ i ] = { name: call.inputs[ i ].name, type: call.inputs[ i ].type, value: ( item === null ? \"null\" :" )
console.log( "\t\t\t\t( typeof item.toString === \"undefined\" ? item : item.toString( 10, 85 ) ) ) } ;" ) ;
console.log( "\t\t}" ) ;
console.log( "\t}" ) ;
console.log( "\treturn merge ;" ) ;
console.log( "}" ) ;
console.log( "\nfunction mergeCall( call, args ) {" ) ;
console.log( "\tvar merge = { inputs: call.inputs, name: call.name, outputs: [], type: call.type } ;" ) ;
console.log( "\tif( typeof args.isError !== 'undefined' ) {" ) ;
console.log( "\t\tmerge.isError = args.isError ;" ) ;
console.log( "\t\tmerge.message = args.message ;" ) ;
console.log( "\t} else if( call.outputs.length === 1 ) {" ) ;
console.log( "\t\tmerge.outputs[ 0 ] = { name: call.outputs[ 0 ].name, type: call.outputs[ 0 ].type, value: ( args === null ? \"null\" :" )
console.log( "\t\t\t\t( typeof args.toString === \"undefined\" ? args : args.toString( 10, 85 ) ) ) } ;" ) ;
console.log( "\t} else {" ) ;
console.log( "\t\tfor( var i = 0; i < call.outputs.length; i++ ) {" ) ;
console.log( "\t\t\tconst item = args[ i ] ;" ) ;
console.log( "\t\t\tmerge.outputs[ i ] = { name: call.outputs[ i ].name, type: call.outputs[ i ].type, value: ( item === null ? \"null\" :" )
console.log( "\t\t\t\t( typeof item.toString === \"undefined\" ? item : item.toString( 10, 85 ) ) ) } ;" ) ;
console.log( "\t\t}" ) ;
console.log( "\t}" ) ;
console.log( "\treturn merge ;" ) ;
console.log( "}" ) ;
console.log( "\nasync function constantFunction( txIndex, deployedContract ) {" ) ;
console.log( "\tvar methodCall, methodArgs, methodResult ;" ) ;
for( var methodIndex = 0; methodIndex < methodPrototypeListOriginal.length; methodIndex++ ) {
const methodPrototype = randomiseProtoype( methodPrototypeListOriginal[ methodIndex ] ) ;
const methodCall = "methodCall[\" + txIndex + \"," + methodIndex + "]" ;
console.log( "\tmethodCall = %s ;", codify_value( methodPrototype ) ) ;
console.log( "\tconsole.log( \"%s = %s\", JSON.stringify( methodCall ) ) ;", methodCall ) ;
const methodActual = methodPrototype.inputs.map( ( item, index ) => "methodCall.inputs[ " + index + " ].value" ) ;
const methodResult = "methodResult[\" + txIndex + \"," + methodIndex + "]" ;
console.log( "\ttry {" ) ;
const methodTypeList = methodPrototype.inputs.map( item => item.type ).join( "," ) ;
const methodName = 'methods[ "' + methodPrototype.name + '(' + methodTypeList + ')" ]' ;
console.log( "\t\tmethodArgs = await deployedContract.%s( %s ) ;", methodName, methodActual ) ;
console.log( "\t} catch( methodError ) {" ) ;
console.log( "\t\tmethodArgs = { isError: 1, message: methodError.message } ;" ) ;
console.log( "\t}" ) ;
console.log( "\tmethodResult = mergeCall( methodCall, methodArgs ) ;" ) ;
console.log( "\tconsole.log( \"%s = %s\", JSON.stringify( methodResult ) ) ;", methodResult ) ;
}
console.log( "}" ) ;
}
// Generate the block check for the test
function checkAddresses( ) {
console.log( "\n\tit( \"TEST: check all blocks\", async function( ) {" ) ;
console.log( "\t\tconst blocknumber = await support.getBlockNumber( ) ;" ) ;
console.log( "\t\tfor( var i = 0; i <= blocknumber; i++ ) {" ) ;
console.log( "\t\t\tconst block = await web3.eth.getBlock( i, true ) ;" ) ;
console.log( "\t\t\tconsole.log( \"block[%d] = %s\", i, JSON.stringify( block ) ) ;" ) ;
console.log( "\t\t}" ) ;
console.log( "\t} )" ) ;
}
// Rember all address in an addressListOriginal, avoiding duplicates
function saveAddress( theAddress, addressListOriginal ) {
var index = addressListOriginal.indexOf( convertAddress( theAddress ) ) ;
if( index === -1 ) {
index = addressListOriginal.push( convertAddress( theAddress ) ) ;
}
}
// Generate the main test for a transaction
async function generateMethodTx( contractName, abiDecoder, txOriginal, txIndex, txPrototype, methodPrototypeListOriginal, eventPrototypeListOriginal, addressListOriginal, topicListOriginal ) {
for( var inputIndex = 0; inputIndex < txPrototype.inputs.length; inputIndex++ ) {
txPrototype.inputs[ inputIndex ].value = prototype2argument( txPrototype.inputs[ inputIndex ].type, txPrototype.inputs[ inputIndex ].value ) ;
}
const txActual = txPrototype.inputs.map( item => item.value ).join( ", " ) ;
const txTypeList = txPrototype.inputs.map( item => item.type ).join( "," ) ;
const txActualTxt = txActual.replace( /"/g, '\\"' ).replace( /\n/g, "" ) ;
console.log( "\n\tit( \"TEST: %s( %s )\", async function( ) {", txPrototype.name, ( txActualTxt.length > 40 ? txActualTxt.slice( 0, 40 ) + "..." : txActualTxt ) ) ;
if( txIndex === 0 ) {
console.log( "\t\tawait support.minerStop( ) ;" ) ;
console.log( "\t\taddressList = [ \"%s\", \"%s\", \"%s\" ].concat( accounts ).map( item => convertAddress( item ) ) ;", addressZero, addressOne, addressThis ) ;
}
console.log( "\t\tconst txOriginal = %s ;", codify( txOriginal ) ) ;
console.log( "\t\tconsole.log( \"txOriginal[%d] = %s\", JSON.stringify( txOriginal ) ) ;", txIndex ) ;
const fromIndex = addressListOriginal.indexOf( convertAddress( txOriginal.from ) ) ;
const toIndex = addressListOriginal.indexOf( convertAddress( txOriginal.to ) ) ;
if( txIndex === 0 ) {
console.log( "\t\tconst txOptions = { from: addressList[%d], to: 0, value: \"%s\" }", fromIndex, txOriginal.value ) ;
} else {
console.log( "\t\tconst txOptions = { from: addressList[%d], to: addressList[%d], value: \"%s\" }", fromIndex, toIndex, txOriginal.value ) ;
}
console.log( "\t\tconsole.log( \"txOptions[%d] = %s\", JSON.stringify( txOptions ) ) ;", txIndex ) ;
console.log( "\t\tconst txCall = %s ;", codify_value( txPrototype ) ) ;
console.log( "\t\tconsole.log( \"txCall[%d] = %s\", JSON.stringify( txCall ) ) ;", txIndex ) ;
console.log( "\t\tvar txRequest, txResult ;" ) ;
var error = typeof txOriginal.isError !== "undefined" ? parseInt( txOriginal.isError ) : 0 ;
if( txOriginal.blockNumber >= 4370000 ) { // Since the Byzanthium hard fork take the status into account
if( error === 0 && parseInt( txOriginal.txreceipt_status ) === 0 ) {
error = 1 ;
}
}
if( error === 1 && parseInt( txOriginal.gas ) === parseInt( txOriginal.gasUsed ) ) {
console.log( "\t\ttxRequest = { receipt: { isError: 1, message: \"Original out of gas, replay skipped\" }, blockNumber: \"latest\", logs: [] } ;" ) ;
} else {
console.log( "\t\ttry {" ) ;
const txActualOptions = ( txActual.length === 0 ? "txOptions" : txActual + ", txOptions" ) ;
if( txIndex === 0 ) {
console.log( "\t\t\ttxRequest = %s.new( %s ) ;", contractName, txActualOptions ) ;
} else if( txPrototype.name === 'sendTransaction' ) {
console.log( "\t\t\ttxRequest = deployedContract.%s( %s ) ;", txPrototype.name, txActualOptions ) ;
} else {
console.log( "\t\t\ttxRequest = deployedContract.%s( %s ) ;", 'methods[ "' + txPrototype.name + '(' + txTypeList + ')" ]', txActualOptions ) ;
}
console.log( "\t\t\tawait new Promise( (resolve) => { txRequest.on( \"transactionHash\", resolve ) } ) ;" ) ;
console.log( "\t\t} catch( requestError ) {" ) ;
console.log( "\t\t\ttxRequest = { receipt: { isError: 1, message: requestError.message }, blockNumber: \"latest\", logs: [] } ;" ) ;
console.log( "\t\t}" ) ;
console.log( "\t\tawait support.mineBlockWithTimestamp( %d, %s ) ;", txIndex, txOriginal.timeStamp ) ;
}
console.log( "\t\ttry {" ) ;
console.log( "\t\t\ttxResult = await txRequest ;" ) ;
console.log( "\t\t} catch( resultError ) {" ) ;
console.log( "\t\t\ttxResult = { receipt: { isError: 1, message: resultError.message }, blockNumber: \"latest\", logs: [] } ;" ) ;
console.log( "\t\t}" ) ;
if( txIndex === 0 ) {
console.log( "\t\tif( typeof txResult.receipt !== 'undefined' ) {" ) ;
console.log( "\t\t\tconsole.log( \"txResult[%d] = %s\", JSON.stringify( txResult.receipt ) ) ;", txIndex ) ;
console.log( "\t\t\tprocess.exit( 1 ) ;" ) ;
console.log( "\t\t} else {" ) ;
console.log( "\t\t\tdeployedContract = txResult;" ) ;
console.log( "\t\t\tconst txReceipt = await web3.eth.getTransactionReceipt( deployedContract.transactionHash ) ;" ) ;
console.log( "\t\t\tconst decodedLogs = %s.decodeLogs( txReceipt.logs ) ;", contractName ) ;
console.log( "\t\t\ttxResult = { receipt: txReceipt, blockNumber: txReceipt.blockNumber, logs: decodedLogs, rawLogs: txReceipt.logs } ;" ) ;
console.log( "\t\t\tdeployedContract.address = txReceipt.contractAddress ;" ) ;
console.log( "\t\t\tconsole.log( \"contractAddress = %s\", JSON.stringify( deployedContract.address ) ) ;" ) ;
console.log( "\t\t\taddressList[%d] = deployedContract.address ;", addressThisIndex ) ;
console.log( "\t\t\tconsole.log( \"addressList = %s\", JSON.stringify( addressList ) ) ;" ) ;
console.log( "\t\t\tconst bytecode = await web3.eth.getCode( deployedContract.address ) ;" ) ;
console.log( "\t\t\tconsole.log( \"code = %s\", JSON.stringify( bytecode ) ) ;" ) ;
console.log( "\t\t\teventPrototypeList = deployedContract.abi.filter( item => item.type === \"event\" ) ;" ) ;
console.log( "\t\t\tconsole.log( \"eventPrototypeList = %s\", JSON.stringify( eventPrototypeList ) ) ;" ) ;
console.log( "\t\t\tmethodPrototypeList = deployedContract.abi.filter( item => item.constant ) ;" ) ;
console.log( "\t\t\tconsole.log( \"methodPrototypeList = %s\", JSON.stringify( methodPrototypeList ) ) ;" ) ;
console.log( "\t\t\tconsole.log( \"txResult[%d] = %s\", JSON.stringify( txResult.receipt ) ) ;", txIndex ) ;
console.log( "\t\t}" ) ;
} else {
console.log( "\t\tconsole.log( \"txResult[%d] = %s\", JSON.stringify( txResult.receipt ) ) ;", txIndex ) ;
}
const logList = await etherscanGetLogs( contractName, addressListOriginal[ 2 ], txOriginal.blockNumber, txOriginal.hash, topicListOriginal ) ;
const logListSum = logList.map( item => item.length ).reduce( ( accu, item) => accu + item, 0 ) ;
if( logListSum > 0 ) {
for( var eventIndex = 0; eventIndex < logList.length; eventIndex++ ) {
if( logList[ eventIndex ].length > 0 ) {
const encodedEventLogs = logList[ eventIndex ] ;
var eventLogs ;
try {
eventLogs = abiDecoder.decodeLogs( encodedEventLogs ) ;
} catch( error ) {
console.error( "chainsol:fatal: cannot decode event of %s at %s with topic %s (error %s)",
contractName, addressListOriginal[ 2 ], topicListOriginal[ eventIndex ], error.message ) ;
process.exit( 1 ) ;
}
if( eventLogs !== null ) {
const eventPrototypeOriginal = eventPrototypeListOriginal[ eventIndex ] ;
console.log( "\t\t%seventCallOriginal = %s ;", ( eventIndex === 0 ? "var " : "" ), codify( eventPrototypeOriginal ) ) ;
console.log( "\t\tconsole.log( \"eventCallOriginal[%d,%d] = %s\", JSON.stringify( eventCallOriginal ) ) ;", txIndex, eventIndex ) ;
console.log( "\t\t%seventResultOriginal = %s ;", ( eventIndex === 0 ? "var " : "" ), codify( eventLogs ) ) ;
console.log( "\t\tconsole.log( \"eventResultOriginal[%d,%d] = %s\", JSON.stringify( eventResultOriginal ) ) ;", txIndex, eventIndex ) ;
}
}
}
}
const fromBalanceOriginal = await etherscanBalance( contractName, txOriginal.from, txOriginal.blockNumber ) ;
console.log( "\t\tconst fromBalanceOriginal = { address: addressListOriginal[%d], balance: \"%s\" } ;", fromIndex, fromBalanceOriginal.toString( 10, 85) ) ;
console.log( "\t\tconsole.log( \"fromBalanceOriginal[%d] = %s\", JSON.stringify( fromBalanceOriginal ) ) ;", txIndex ) ;
if( txIndex !== 0 ) {
const toBalanceOriginal = await etherscanBalance( contractName, txOriginal.to, txOriginal.blockNumber ) ;
console.log( "\t\tconst toBalanceOriginal = { address: addressListOriginal[%d], balance: \"%s\" } ;", toIndex, toBalanceOriginal.toString( 10, 85) ) ;
console.log( "\t\tconsole.log( \"toBalanceOriginal[%d] = %s\", JSON.stringify( toBalanceOriginal ) ) ;", txIndex ) ;
}
console.log( "\t\tconst fromBalance = { address: addressList[%d], balance: ( await web3.eth.getBalance( addressList[%d], txResult.blockNumber ) ).toString( 10, 85) } ;", fromIndex, fromIndex ) ;
console.log( "\t\tconsole.log( \"fromBalance[%d] = %s\", JSON.stringify( fromBalance ) ) ;", txIndex ) ;
if( txIndex !== 0 ) {
console.log( "\t\tconst toBalance = { address: addressList[%d], balance: ( await web3.eth.getBalance( addressList[%d], txResult.blockNumber ) ).toString( 10, 85) } ;", toIndex, toIndex ) ;
console.log( "\t\tconsole.log( \"toBalance[%d] = %s\", JSON.stringify( toBalance) ) ;", txIndex ) ;
}
console.log( "\t\tfor( var eventIndex = 0; eventIndex < eventPrototypeList.length; eventIndex++ ) {" ) ;
console.log( "\t\t\tconst eventCall = eventPrototypeList[ eventIndex ] ;" ) ;
console.log( "\t\t\tconst eventLogs = txResult.logs.filter( item => item.event === eventCall.name && item.args.__length__ === eventCall.inputs.length ) ;" ) ;
console.log( "\t\t\tif( eventLogs.length > 0 ) {" ) ;
console.log( "\t\t\t\tconsole.log( \"eventCall[%d,%d] = %s\", eventIndex, JSON.stringify( eventCall ) ) ;", txIndex ) ;
console.log( "\t\t\t\tconsole.log( \"eventResult[%d,%d] = %s\", eventIndex, JSON.stringify( eventLogs.map( item => mergeEvent( eventCall, item.args ) ) ) ) ;", txIndex ) ;
console.log( "\t\t\t}" ) ;
console.log( "\t\t}" ) ;
console.log( "\t} ) ;" ) ;
}
// Generate the main body of the tests
async function generateTest( contractName, decodedAbiOriginal, constructorPrototypeOriginal, methodPrototypeListOriginal, eventPrototypeListOriginal, txListOriginal, addressListOriginal ) {
const contractname = contractName.toLowerCase( ) ;
console.log( "cat >test/%s.js << 'END-of-test/%s.js'", contractname, contractname ) ;
console.log( "const %s = artifacts.require( \"./%s.sol\" ) ;", contractName, contractName ) ;
console.log( "const web3Utils = require( \"web3-utils\" ) ;" ) ;