-
Notifications
You must be signed in to change notification settings - Fork 93
/
kakuna.js
1839 lines (1640 loc) · 49.3 KB
/
kakuna.js
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
BN = require('bn.js')
fs = require('fs')
utils = require('ethereumjs-util')
VM = require('ethereumjs-vm')
Web3 = require('web3')
module.exports = {kakuna: async function (contractName, preludeRaw, logging) {
vm = new VM()
web3 = new Web3()
const prelude = Buffer.from(preludeRaw.slice(2), 'hex')
const preludeSize = prelude.length
if (logging) {
console.log(`Attempting jump analysis and prelude insertion for ${contractName} contract.`)
console.log(`Prelude: ${preludeRaw} (length: ${preludeSize} bytes)`)
}
// get the bytecode of the test contract that we want to add a prelude to
const Artifact = require(`../../build/contracts/${contractName}.json`)
/* init code: checks and constructor logic, then keyword, then runtime code.
keyword: 0x61****8061****60003960f3fe (13 bytes)
# op opcode
0 61 PUSH2 0x022b // length - this will need to be increased
1 80 DUP1 // duplicated so the return can use it too
2 61 PUSH2 0x003a // offset - this will not change
3 60 PUSH1 0x00 // dest offset - runtime code at 0 in memory
4 39 CODECOPY // get the code and place it in memory
5 60 PUSH1 0x00 // return offset - runtime starting at 0
6 F3 RETURN // return runtime code from memory and deploy
also note that the PUSH2s might actually be PUSH1s, depending on the size.
*/
let initCode = Buffer.from(Artifact.bytecode.slice(2), 'hex')
// parse out the init code by each instruction.
initOps = nameOpCodes(initCode)
// find the first occurrence of the full sequence of opcodes in the keyword
const sequence = ['PUSH', 'DUP1', 'PUSH', 'PUSH', 'CODECOPY', 'PUSH', 'RETURN']
let candidate = {
sequenceStart: 0,
sequenceProgress: 0,
found: false
}
initOps.some((op, i) => {
if (op.opcode.includes(sequence[candidate.sequenceProgress])) {
candidate.sequenceProgress++
} else {
candidate.sequenceStart = i + 1
candidate.sequenceProgress = 0
}
if (candidate.sequenceProgress >= 7) {
candidate.found = true
return true
}
})
if (!candidate.found) {
throw new Error(
'No valid runtime keyword found for supplied initialization code.'
)
}
// mark the start of runtime code based on the extracted keyword.
const codeStart = parseInt(initOps[candidate.sequenceStart + 2].push.data, 16)
if (logging) {
console.log()
console.log(
'##################################################################'
)
console.log(
`runtime payload at instruction #${
candidate.sequenceStart
}: pc ${
initOps[candidate.sequenceStart].pc
}, length ${
parseInt(initOps[candidate.sequenceStart].push.data, 16)
}, offset ${
codeStart
}.`
)
console.log(initOps[candidate.sequenceStart])
console.log(
'##################################################################'
)
}
// get the initialization code without the runtime portion.
initCodeWithoutRuntime = initCode.slice(0, codeStart)
// get the runtime code and ensure that it matches the existing runtime code
let runtime = Buffer.from(Artifact.deployedBytecode.slice(2), 'hex')
extractedRuntime = initCode.slice(codeStart, initCode.length)
if (!(runtime.toString() === extractedRuntime.toString())) {
throw new Error('runtime does not match expected runtime.')
process.exit()
}
// parse out individual op instructions from runtime (remove metadata hash)
ops = nameOpCodes(Buffer.from(Artifact.deployedBytecode.slice(2, -86), 'hex'))
// include each prior instruction - used to check for adjacent PUSHes + JUMPs.
priors = [null].concat(ops.slice(0, -1))
opsAndPriors = []
ops.forEach((op, index) => {
if (priors[index] !== null) {
opsAndPriors.push({
i: index,
x: op.x,
pc: op.pc,
opcode: op.opcode,
push: {data: op.push.data},
prior: {
x: priors[index].x,
pc: priors[index].pc,
opcode: priors[index].opcode,
push: {data: priors[index].push.data}
}
})
} else {
opsAndPriors.push({
i: index,
x: op.x,
pc: op.pc,
opcode: op.opcode,
push: {data: op.push.data},
prior: null
})
}
})
// locate and index each PUSH instruction.
originalPushes = []
originalPushIndexes = {}
originalPushIndex = 0
opsAndPriors.forEach(op => {
if (op.opcode.includes('PUSH')) {
originalPushIndexes[op.pc] = originalPushIndex
originalPushes.push(op)
originalPushIndex++
}
})
// locate and index each JUMP / JUMPI instruction.
originalJumps = []
originalJumpIndexes = {}
originalJumpIndex = 0
opsAndPriors.forEach(op => {
if (op.opcode.includes('JUMP') && !op.opcode.includes('JUMPDEST')) {
originalJumpIndexes[op.pc] = originalJumpIndex
originalJumps.push(op)
originalJumpIndex++
}
})
// locate and index each JUMPDEST instruction.
originalJumpdests = []
originalJumpdestIndexes = {}
originalJumpdestIndex = 0
opsAndPriors.forEach(op => {
if (op.opcode.includes('JUMPDEST')) {
originalJumpdestIndexes[op.pc] = originalJumpdestIndex
originalJumpdests.push(op)
originalJumpdestIndex++
}
})
// construct a more detailed set of instructions with contextual information.
opsAndJumps = []
opsAndPriors.forEach(op => {
if (op.opcode.includes("JUMP")) {
if (op.opcode.includes("DEST")) {
opsAndJumps.push({
i: op.i,
x: op.x,
pc: op.pc,
opcode: op.opcode,
push: {data: op.push.data},
prior: op.prior,
jump: null,
jumpdest: {
index: originalJumpdestIndexes[op.pc]
}
})
} else {
opsAndJumps.push({
i: op.i,
x: op.x,
pc: op.pc,
opcode: op.opcode,
push: {data: op.push.data},
prior: op.prior,
jump: {
index: originalJumpIndexes[op.pc]
},
jumpdest: null
})
}
} else if (op.opcode.includes("PUSH")) {
opsAndJumps.push({
i: op.i,
x: op.x,
pc: op.pc,
opcode: op.opcode,
push: {index: originalPushIndexes[op.pc], data: op.push.data, dataBaseTen: parseInt(op.push.data, 16)},
prior: op.prior,
jump: null,
jumpdest: null
})
} else {
opsAndJumps.push({
i: op.i,
x: op.x,
pc: op.pc,
opcode: op.opcode,
push: {data: op.push.data, dataBaseTen: parseInt(op.push.data, 16)},
prior: op.prior,
jump: null,
jumpdest: null
})
}
})
// create a mapping from each program counter to each instruction index.
instructions = {}
opsAndJumps.forEach(op => {
instructions[op.pc] = op.i
})
// create a new instance of a Stack class.
stack = new Stack()
// create a new instance of a Counter class.
counter = new Counter()
// track which code branches have already been run (circular references)
completedOneBranches = {}
completedZeroBranches = {}
// run through code & build up modified stack until halt or breaker is tripped
breaker = 0
function run(fork, currentStack, counter) {
while (!counter.stopped && breaker < 10000) {
var op = opsAndJumps[counter.instruction];
var stackSize = currentStack.length
// make sure the opcode is included in opFns
if (!op.opcode in opFns) {
console.log('DEBUG:', op.opcode)
throw new Error('Missing opcode')
}
// update CODECOPY in the event that the offset stack item is known
if (
op.opcode === 'CODECOPY' &&
currentStack._store[currentStack.length - 2].constant === true
) {
opsAndJumps[counter.instruction].codecopy = {
constant: true,
origin: currentStack._store[currentStack.length - 2].origin,
codeOffset: currentStack._store[currentStack.length - 2].item,
duplicated: currentStack._store[currentStack.length - 2].duplicated
}
}
// strip out number from PUSH / DUP / SWAP / LOG, will be added back later
if (
op.opcode.includes("PUSH") ||
op.opcode.includes("DUP") ||
op.opcode.includes("SWAP") ||
op.opcode.includes("LOG")
) {
// execute the instruction
opFns[op.opcode.slice(
0,
(
op.opcode.includes("DUP") ||
op.opcode.includes("LOG")
) ? 3 : 4
)](op, currentStack, counter)
// ensure that the stack size is still OK
if (stackSize + stackDelta(op) !== currentStack.length) {
console.log('DEBUG:', op, stackSize, stackDelta(op), currentStack.length)
throw new Error('unexpected stack size change!')
}
// For JUMPI: if condition is unknown, fork and take both possible paths
} else if (
op.opcode === 'JUMPI' &&
currentStack._store[currentStack.length - 2].constant === false
) {
// clone the stack for use in the fork
var clone = Object.assign(
Object.create(Object.getPrototypeOf(currentStack)),
currentStack
)
clone._store = clone._store.slice(0)
// clone the counter too
var c = Object.assign(Object.create(Object.getPrototypeOf(counter)), counter)
// set the condition to True
clone._store[clone.length - 2] = {
constant: true,
item: new BN(1)
}
// designate a key based on the stack and the jump location
var key = JSON.stringify({i: op.jump.index, s: clone._store.slice(0).map(x => {return {c: x.constant, d: x.duplicated}})})
// only perform fork if stack has changed & hasn't already forked a lot
if (completedOneBranches[key] !== true && fork < 30) {
// recursive call, then record that truthy has been tried for stack
run(fork + 1, clone, c)
completedOneBranches[key] = true
}
// now set the condition to false in the old stack and proceed as normal
currentStack._store[currentStack.length - 2] = {
constant: true,
item: new BN(0)
}
// execute instruction & record that not-truthy has been tried for stack
opFns[op.opcode](op, currentStack, counter)
completedZeroBranches[op.jump.index] = true // not using this yet :)
// ensure that the stack size is still OK
if (stackSize + stackDelta(op) !== currentStack.length) {
console.log('DEBUG:', op, stackSize, stackDelta(op), currentStack.length)
throw new Error('unexpected stack size change!')
}
// if none of the above applies, just keep going through the opcodes
} else {
// execute instruction
opFns[op.opcode](op, currentStack, counter)
// ensure that the stack size is still OK
if (stackSize + stackDelta(op) !== currentStack.length) {
console.log('DEBUG:', op, stackSize, stackDelta(op), currentStack.length)
throw new Error('unexpected stack size change!')
}
}
// increment the counter and breaker, stopping if we reach the end
counter.increment()
if (counter.instruction >= opsAndJumps.length) {
counter.stop()
}
breaker++
}
}
// kick off run to start populating modified stack and search for stack items
run(0, stack, counter)
// TODO: work BACKWARDS from each remaining problem, looking for the PUSH
// (basically, all the routes through the code might not be located)
// last-ditch attempt in case only basic static jumps remain
opsAndJumps.forEach(op => {
if (
op.opcode.includes('JUMP') &&
!op.opcode.includes('DEST') &&
!op.jump.origins &&
op.prior.opcode.includes('PUSH')
) {
op.jump.origins = [{
index: originalPushIndexes[op.prior.pc],
pc: op.prior.pc,
static: true,
duplicated: false
}]
op.jump.dests = [{
index: originalJumpdestIndexes[parseInt(op.prior.push.data, 16)],
pc: parseInt(op.prior.push.data, 16)
}]
}
})
// build up an updated group of jumps, identifying any remaining problems
jumps = []
if (logging) {
console.log()
console.log(
'************* PUSH ************* '+
' ************ JUMP ************ '+
' ********** JUMPDEST **********'
)
}
opsAndJumps.forEach(op => {
if (op.opcode.includes('JUMP') && !op.opcode.includes('DEST')) {
if (op.jump.origins) {
if (logging) {
// don't mind the mess :D
console.log(
`${op.jump.origins.map(x => `${x.index} (pc ${x.pc}: ${
originalPushes[x.index].opcode
} 0x${originalPushes[x.index].push.data}${
x.duplicated ? ", DUP'd!" : ''})`).join(', ')
} \t=>\t ${op.jump.index} (pc ${op.pc}: ${op.opcode
}) \t=>\t${op.jump.dests.map(
x => `${x.index} (pc ${x.pc}: JUMPDEST)`
)}`
)
}
jumps.push({
problem: false,
index: op.jump.index,
pc: op.pc,
origins: op.jump.origins,
dests: op.jump.dests
})
} else {
if (logging) {
console.log('PROBLEM:', op.jump.index, op)
}
jumps.push({
problem: true,
index: op.jump.index,
pc: op.pc,
origins: [],
dests: []
})
}
}
})
// do the same for codecopies
codecopies = []
if (logging) {
console.log()
console.log(
'************* PUSH ************* '+
' ******************** CODECOPY ********************'
)
}
codecopyIndex = 0
opsAndJumps.forEach(op => {
if (op.opcode === 'CODECOPY') {
if (op.codecopy && op.codecopy.constant === true && op.codecopy.origin) {
const originIndex = originalPushIndexes[op.codecopy.origin]
let origin = originalPushes[originIndex]
origin.duplicated = op.codecopy.duplicated
if (logging) {
// can't be bothered to clean up...
console.log(
`${originIndex} (pc ${origin.pc}: ${origin.opcode} 0x${
origin.push.data}${origin.duplicated ? ", DUP'd!" : ''
}) \t=>\t ${codecopyIndex} (pc ${op.pc}: ${
op.opcode
} <code offset ${op.codecopy.codeOffset.toString()}>)`)
}
codecopies.push({
problem: false,
op: op
})
} else {
if (logging) {
console.log(
`???????????????????????????????????????\t=>\t ${
codecopyIndex
} (pc ${op.pc}: ${op.opcode} <code offset unknown>)`
)
}
codecopies.push({
problem: true,
op: op
})
}
codecopyIndex++
}
})
if (logging) {
console.log()
}
// sanity check for jumps
opsAndJumps.forEach(op => {
if (
op.opcode.includes('JUMP') &&
!op.opcode.includes('DEST') && (
typeof op.jump.origins === 'undefined' ||
op.jump.origins.some(o => o.static === false)
)) {
if (logging) {
console.log(op)
}
throw new Error("cannot assign a specific push to each jump.")
}
})
// Increase each PUSH to a JUMPDEST in runtime code by length of prelude
let jumpPushSize = null;
jumps.forEach(jump => {
if (!(jump.problem === false)) {
throw new Error('cannot adjust problematic push used to jump.')
}
jump.origins.forEach((origin, index) => {
if (!(origin.static === true)) {
throw new Error('only static pushes are supported for now.')
}
if (!(origin.duplicated === false)) {
throw new Error('only unduplicated pushes are supported for now.')
}
// get the relevant instruction so that we can parse out the data field
let pushInstruction = opsAndJumps[instructions[origin.pc]]
// find out if it's a PUSH1 or PUSH2 and adjust accordingly
let pushSize = 0
if (pushInstruction.opcode === 'PUSH1') {
pushSize = 1
if (jumpPushSize === null) {
jumpPushSize = 1
}
} else if (pushInstruction.opcode === 'PUSH2') {
pushSize = 2
if (jumpPushSize === null) {
jumpPushSize = 2
}
}
if (pushSize === 0) {
throw new Error('only PUSH1 and PUSH2 opcodes are supported for now.')
}
if (jumpPushSize !== pushSize) {
throw new Error('size of PUSH opcodes must be consistent.')
}
// modify the relevant runtime code (TODO: ensure it doesn't overflow!)
let modified = Buffer.from(
(
runtime.slice(
pushInstruction.pc + 1,
pushInstruction.pc + 1 + pushSize
).readUIntBE(0, pushSize) + preludeSize
).toString(16).padStart(2 * pushSize, '0'),
'hex'
)
// update the runtime with the new modified code
let runtimeSegments = [
runtime.slice(0, pushInstruction.pc + 1),
modified,
runtime.slice(pushInstruction.pc + 1 + pushSize)
];
runtime = Buffer.concat(runtimeSegments);
})
})
// Increase each PUSH to a CODECOPY offset in runtime code by prelude length
let codecopyPushSize = null;
codecopies.forEach(codecopy => {
if (!(codecopy.problem === false)) {
throw new Error('cannot adjust problematic codecopy offset.')
}
// get the relevant instruction so that we can parse out the data field
let pushInstruction = opsAndJumps[instructions[codecopy.op.codecopy.origin]]
// find out if it's a PUSH1 or PUSH2 and adjust accordingly
let pushSize = 0
if (pushInstruction.opcode === 'PUSH1') {
pushSize = 1
if (codecopyPushSize === null) {
codecopyPushSize = 1
}
} else if (pushInstruction.opcode === 'PUSH2') {
pushSize = 2
if (codecopyPushSize === null) {
codecopyPushSize = 2
}
}
if (pushSize === 0) {
throw new Error('only PUSH1 and PUSH2 opcodes are supported for now.')
}
if (codecopyPushSize !== pushSize) {
throw new Error('size of PUSH opcodes must be consistent.')
}
// modify the relevant runtime code (TODO: ensure it doesn't overflow!)
let modified = Buffer.from(
(
runtime.slice(
pushInstruction.pc + 1,
pushInstruction.pc + 1 + pushSize
).readUIntBE(0, pushSize) + preludeSize
).toString(16).padStart(2 * pushSize, '0'),
'hex'
)
// update the runtime with the new modified code
let runtimeSegments = [
runtime.slice(0, pushInstruction.pc + 1),
modified,
runtime.slice(pushInstruction.pc + 1 + pushSize)
];
runtime = Buffer.concat(runtimeSegments);
})
// Increase PUSH to CODECOPY length & RETURN in init code by prelude length
let pushSize = 0
if (initOps[candidate.sequenceStart].opcode === 'PUSH1') {
pushSize = 1
} else if (initOps[candidate.sequenceStart].opcode === 'PUSH2') {
pushSize = 2
}
if (pushSize === 0) {
throw new Error('only PUSH1 and PUSH2 opcodes are supported for now.')
}
runtimeLength = initOps[candidate.sequenceStart].pc
// modify the relevant runtime code (TODO: ensure it doesn't overflow!)
const modified = Buffer.from(
(
initCodeWithoutRuntime.slice(
runtimeLength + 1,
runtimeLength + 1 + pushSize
).readUIntBE(0, pushSize) + preludeSize
).toString(16).padStart(2 * pushSize, '0'),
'hex'
)
// update the init code with the new modified length
var initSegments = [
initCodeWithoutRuntime.slice(0, runtimeLength + 1),
modified,
initCodeWithoutRuntime.slice(runtimeLength + 1 + pushSize)
];
var updatedInitCode = Buffer.concat(initSegments);
// concatenate new init code, prelude, and runtime code to get final init code
var finalSegments = [updatedInitCode, prelude, runtime];
var final = Buffer.concat(finalSegments);
// get the final runtime code too
var finalRuntimeSegments = [prelude, runtime];
var finalRuntime = Buffer.concat(finalRuntimeSegments);
// make the kakuna build directory if it doesn't currently exist
if (!fs.existsSync('build/kakuna')) {
fs.mkdir('build/kakuna', { recursive: true }, (err) => {
if (err) throw err;
});
}
// write new init code and runtime code to a file (along with some metadata)
const out = JSON.stringify({
contractName: contractName,
prelude: preludeRaw,
preludeSize: preludeSize,
bytecode: '0x' + final.toString('hex'),
deployedBytecode: '0x' + finalRuntime.toString('hex')
}, null, 2)
fs.writeFileSync(`build/kakuna/${contractName}.json`, out, {flag: 'w'})
// Wow, it actually worked! Return kakuna'd initialization code & runtime code
return ['0x' + final.toString('hex'), '0x' + finalRuntime.toString('hex')]
}}
/**
* Modified implementation of the stack used in evm, where values are objects
* rather than BN values. This is so we can deal with unknown stack items and
* track whether the items are ever duplicated.
*/
class Stack {
constructor () {
this._store = []
}
get length () {
return this._store.length
}
push (value) {
if (this._store.length > 1023) {
throw new Error("stack overflow")
}
if (!this._isValidValue(value)) {
throw new Error("out of range")
}
if (value.duplicated !== true) {
value.duplicated = false
}
this._store.push(value) // assign each {constant: false} a unique ID?
}
pop () {
if (this._store.length < 1) {
throw new Error("stack underflow")
}
return this._store.pop()
}
/**
* Pop multiple items from stack. Top of stack is first item
* in returned array.
* @param {Number} num - Number of items to pop
* @returns {Array}
*/
popN (num = 1) {
if (this._store.length < num) {
throw new Error("stack underflow")
}
if (num === 0) {
return []
}
return this._store.splice(-1 * num).reverse()
}
/**
* Swap top of stack with an item in the stack.
* @param {Number} position - Index of item from top of the stack (0-indexed)
*/
swap (position) {
if (this._store.length <= position) {
throw new Error("stack underflow")
}
const head = this._store.length - 1
const i = this._store.length - position - 1
const tmp = this._store[head]
this._store[head] = this._store[i]
this._store[i] = tmp
}
/**
* Pushes a copy of an item in the stack.
* @param {Number} position - Index of item to be copied (1-indexed)
*/
dup (position) {
if (this._store.length < position) {
throw new Error("stack underflow")
}
const i = this._store.length - position
this._store[i].duplicated = true
this.push(this._store[i])
}
_isValidValue (value) {
if (BN.isBN(value.item)) {
if (value.item.lte(utils.MAX_INTEGER)) {
return true
}
} else if (Buffer.isBuffer(value.item)) {
if (value.item.length <= 32) {
return true
}
}
return !value.constant
}
}
// used to track the program counter and whether execution has halted.
class Counter {
constructor () {
this.instruction = 0
this.stopped = false
}
jump (value) {
this.instruction = value
}
increment () {
this.instruction++
}
stop() {
this.stopped = true
}
}
// the functions that will operate on our modified stack for each opcode.
opFns = {
JUMP: function (op, stack, counter) {
let dest = stack.pop()
// this means we found a jump constant.
if (dest.constant && dest.origin) {
if (
typeof opsAndJumps[op.i].jump.dests === 'undefined' &&
typeof opsAndJumps[op.i].jump.origins === 'undefined'
) {
opsAndJumps[op.i].jump.dests = [{
index: originalJumpdestIndexes[dest.item.toNumber()],
pc: dest.item.toNumber()
}]
opsAndJumps[op.i].jump.origins = [{
index: originalPushIndexes[dest.origin],
pc: dest.origin,
static: true,
duplicated: dest.duplicated
}]
} else {
const jumpdest = {
index: originalJumpdestIndexes[dest.item.toNumber()],
pc: dest.item.toNumber()
}
const origin = {
index: originalPushIndexes[dest.origin],
pc: dest.origin,
static: true,
duplicated: dest.duplicated
}
if (
!(opsAndJumps[op.i].jump.dests
.map(x => x.pc)
.includes(jumpdest.pc)) &&
!(opsAndJumps[op.i].jump.origins
.map(x => x.pc)
.includes(origin.pc))
) {
opsAndJumps[op.i].jump.dests.push(jumpdest)
opsAndJumps[op.i].jump.origins.push(origin)
}
}
// determine what instruction # the pc points to (ie no counting pushData)
newInstruction = instructions[dest.item.toNumber()]
// check that it points to a jumpdest
if (opsAndJumps[newInstruction].opcode !== 'JUMPDEST') {
throw new Error('selected jump does not point to a jumpdest.')
}
// alter instruction
counter.jump(newInstruction)
} else {
console.log('DEBUG:', op, stack, counter)
throw new Error('jump does not have a constant')
}
},
JUMPI: function (op, stack, counter) {
let [dest, cond] = stack.popN(2)
// this means we found a jumpi constant.
if (dest.constant) {
if (
typeof opsAndJumps[op.i].jump.dests === 'undefined' &&
typeof opsAndJumps[op.i].jump.origins === 'undefined'
) {
opsAndJumps[op.i].jump.dests = [{
index: originalJumpdestIndexes[dest.item.toNumber()],
pc: dest.item.toNumber()
}]
opsAndJumps[op.i].jump.origins = [{
index: originalPushIndexes[dest.origin],
pc: dest.origin,
static: true,
duplicated: dest.duplicated
}]
} else {
const jumpdest = {
index: originalJumpdestIndexes[dest.item.toNumber()],
pc: dest.item.toNumber()
}
const origin = {
index: originalPushIndexes[dest.origin],
pc: dest.origin,
static: true,
duplicated: dest.duplicated
}
if (
!(opsAndJumps[op.i].jump.dests
.map(x => x.pc)
.includes(jumpdest.pc)) &&
!(opsAndJumps[op.i].jump.origins
.map(x => x.pc)
.includes(origin.pc))
) {
opsAndJumps[op.i].jump.dests.push(jumpdest)
opsAndJumps[op.i].jump.origins.push(origin)
}
}
} else {
console.log('DEBUG:', op, stack, counter)
throw new Error('jumpi does not have a constant')
}
if (!cond.constant) {
throw new Error('cannot pass a non-constant as a JUMPI condition')
}
if (dest.constant && cond.constant && !cond.item.isZero()) {
// determine what instruction # the pc points to (ie no counting pushData)
newInstruction = instructions[dest.item.toNumber().toString()]
// check that it points to a jumpdest
if (opsAndJumps[newInstruction].opcode !== 'JUMPDEST') {
throw new Error('selected jump does not point to a jumpdest.')
}
// alter instruction
counter.jump(newInstruction)
}
},
JUMPDEST: function (op, stack, counter) {},
CODECOPY: function (op, stack, counter) {
// this could be used as constants - requires working with memory
let [memOffset, codeOffset, dataLength] = stack.popN(3)
},
POP: function (op, stack, counter) {
stack.pop()
},
PUSH: function (op, stack, counter) {
stack.push({constant: true, item: web3.utils.toBN('0x' + op.push.data), origin: op.pc})
},
DUP: function (op, stack, counter) {
const stackPos = op.x - 127
stack.dup(op.x - 127)
},
SWAP: function (op, stack, counter) {
stack.swap(op.x - 143)
},
PC: function (op, stack, counter) {
stack.push({constant: false}) // could set to true (op.pc) and transform?
},
MSIZE: function (op, stack, counter) {
stack.push({constant: false})
},
STOP: function (op, stack, counter) {
counter.stop()
},
ADD: function (op, stack, counter) {
const [a, b] = stack.popN(2)
let r
if (a.constant && b.constant) {
r = {constant: true, item: a.item.add(b.item).mod(utils.TWO_POW256)}
} else {
r = {constant: false}
}
stack.push(r)
},
MUL: function (op, stack, counter) {
const [a, b] = stack.popN(2)
let r
if (a.constant && b.constant) {
r = {constant: true, item: a.item.mul(b.item).mod(utils.TWO_POW256)}
} else {
r = {constant: false}
}
stack.push(r)
},
SUB: function (op, stack, counter) {
const [a, b] = stack.popN(2)
let r
if (a.constant && b.constant) {
r = {constant: true, item: a.item.sub(b.item).toTwos(256)}
} else {
r = {constant: false}
}
stack.push(r)
},
DIV: function (op, stack, counter) {
const [a, b] = stack.popN(2)
let r
if (b.constant && b.item.isZero()) {
r = {constant: true, item: new BN(b.item)}
} else if (a.constant && b.constant) {
r = {constant: true, item: a.item.div(b.item)}
} else {
r = {constant: false}
}
stack.push(r)
},
SDIV: function (op, stack, counter) {
let [a, b] = stack.popN(2)
let r
if (b.constant && b.item.isZero()) {
r = {constant: true, item: new BN(b.item)}
} else if (a.constant && b.constant) {