-
Notifications
You must be signed in to change notification settings - Fork 10
/
EVMimports.js
702 lines (600 loc) · 22 KB
/
EVMimports.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
/**
* This is the Ethereum interface that is exposed to the WASM instance which
* enables to interact with the Ethereum Environment
*/
const fs = require('fs')
const path = require('path')
const ethUtil = require('ethereumjs-util')
const U256 = require('./deps/u256.js')
const U128_SIZE_BYTES = 16
const ADDRESS_SIZE_BYTES = 20
const U256_SIZE_BYTES = 32
const log = require('loglevel')
log.setLevel('warn') // hide logs
// log.setLevel('debug') // for debugging
// The interface exposed to the WebAessembly Core
module.exports = class Interface {
constructor (kernel) {
this.kernel = kernel
const shimBin = fs.readFileSync(path.join(__dirname, '/wasm/interface.wasm'))
const shimMod = WebAssembly.Module(shimBin)
this.shims = WebAssembly.Instance(shimMod, {
'interface': {
'useGas': this._useGas.bind(this),
'getGasLeftHigh': this._getGasLeftHigh.bind(this),
'getGasLeftLow': this._getGasLeftLow.bind(this),
'call': this._call.bind(this)
}
})
}
static get name () {
return 'ethereum'
}
get exports () {
let exportMethods = [
// include all the public methods according to the Ethereum Environment Interface (EEI) r1
'getAddress',
'getBalance',
'getTxOrigin',
'getCaller',
'getCallValue',
'getCallDataSize',
'callDataCopy',
'callDataCopy256',
'getCodeSize',
'codeCopy',
'getExternalCodeSize',
'externalCodeCopy',
'getTxGasPrice',
'getBlockHash',
'getBlockCoinbase',
'getBlockTimestamp',
'getBlockNumber',
'getBlockDifficulty',
'getBlockGasLimit',
'log',
'create',
'callCode',
'callDelegate',
'storageStore',
'storageLoad',
'return',
'selfDestruct'
]
let ret = {}
exportMethods.forEach((method) => {
ret[method] = this[method].bind(this)
})
// add shims
ret.useGas = this.shims.exports.useGas
ret.getGasLeft = this.shims.exports.getGasLeft
ret.call = this.shims.exports.call
return ret
}
setModule (mod) {
this.module = mod
}
/**
* Subtracts an amount to the gas counter
* @param {integer} amount the amount to subtract to the gas counter
*/
_useGas (high, low) {
this.takeGas(from64bit(high, low))
}
/**
* Returns the current amount of gas
* @return {integer}
*/
_getGasLeftHigh () {
return Math.floor(this.kernel.environment.gasLeft / 4294967296)
}
/**
* Returns the current amount of gas
* @return {integer}
*/
_getGasLeftLow () {
return this.kernel.environment.gasLeft
}
/**
* Gets address of currently executing account and loads it into memory at
* the given offset.
* @param {integer} offset
*/
getAddress (offset) {
log.debug('EVMImports.js getAddress')
this.takeGas(2)
this.setMemory(offset, ADDRESS_SIZE_BYTES, this.kernel.environment.address.toMemory())
}
/**
* Gets balance of the given account and loads it into memory at the given
* offset.
* @param {integer} addressOffset the memory offset to laod the address
* @param {integer} resultOffset
*/
getBalance (addressOffset, offset, cbIndex) {
log.debug('EVMImports.js getBalance')
this.takeGas(20)
const address = this.getMemory(addressOffset, ADDRESS_SIZE_BYTES)
const addressHex = '0x' + Buffer.from(address).toString('hex')
let balance
if (this.kernel.environment.state.hasOwnProperty(addressHex)) {
balance = this.kernel.environment.state[addressHex].balance
} else {
balance = '0x0'
}
const balanceU256 = new U256(balance)
const opPromise = Promise.resolve(balanceU256)
this.kernel.pushOpsQueue(opPromise, cbIndex, balance => {
this.setMemory(offset, U128_SIZE_BYTES, balance.toMemory(U128_SIZE_BYTES))
})
}
/**
* Gets the execution's origination address and loads it into memory at the
* given offset. This is the sender of original transaction; it is never an
* account with non-empty associated code.
* @param {integer} offset
*/
getTxOrigin (offset) {
log.debug('EVMImports.js getTxOrigin')
this.takeGas(2)
this.setMemory(offset, ADDRESS_SIZE_BYTES, this.kernel.environment.origin.toMemory())
}
/**
* Gets caller address and loads it into memory at the given offset. This is
* the address of the account that is directly responsible for this execution.
* @param {integer} offset
*/
getCaller (offset) {
log.debug('EVMImports.js getCaller')
this.takeGas(2)
this.setMemory(offset, ADDRESS_SIZE_BYTES, this.kernel.environment.caller.toMemory())
}
/**
* Gets the deposited value by the instruction/transaction responsible for
* this execution and loads it into memory at the given location.
* @param {integer} offset
*/
getCallValue (offset) {
log.debug('EVMImports.js getCallValue')
this.takeGas(2)
this.setMemory(offset, U128_SIZE_BYTES, this.kernel.environment.callValue.toMemory(U128_SIZE_BYTES))
}
/**
* Get size of input data in current environment. This pertains to the input
* data passed with the message call instruction or transaction.
* @return {integer}
*/
getCallDataSize () {
log.debug('EVMImports.js getCallDataSize')
this.takeGas(2)
return this.kernel.environment.callData.length
}
/**
* Copys the input data in current environment to memory. This pertains to
* the input data passed with the message call instruction or transaction.
* @param {integer} offset the offset in memory to load into
* @param {integer} dataOffset the offset in the input data
* @param {integer} length the length of data to copy
*/
callDataCopy (offset, dataOffset, length) {
log.debug('EVMImports.js callDataCopy')
this.takeGas(3 + Math.ceil(length / 32) * 3)
if (length) {
const callData = this.kernel.environment.callData.slice(dataOffset, dataOffset + length)
this.setMemory(offset, length, callData)
}
}
/**
* Copys the input data in current environment to memory. This pertains to
* the input data passed with the message call instruction or transaction.
* @param {integer} offset the offset in memory to load into
* @param {integer} dataOffset the offset in the input data
*/
callDataCopy256 (offset, dataOffset) {
log.debug('EVMImports.js callDataCopy256')
this.takeGas(3)
const callData = this.kernel.environment.callData.slice(dataOffset, dataOffset + 32)
this.setMemory(offset, U256_SIZE_BYTES, callData)
}
/**
* Gets the size of code running in current environment.
* @return {interger}
*/
getCodeSize (cbIndex) {
log.debug('EVMImports.js getCodeSize')
this.takeGas(2)
const opPromise = Promise.resolve(this.kernel.environment.code.length)
// wait for all the prevouse async ops to finish before running the callback
this.kernel.pushOpsQueue(opPromise, cbIndex, length => length)
}
/**
* Copys the code running in current environment to memory.
* @param {integer} offset the memory offset
* @param {integer} codeOffset the code offset
* @param {integer} length the length of code to copy
*/
codeCopy (resultOffset, codeOffset, length, cbIndex) {
log.debug('EVMimports.js codeCopy')
this.takeGas(3 + Math.ceil(length / 32) * 3)
const contextAccount = this.kernel.environment.address
let addressCode = Buffer.from([])
let codeCopied = Buffer.from([])
if (length) {
if (this.kernel.environment.state[contextAccount]) {
const hexCode = this.kernel.environment.state[contextAccount].code.slice(2)
addressCode = Buffer.from(hexCode, 'hex')
codeCopied = addressCode.slice(codeOffset, codeOffset + length)
}
}
const opPromise = Promise.resolve(codeCopied)
// wait for all the prevouse async ops to finish before running the callback
this.kernel.pushOpsQueue(opPromise, cbIndex, code => {
if (code.length) {
this.setMemory(resultOffset, length, code)
}
})
}
/**
* Get size of an account’s code.
* @param {integer} addressOffset the offset in memory to load the address from
* @return {integer}
*/
getExternalCodeSize (addressOffset, cbOffset) {
log.debug('EVMImports.js getExternalCodeSize')
this.takeGas(20)
const address = this.getMemory(addressOffset, ADDRESS_SIZE_BYTES)
const addressHex = '0x' + Buffer.from(address).toString('hex')
let addressCode = []
if (this.kernel.environment.state[addressHex]) {
const hexCode = this.kernel.environment.state[addressHex].code.slice(2)
addressCode = Buffer.from(hexCode, 'hex')
}
const opPromise = Promise.resolve(addressCode.length)
// wait for all the prevouse async ops to finish before running the callback
this.kernel.pushOpsQueue(opPromise, cbOffset, length => length)
}
/**
* Copys the code of an account to memory.
* @param {integer} addressOffset the memory offset of the address
* @param {integer} resultOffset the memory offset
* @param {integer} codeOffset the code offset
* @param {integer} length the length of code to copy
*/
externalCodeCopy (addressOffset, resultOffset, codeOffset, length, cbIndex) {
log.debug('EVMImports.js externalCodeCopy')
this.takeGas(20 + Math.ceil(length / 32) * 3)
const address = this.getMemory(addressOffset, ADDRESS_SIZE_BYTES)
const addressHex = '0x' + Buffer.from(address).toString('hex')
let addressCode = Buffer.from([])
if (length) {
if (this.kernel.environment.state[addressHex]) {
const hexCode = this.kernel.environment.state[addressHex].code.slice(2)
addressCode = Buffer.from(hexCode, 'hex')
}
}
let opPromise = Promise.resolve(addressCode)
// wait for all the prevouse async ops to finish before running the callback
this.kernel.pushOpsQueue(opPromise, cbIndex, code => {
if (code.length) {
code = code.slice(codeOffset, codeOffset + length)
this.setMemory(resultOffset, length, code)
}
})
}
/**
* Gets price of gas in current environment.
* @return {integer}
*/
getTxGasPrice () {
log.debug('EVMImports.js getTxGasPrice')
this.takeGas(2)
return this.kernel.environment.gasPrice
}
/**
* Gets the hash of one of the 256 most recent complete blocks.
* @param {integer} number which block to load
* @param {integer} offset the offset to load the hash into
*/
getBlockHash (number, offset, cbOffset) {
log.debug('EVMImports.js getBlockHash')
this.takeGas(20)
const diff = this.kernel.environment.block.number - number
let opPromise
if (diff > 256 || diff <= 0) {
opPromise = Promise.resolve(new U256(0))
} else {
opPromise = this.kernel.environment.getBlockHash(number)
}
// wait for all the prevouse async ops to finish before running the callback
this.kernel.pushOpsQueue(opPromise, cbOffset, hash => {
this.setMemory(offset, U256_SIZE_BYTES, hash.toMemory())
})
}
/**
* Gets the block’s beneficiary address and loads into memory.
* @param offset
*/
getBlockCoinbase (offset) {
log.debug('EVMImports.js getBlockCoinbase')
this.takeGas(2)
this.setMemory(offset, ADDRESS_SIZE_BYTES, this.kernel.environment.coinbase.toMemory())
}
/**
* Get the block’s timestamp.
* @return {integer}
*/
getBlockTimestamp () {
log.debug('EVMImports.js getBlockTimestamp')
this.takeGas(2)
return this.kernel.environment.block.timestamp
}
/**
* Get the block’s number.
* @return {integer}
*/
getBlockNumber () {
log.debug('EVMImports.js getBlockNumber')
this.takeGas(2)
return this.kernel.environment.block.number
}
/**
* Get the block’s difficulty.
* @return {integer}
*/
getBlockDifficulty (offset) {
log.debug('EVMImports.js getBlockDifficulty')
this.takeGas(2)
this.setMemory(offset, U256_SIZE_BYTES, this.kernel.environment.block.difficulty.toMemory())
}
/**
* Get the block’s gas limit.
* @return {integer}
*/
getBlockGasLimit () {
log.debug('EVMImports.js getBlockGasLimit')
this.takeGas(2)
return this.kernel.environment.block.gasLimit
}
/**
* Creates a new log in the current environment
* @param {integer} dataOffset the offset in memory to load the memory
* @param {integer} length the data length
* @param {integer} number of topics
*/
log (dataOffset, length, numberOfTopics, topic1, topic2, topic3, topic4) {
log.debug('EVMImports.js log')
if (numberOfTopics < 0 || numberOfTopics > 4) {
throw new Error('Invalid numberOfTopics')
}
this.takeGas(375 + length * 8 + numberOfTopics * 375)
const data = length ? this.getMemory(dataOffset, length).slice(0) : new Uint8Array([])
const topics = []
if (numberOfTopics > 0) {
topics.push(U256.fromMemory(this.getMemory(topic1, U256_SIZE_BYTES)))
}
if (numberOfTopics > 1) {
topics.push(U256.fromMemory(this.getMemory(topic2, U256_SIZE_BYTES)))
}
if (numberOfTopics > 2) {
topics.push(U256.fromMemory(this.getMemory(topic3, U256_SIZE_BYTES)))
}
if (numberOfTopics > 3) {
topics.push(U256.fromMemory(this.getMemory(topic4, U256_SIZE_BYTES)))
}
this.kernel.environment.logs.push({
data: data,
topics: topics
})
}
/**
* Creates a new contract with a given value.
* @param {integer} valueOffset the offset in memory to the value from
* @param {integer} dataOffset the offset to load the code for the new contract from
* @param {integer} length the data length
* @param (integer} resultOffset the offset to write the new contract address to
* @return {integer} Return 1 or 0 depending on if the VM trapped on the message or not
*/
create (valueOffset, dataOffset, length, resultOffset, cbIndex) {
log.debug('EVMImports.js create')
this.takeGas(32000)
const value = U256.fromMemory(this.getMemory(valueOffset, U128_SIZE_BYTES))
// if (length) {
// const code = this.getMemory(dataOffset, length).slice(0)
// }
let opPromise
if (value.gt(this.kernel.environment.value)) {
opPromise = Promise.resolve(Buffer.alloc(20))
} else {
// todo actully run the code
opPromise = Promise.resolve(ethUtil.generateAddress(this.kernel.environment.address, this.kernel.environment.nonce))
}
// wait for all the prevouse async ops to finish before running the callback
this.kernel.pushOpsQueue(opPromise, cbIndex, address => {
this.setMemory(resultOffset, ADDRESS_SIZE_BYTES, address)
})
}
/**
* Sends a message with arbiatary data to a given address path
* @param {integer} addressOffset the offset to load the address path from
* @param {integer} valueOffset the offset to load the value from
* @param {integer} dataOffset the offset to load data from
* @param {integer} dataLength the length of data
* @param {integer} resultOffset the offset to store the result data at
* @param {integer} resultLength
* @param {integer} gas
* @return {integer} Returns 1 or 0 depending on if the VM trapped on the message or not
*/
_call (gasHigh, gasLow, addressOffset, valueOffset, dataOffset, dataLength, resultOffset, resultLength, cbIndex) {
log.debug('EVMimports.js _call')
this.takeGas(40)
const gas = from64bit(gasHigh, gasLow)
// Load the params from mem
// const toAddress = [...this.getMemory(addressOffset, ADDRESS_SIZE_BYTES)]
const value = new U256(this.getMemory(valueOffset, U128_SIZE_BYTES))
// Special case for non-zero value; why does this exist?
if (!value.isZero()) {
this.takeGas(9000 - 2300 + gas)
this.takeGas(-gas)
}
const opPromise = Promise.resolve(0)
// wait for all the prevouse async ops to finish before running the callback
this.kernel.pushOpsQueue(opPromise, cbIndex, () => {
return 1
})
}
/**
* Message-call into this account with an alternative account’s code.
* @param {integer} addressOffset the offset to load the address path from
* @param {integer} valueOffset the offset to load the value from
* @param {integer} dataOffset the offset to load data from
* @param {integer} dataLength the length of data
* @param {integer} resultOffset the offset to store the result data at
* @param {integer} resultLength
* @param {integer} gas
* @return {integer} Returns 1 or 0 depending on if the VM trapped on the message or not
*/
callCode (gas, addressOffset, valueOffset, dataOffset, dataLength, resultOffset, resultLength, cbIndex) {
log.debug('EVMimports.js callCode')
this.takeGas(40)
// Load the params from mem
// const address = this.getMemory(addressOffset, ADDRESS_SIZE_BYTES)
const value = U256.fromMemory(this.getMemory(valueOffset, U128_SIZE_BYTES))
// makes vm test callcodeToReturn1 pass
if (!value.isZero()) {
this.takeGas(6700)
}
// TODO: actually run code, using this.environment.callCode?
const opPromise = Promise.resolve(null)
this.kernel.pushOpsQueue(opPromise, cbIndex, oldValue => {
return 1
})
}
/**
* Message-call into this account with an alternative account’s code, but
* persisting the current values for sender and value.
* @param {integer} gas
* @param {integer} addressOffset the offset to load the address path from
* @param {integer} valueOffset the offset to load the value from
* @param {integer} dataOffset the offset to load data from
* @param {integer} dataLength the length of data
* @param {integer} resultOffset the offset to store the result data at
* @param {integer} resultLength
* @return {integer} Returns 1 or 0 depending on if the VM trapped on the message or not
*/
callDelegate (gas, addressOffset, dataOffset, dataLength, resultOffset, resultLength) {
log.debug('EVMimports.js callDelegate')
// FIXME: count properly
this.takeGas(40)
const data = this.getMemory(dataOffset, dataLength).slice(0)
const address = [...this.getMemory(addressOffset, ADDRESS_SIZE_BYTES)]
const [errorCode, result] = this.environment.callDelegate(gas, address, data)
this.setMemory(resultOffset, resultLength, result)
return errorCode
}
/**
* store a value at a given path in long term storage which are both loaded
* from Memory
* @param {interger} keyOffest the memory offset of the storage key
* @param {interger} valueOffset the memory offset of the storage value
*/
storageStore (keyOffset, valueOffset, cbIndex) {
log.debug('EVMimports.js storageStore')
this.takeGas(5000)
const key = this.getMemory(keyOffset, U256_SIZE_BYTES)
const keyHex = U256.fromMemory(key).toString(16)
const value = this.getMemory(valueOffset, U256_SIZE_BYTES).slice(0)
const valueHex = U256.fromMemory(value).toString(16)
const valIsZero = value.every((i) => i === 0)
const contextAccount = this.kernel.environment.address
const oldStorageVal = this.kernel.environment.state[contextAccount]['storage'][keyHex]
const opPromise = Promise.resolve(oldStorageVal)
this.kernel.pushOpsQueue(opPromise, cbIndex, oldValue => {
if (valIsZero && oldValue) {
// delete a value
this.kernel.environment.gasRefund += 15000
delete this.kernel.environment.state[contextAccount]['storage'][keyHex]
} else {
if (!valIsZero && !oldValue) {
// creating a new value
this.takeGas(15000)
}
// update
this.kernel.environment.state[contextAccount]['storage'][keyHex] = valueHex
}
})
}
/**
* reterives a value at a given path in long term storage
* @param {interger} keyOffset the memory offset to load the the path from
* @param {interger} resultOffset the memory offset to load the value from
*/
storageLoad (keyOffset, resultOffset, cbIndex) {
log.debug('EVMimports.js storageLoad')
log.trace('getBalance kernel.environment.state:', this.kernel.environment.state)
this.takeGas(50)
const key = this.getMemory(keyOffset, U256_SIZE_BYTES)
const keyHex = U256.fromMemory(key).toString(16)
const contextAccount = this.kernel.environment.address
let value = this.kernel.environment.state[contextAccount]['storage'][keyHex]
if (typeof value === 'undefined') {
value = new Uint8Array(32)
} else {
value = (new U256(value)).toMemory()
}
const opPromise = Promise.resolve(value)
this.kernel.pushOpsQueue(opPromise, cbIndex, value => {
this.setMemory(resultOffset, U256_SIZE_BYTES, value)
})
}
/**
* Halt execution returning output data.
* @param {integer} offset the offset of the output data.
* @param {integer} length the length of the output data.
*/
return (offset, length) {
if (length) {
this.kernel.environment.returnValue = this.getMemory(offset, length).slice(0)
}
}
/**
* Halt execution and register account for later deletion giving the remaining
* balance to an address path
* @param {integer} offset the offset to load the address from
*/
selfDestruct (addressOffset) {
log.debug('EVMimports.js selfDestruct')
this.kernel.environment.selfDestruct = true
this.kernel.environment.selfDestructAddress = this.getMemory(addressOffset, ADDRESS_SIZE_BYTES)
this.kernel.environment.gasRefund += 24000
}
getMemory (offset, length) {
return new Uint8Array(this.kernel.memory, offset, length)
}
setMemory (offset, length, value) {
const memory = new Uint8Array(this.kernel.memory, offset, length)
memory.set(value)
}
/*
* Takes gas from the tank. Only needs to check if there's gas left to be taken,
* because every caller of this method is trusted.
*/
takeGas (amount) {
if (this.kernel.environment.gasLeft < amount) {
throw new Error('Ran out of gas')
}
this.kernel.environment.gasLeft -= amount
}
}
// converts a 64 bit number to a JS number
function from64bit (high, low) {
if (high < 0) {
// convert from a 32-bit two's compliment
high = 0x100000000 - high
}
if (low < 0) {
// convert from a 32-bit two's compliment
low = 0x100000000 - low
}
// JS only bitshift 32bits, so instead of high << 32 we have high * 2 ^ 32
return (high * 4294967296) + low
}