Commit 34bc1cd6 authored by aniket-engg's avatar aniket-engg Committed by Aniket

providers, init, util, txRunner

parent 142d6478
...@@ -9,6 +9,7 @@ const Web3VMProvider = require('../web3Provider/web3VmProvider') ...@@ -9,6 +9,7 @@ const Web3VMProvider = require('../web3Provider/web3VmProvider')
const LogsManager = require('./logsManager.js') const LogsManager = require('./logsManager.js')
declare let ethereum: any;
let web3 let web3
if (typeof window !== 'undefined' && typeof window['ethereum'] !== 'undefined') { if (typeof window !== 'undefined' && typeof window['ethereum'] !== 'undefined') {
var injectedProvider = window['ethereum'] var injectedProvider = window['ethereum']
......
'use strict' 'use strict'
import { Transaction } from 'ethereumjs-tx' import { Transaction } from 'ethereumjs-tx'
import { Block } from 'ethereumjs-block' import { Block } from 'ethereumjs-block'
import { BN } from 'ethereumjs-util' import { BN, bufferToHex } from 'ethereumjs-util'
import { ExecutionContext } from './execution-context' import { ExecutionContext } from './execution-context'
const EventManager = require('../eventManager') const EventManager = require('../eventManager')
......
'use strict' 'use strict'
const Web3 = require('web3') import Web3 from 'web3'
module.exports = { export function loadWeb3 (url = 'http://localhost:8545') {
loadWeb3: function (url) {
if (!url) url = 'http://localhost:8545'
const web3 = new Web3() const web3 = new Web3()
web3.setProvider(new web3.providers.HttpProvider(url)) web3.setProvider(new Web3.providers.HttpProvider(url))
this.extend(web3) this.extend(web3)
return web3 return web3
}, }
extendWeb3: function (web3) { export function extendWeb3 (web3) {
this.extend(web3) this.extend(web3)
}, }
setProvider: function (web3, url) { export function setProvider (web3, url) {
web3.setProvider(new web3.providers.HttpProvider(url)) web3.setProvider(new web3.providers.HttpProvider(url))
}, }
web3DebugNode: function (network) { export function web3DebugNode (network) {
const web3DebugNodes = {
'Main': 'https://gethmainnet.komputing.org',
'Rinkeby': 'https://remix-rinkeby.ethdevops.io',
'Ropsten': 'https://remix-ropsten.ethdevops.io',
'Goerli': 'https://remix-goerli.ethdevops.io',
'Kovan': 'https://remix-kovan.ethdevops.io'
}
if (web3DebugNodes[network]) { if (web3DebugNodes[network]) {
return this.loadWeb3(web3DebugNodes[network]) return this.loadWeb3(web3DebugNodes[network])
} }
return null return null
}, }
extend: function (web3) { export function extend (web3) {
if (!web3.extend) { if (!web3.extend) {
return return
} }
...@@ -65,12 +70,3 @@ module.exports = { ...@@ -65,12 +70,3 @@ module.exports = {
}) })
} }
} }
}
const web3DebugNodes = {
'Main': 'https://gethmainnet.komputing.org',
'Rinkeby': 'https://remix-rinkeby.ethdevops.io',
'Ropsten': 'https://remix-ropsten.ethdevops.io',
'Goerli': 'https://remix-goerli.ethdevops.io',
'Kovan': 'https://remix-kovan.ethdevops.io'
}
...@@ -10,11 +10,10 @@ import { BN, bufferToHex, keccak, setLengthLeft } from 'ethereumjs-util' ...@@ -10,11 +10,10 @@ import { BN, bufferToHex, keccak, setLengthLeft } from 'ethereumjs-util'
- swarm hash extraction - swarm hash extraction
- bytecode comparison - bytecode comparison
*/ */
module.exports = {
/* /*
ints: IntArray ints: IntArray
*/ */
hexConvert: function (ints) { export function hexConvert (ints) {
let ret = '0x' let ret = '0x'
for (let i = 0; i < ints.length; i++) { for (let i = 0; i < ints.length; i++) {
const h = ints[i] const h = ints[i]
...@@ -25,12 +24,12 @@ module.exports = { ...@@ -25,12 +24,12 @@ module.exports = {
} }
} }
return ret return ret
}, }
/** /**
* Converts a hex string to an array of integers. * Converts a hex string to an array of integers.
*/ */
hexToIntArray: function (hexString) { export function hexToIntArray (hexString) {
if (hexString.slice(0, 2) === '0x') { if (hexString.slice(0, 2) === '0x') {
hexString = hexString.slice(2) hexString = hexString.slice(2)
} }
...@@ -39,12 +38,12 @@ module.exports = { ...@@ -39,12 +38,12 @@ module.exports = {
integers.push(parseInt(hexString.slice(i, i + 2), 16)) integers.push(parseInt(hexString.slice(i, i + 2), 16))
} }
return integers return integers
}, }
/* /*
ints: list of BNs ints: list of BNs
*/ */
hexListFromBNs: function (bnList) { export function hexListFromBNs (bnList) {
const ret = [] const ret = []
for (let k in bnList) { for (let k in bnList) {
const v = bnList[k] const v = bnList[k]
...@@ -55,23 +54,23 @@ module.exports = { ...@@ -55,23 +54,23 @@ module.exports = {
} }
} }
return ret return ret
}, }
/* /*
ints: list of IntArrays ints: list of IntArrays
*/ */
hexListConvert: function (intsList) { export function hexListConvert (intsList) {
const ret = [] const ret = []
for (let k in intsList) { for (let k in intsList) {
ret.push(this.hexConvert(intsList[k])) ret.push(this.hexConvert(intsList[k]))
} }
return ret return ret
}, }
/* /*
ints: ints: IntArray ints: ints: IntArray
*/ */
formatMemory: function (mem) { export function formatMemory (mem) {
const hexMem = this.hexConvert(mem).substr(2) const hexMem = this.hexConvert(mem).substr(2)
const ret = [] const ret = []
for (let k = 0; k < hexMem.length; k += 32) { for (let k = 0; k < hexMem.length; k += 32) {
...@@ -79,14 +78,14 @@ module.exports = { ...@@ -79,14 +78,14 @@ module.exports = {
ret.push(row) ret.push(row)
} }
return ret return ret
}, }
/* /*
Binary Search: Binary Search:
Assumes that @arg array is sorted increasingly Assumes that @arg array is sorted increasingly
return largest i such that array[i] <= target; return -1 if array[0] > target || array is empty return largest i such that array[i] <= target; return -1 if array[0] > target || array is empty
*/ */
findLowerBound: function (target, array) { export function findLowerBound (target, array) {
let start = 0 let start = 0
let length = array.length let length = array.length
while (length > 0) { while (length > 0) {
...@@ -100,25 +99,25 @@ module.exports = { ...@@ -100,25 +99,25 @@ module.exports = {
} }
} }
return start - 1 return start - 1
}, }
/* /*
Binary Search: Binary Search:
Assumes that @arg array is sorted increasingly Assumes that @arg array is sorted increasingly
return largest array[i] such that array[i] <= target; return null if array[0] > target || array is empty return largest array[i] such that array[i] <= target; return null if array[0] > target || array is empty
*/ */
findLowerBoundValue: function (target, array) { export function findLowerBoundValue (target, array) {
const index = this.findLowerBound(target, array) const index = this.findLowerBound(target, array)
return index >= 0 ? array[index] : null return index >= 0 ? array[index] : null
}, }
/* /*
Binary Search: Binary Search:
Assumes that @arg array is sorted increasingly Assumes that @arg array is sorted increasingly
return Return i such that |array[i] - target| is smallest among all i and -1 for an empty array. return Return i such that |array[i] - target| is smallest among all i and -1 for an empty array.
Returns the smallest i for multiple candidates. Returns the smallest i for multiple candidates.
*/ */
findClosestIndex: function (target, array) { export function findClosestIndex (target, array): number {
if (array.length === 0) { if (array.length === 0) {
return -1 return -1
} }
...@@ -131,16 +130,19 @@ module.exports = { ...@@ -131,16 +130,19 @@ module.exports = {
const middle = (array[index] + array[index + 1]) / 2 const middle = (array[index] + array[index + 1]) / 2
return target <= middle ? index : index + 1 return target <= middle ? index : index + 1
} }
}, }
/** /**
* Find the call from @args rootCall which contains @args index (recursive) * Find the call from @args rootCall which contains @args index (recursive)
* *
* @param {Int} index - index of the vmtrace * @param {Int} index - index of the vmtrace
* @param {Object} rootCall - call tree, built by the trace analyser * @param {Object} rootCall - call tree, built by the trace analyser
* @return {Object} - return the call which include the @args index * @return {Object} - return the call which include the @args index
*/ */
findCall: findCall, export function findCall (index, rootCall) {
const ret = buildCallPath(index, rootCall)
return ret[ret.length - 1]
}
/** /**
* Find calls path from @args rootCall which leads to @args index (recursive) * Find calls path from @args rootCall which leads to @args index (recursive)
...@@ -149,7 +151,11 @@ module.exports = { ...@@ -149,7 +151,11 @@ module.exports = {
* @param {Object} rootCall - call tree, built by the trace analyser * @param {Object} rootCall - call tree, built by the trace analyser
* @return {Array} - return the calls path to @args index * @return {Array} - return the calls path to @args index
*/ */
buildCallPath: buildCallPath, export function buildCallPath (index, rootCall) {
const ret = []
findCallInternal(index, rootCall, ret)
return ret
}
/** /**
* sha3 the given @arg value (left pad to 32 bytes) * sha3 the given @arg value (left pad to 32 bytes)
...@@ -157,63 +163,63 @@ module.exports = { ...@@ -157,63 +163,63 @@ module.exports = {
* @param {String} value - value to sha3 * @param {String} value - value to sha3
* @return {Object} - return sha3ied value * @return {Object} - return sha3ied value
*/ */
sha3_256: function (value) { export function sha3_256 (value) {
if (typeof value === 'string' && value.indexOf('0x') !== 0) { if (typeof value === 'string' && value.indexOf('0x') !== 0) {
value = '0x' + value value = '0x' + value
} }
let ret: any = bufferToHex(setLengthLeft(value, 32)) let ret: any = bufferToHex(setLengthLeft(value, 32))
ret = keccak(ret) ret = keccak(ret)
return bufferToHex(ret) return bufferToHex(ret)
}, }
/** /**
* return a regex which extract the swarmhash from the bytecode. * return a regex which extract the swarmhash from the bytecode.
* *
* @return {RegEx} * @return {RegEx}
*/ */
swarmHashExtraction: function () { export function swarmHashExtraction () {
return /a165627a7a72305820([0-9a-f]{64})0029$/ return /a165627a7a72305820([0-9a-f]{64})0029$/
}, }
/** /**
* return a regex which extract the swarmhash from the bytecode, from POC 0.3 * return a regex which extract the swarmhash from the bytecode, from POC 0.3
* *
* @return {RegEx} * @return {RegEx}
*/ */
swarmHashExtractionPOC31: function () { export function swarmHashExtractionPOC31 () {
return /a265627a7a72315820([0-9a-f]{64})64736f6c6343([0-9a-f]{6})0032$/ return /a265627a7a72315820([0-9a-f]{64})64736f6c6343([0-9a-f]{6})0032$/
}, }
/** /**
* return a regex which extract the swarmhash from the bytecode, from POC 0.3 * return a regex which extract the swarmhash from the bytecode, from POC 0.3
* *
* @return {RegEx} * @return {RegEx}
*/ */
swarmHashExtractionPOC32: function () { export function swarmHashExtractionPOC32 () {
return /a265627a7a72305820([0-9a-f]{64})64736f6c6343([0-9a-f]{6})0032$/ return /a265627a7a72305820([0-9a-f]{64})64736f6c6343([0-9a-f]{6})0032$/
}, }
/** /**
* return a regex which extract the cbor encoded metadata : {"ipfs": <IPFS hash>, "solc": <compiler version>} from the bytecode. * return a regex which extract the cbor encoded metadata : {"ipfs": <IPFS hash>, "solc": <compiler version>} from the bytecode.
* ref https://solidity.readthedocs.io/en/v0.6.6/metadata.html?highlight=ipfs#encoding-of-the-metadata-hash-in-the-bytecode * ref https://solidity.readthedocs.io/en/v0.6.6/metadata.html?highlight=ipfs#encoding-of-the-metadata-hash-in-the-bytecode
* @return {RegEx} * @return {RegEx}
*/ */
cborEncodedValueExtraction: function () { export function cborEncodedValueExtraction () {
return /64697066735822([0-9a-f]{68})64736f6c6343([0-9a-f]{6})0033$/ return /64697066735822([0-9a-f]{68})64736f6c6343([0-9a-f]{6})0033$/
}, }
extractcborMetadata: function (value) { export function extractcborMetadata (value) {
return value.replace(this.cborEncodedValueExtraction(), '') return value.replace(this.cborEncodedValueExtraction(), '')
}, }
extractSwarmHash: function (value) { export function extractSwarmHash (value) {
value = value.replace(this.swarmHashExtraction(), '') value = value.replace(this.swarmHashExtraction(), '')
value = value.replace(this.swarmHashExtractionPOC31(), '') value = value.replace(this.swarmHashExtractionPOC31(), '')
value = value.replace(this.swarmHashExtractionPOC32(), '') value = value.replace(this.swarmHashExtractionPOC32(), '')
return value return value
}, }
/** /**
* Compare bytecode. return true if the code is equal (handle swarm hash and library references) * Compare bytecode. return true if the code is equal (handle swarm hash and library references)
* @param {String} code1 - the bytecode that is actually deployed (contains resolved library reference and a potentially different swarmhash) * @param {String} code1 - the bytecode that is actually deployed (contains resolved library reference and a potentially different swarmhash)
* @param {String} code2 - the bytecode generated by the compiler (contains unresolved library reference and a potentially different swarmhash) * @param {String} code2 - the bytecode generated by the compiler (contains unresolved library reference and a potentially different swarmhash)
...@@ -221,7 +227,7 @@ module.exports = { ...@@ -221,7 +227,7 @@ module.exports = {
* *
* @return {bool} * @return {bool}
*/ */
compareByteCode: function (code1, code2) { export function compareByteCode (code1, code2) {
if (code1 === code2) return true if (code1 === code2) return true
if (code2 === '0x') return false // abstract contract. see comment if (code2 === '0x') return false // abstract contract. see comment
...@@ -245,25 +251,29 @@ module.exports = { ...@@ -245,25 +251,29 @@ module.exports = {
return true return true
} }
return false return false
}, }
groupBy: groupBy, /* util extracted out from remix-ide. @TODO split this file, cause it mix real util fn with solidity related stuff ... */
concatWithSeperator: concatWithSeperator, export function groupBy (arr, key) {
escapeRegExp: escapeRegExp return arr.reduce((sum, item) => {
const groupByVal = item[key]
const groupedItems = sum[groupByVal] || []
groupedItems.push(item)
sum[groupByVal] = groupedItems
return sum
}, {})
} }
function replaceLibReference (code, pos) { export function concatWithSeperator (list, seperator) {
return code.substring(0, pos) + '0000000000000000000000000000000000000000' + code.substring(pos + 40) return list.reduce((sum, item) => sum + item + seperator, '').slice(0, -seperator.length)
} }
function buildCallPath (index, rootCall) { export function escapeRegExp (str) {
const ret = [] return str.replace(/[-[\]/{}()+?.\\^$|]/g, '\\$&')
findCallInternal(index, rootCall, ret)
return ret
} }
function findCall (index, rootCall) {
const ret = buildCallPath(index, rootCall) function replaceLibReference (code, pos) {
return ret[ret.length - 1] return code.substring(0, pos) + '0000000000000000000000000000000000000000' + code.substring(pos + 40)
} }
function findCallInternal (index, rootCall, callsPath) { function findCallInternal (index, rootCall, callsPath) {
...@@ -279,22 +289,3 @@ function findCallInternal (index, rootCall, callsPath) { ...@@ -279,22 +289,3 @@ function findCallInternal (index, rootCall, callsPath) {
} }
return ret return ret
} }
/* util extracted out from remix-ide. @TODO split this file, cause it mix real util fn with solidity related stuff ... */
function groupBy (arr, key) {
return arr.reduce((sum, item) => {
const groupByVal = item[key]
const groupedItems = sum[groupByVal] || []
groupedItems.push(item)
sum[groupByVal] = groupedItems
return sum
}, {})
}
function concatWithSeperator (list, seperator) {
return list.reduce((sum, item) => sum + item + seperator, '').slice(0, -seperator.length)
}
function escapeRegExp (str) {
return str.replace(/[-[\]/{}()+?.\\^$|]/g, '\\$&')
}
function dummyProvider () { export class dummyProvider {
eth
debug
providers
currentProvider
constructor() {
this.eth = {} this.eth = {}
this.debug = {} this.debug = {}
this.eth.getCode = (address, cb) => { return this.getCode(address, cb) } this.eth.getCode = (address, cb) => { return this.getCode(address, cb) }
...@@ -9,42 +15,41 @@ function dummyProvider () { ...@@ -9,42 +15,41 @@ function dummyProvider () {
this.debug.storageRangeAt = (blockNumber, txIndex, address, start, end, maxLength, cb) => { return this.storageRangeAt(blockNumber, txIndex, address, start, end, maxLength, cb) } this.debug.storageRangeAt = (blockNumber, txIndex, address, start, end, maxLength, cb) => { return this.storageRangeAt(blockNumber, txIndex, address, start, end, maxLength, cb) }
this.providers = { 'HttpProvider': function (url) {} } this.providers = { 'HttpProvider': function (url) {} }
this.currentProvider = {'host': ''} this.currentProvider = {'host': ''}
} }
dummyProvider.prototype.getCode = function (address, cb) { getCode (address, cb) {
cb(null, '') cb(null, '')
} }
dummyProvider.prototype.setProvider = function (provider) {} setProvider (provider) {}
dummyProvider.prototype.traceTransaction = function (txHash, options, cb) { traceTransaction (txHash, options, cb) {
if (cb) { if (cb) {
cb(null, {}) cb(null, {})
} }
return {} return {}
} }
dummyProvider.prototype.storageRangeAt = function (blockNumber, txIndex, address, start, end, maxLength, cb) { storageRangeAt (blockNumber, txIndex, address, start, end, maxLength, cb) {
if (cb) { if (cb) {
cb(null, {}) cb(null, {})
} }
return {} return {}
} }
dummyProvider.prototype.getBlockNumber = function (cb) { cb(null, '') } getBlockNumber (cb) { cb(null, '') }
dummyProvider.prototype.getTransaction = function (txHash, cb) { getTransaction (txHash, cb) {
if (cb) { if (cb) {
cb(null, {}) cb(null, {})
} }
return {} return {}
} }
dummyProvider.prototype.getTransactionFromBlock = function (blockNumber, txIndex, cb) { getTransactionFromBlock (blockNumber, txIndex, cb) {
if (cb) { if (cb) {
cb(null, {}) cb(null, {})
} }
return {} return {}
}
} }
module.exports = dummyProvider
const Web3VMProvider = require('./web3VmProvider') import { Web3VmProvider } from './web3VmProvider'
const init = require('../init') import { loadWeb3, extendWeb3 } from '../init'
function Web3Providers () { export class Web3Providers {
modes
constructor() {
this.modes = {} this.modes = {}
} }
Web3Providers.prototype.addProvider = function (type, obj) { addProvider (type, obj) {
if (type === 'INTERNAL') { if (type === 'INTERNAL') {
const web3 = init.loadWeb3() const web3 = loadWeb3()
this.addWeb3(type, web3) this.addWeb3(type, web3)
} else if (type === 'vm') { } else if (type === 'vm') {
this.addVM(type, obj) this.addVM(type, obj)
} else { } else {
init.extendWeb3(obj) extendWeb3(obj)
this.addWeb3(type, obj) this.addWeb3(type, obj)
} }
} }
Web3Providers.prototype.get = function (type, cb) { get (type, cb) {
if (this.modes[type]) { if (this.modes[type]) {
return cb(null, this.modes[type]) return cb(null, this.modes[type])
} }
cb('error: this provider has not been setup (' + type + ')', null) cb('error: this provider has not been setup (' + type + ')', null)
} }
Web3Providers.prototype.addWeb3 = function (type, web3) { addWeb3 (type, web3) {
this.modes[type] = web3 this.modes[type] = web3
} }
Web3Providers.prototype.addVM = function (type, vm) { addVM (type, vm) {
const vmProvider = new Web3VMProvider() const vmProvider = new Web3VmProvider()
vmProvider.setVM(vm) vmProvider.setVM(vm)
this.modes[type] = vmProvider this.modes[type] = vmProvider
}
} }
module.exports = Web3Providers
const util = require('../util') import { hexConvert, hexListFromBNs, formatMemory } from '../util'
const uiutil = require('../helpers/uiHelper') import { normalizeHexAddress } from '../helpers/uiHelper'
const ethutil = require('ethereumjs-util') import { toChecksumAddress, BN, toBuffer, } from 'ethereumjs-util'
const Web3 = require('web3') const Web3 = require('web3')
function web3VmProvider () { export class Web3VmProvider {
web3
vm
vmTraces
txs
txsReceipt
processingHash
processingAddress
processingIndex
previousDepth
incr
eth
debug
providers
currentProvider
storageCache
lastProcessedStorageTxHash
sha3Preimages
sha3
toHex
toAscii
fromAscii
fromDecimal
fromWei
toWei
toBigNumber
isAddress
utils
constructor () {
this.web3 = new Web3() this.web3 = new Web3()
this.vm = null this.vm = null
this.vmTraces = {} this.vmTraces = {}
...@@ -40,9 +70,9 @@ function web3VmProvider () { ...@@ -40,9 +70,9 @@ function web3VmProvider () {
this.toBigNumber = (...args) => this.web3.utils.toBN(...args) this.toBigNumber = (...args) => this.web3.utils.toBN(...args)
this.isAddress = (...args) => this.web3.utils.isAddress(...args) this.isAddress = (...args) => this.web3.utils.isAddress(...args)
this.utils = Web3.utils || [] this.utils = Web3.utils || []
} }
web3VmProvider.prototype.setVM = function (vm) { setVM (vm) {
if (this.vm === vm) return if (this.vm === vm) return
this.vm = vm this.vm = vm
this.vm.on('step', (data) => { this.vm.on('step', (data) => {
...@@ -54,49 +84,49 @@ web3VmProvider.prototype.setVM = function (vm) { ...@@ -54,49 +84,49 @@ web3VmProvider.prototype.setVM = function (vm) {
this.vm.on('beforeTx', (data) => { this.vm.on('beforeTx', (data) => {
this.txWillProcess(this, data) this.txWillProcess(this, data)
}) })
} }
web3VmProvider.prototype.releaseCurrentHash = function () { releaseCurrentHash () {
const ret = this.processingHash const ret = this.processingHash
this.processingHash = undefined this.processingHash = undefined
return ret return ret
} }
web3VmProvider.prototype.txWillProcess = function (self, data) { txWillProcess (self, data) {
self.incr++ self.incr++
self.processingHash = util.hexConvert(data.hash()) self.processingHash = hexConvert(data.hash())
self.vmTraces[self.processingHash] = { self.vmTraces[self.processingHash] = {
gas: '0x0', gas: '0x0',
return: '0x0', return: '0x0',
structLogs: [] structLogs: []
} }
let tx = {} let tx = {}
tx.hash = self.processingHash tx['hash'] = self.processingHash
tx.from = ethutil.toChecksumAddress(util.hexConvert(data.getSenderAddress())) tx['from'] = toChecksumAddress(hexConvert(data.getSenderAddress()))
if (data.to && data.to.length) { if (data.to && data.to.length) {
tx.to = ethutil.toChecksumAddress(util.hexConvert(data.to)) tx['to'] = toChecksumAddress(hexConvert(data.to))
} }
this.processingAddress = tx.to this.processingAddress = tx['to']
tx.data = util.hexConvert(data.data) tx['data'] = hexConvert(data.data)
tx.input = util.hexConvert(data.input) tx['input'] = hexConvert(data.input)
tx.gas = (new ethutil.BN(util.hexConvert(data.gas).replace('0x', ''), 16)).toString(10) tx['gas'] = (new BN(hexConvert(data.gas).replace('0x', ''), 16)).toString(10)
if (data.value) { if (data.value) {
tx.value = util.hexConvert(data.value) tx['value'] = hexConvert(data.value)
} }
self.txs[self.processingHash] = tx self.txs[self.processingHash] = tx
self.txsReceipt[self.processingHash] = tx self.txsReceipt[self.processingHash] = tx
self.storageCache[self.processingHash] = {} self.storageCache[self.processingHash] = {}
if (tx.to) { if (tx['to']) {
const account = ethutil.toBuffer(tx.to) const account = toBuffer(tx['to'])
self.vm.stateManager.dumpStorage(account, (storage) => { self.vm.stateManager.dumpStorage(account, (storage) => {
self.storageCache[self.processingHash][tx.to] = storage self.storageCache[self.processingHash][tx['to']] = storage
self.lastProcessedStorageTxHash[tx.to] = self.processingHash self.lastProcessedStorageTxHash[tx['to']] = self.processingHash
}) })
} }
this.processingIndex = 0 this.processingIndex = 0
} }
web3VmProvider.prototype.txProcessed = function (self, data) { txProcessed (self, data) {
const lastOp = self.vmTraces[self.processingHash].structLogs[self.processingIndex - 1] const lastOp = self.vmTraces[self.processingHash].structLogs[self.processingIndex - 1]
if (lastOp) { if (lastOp) {
lastOp.error = lastOp.op !== 'RETURN' && lastOp.op !== 'STOP' && lastOp.op !== 'SELFDESTRUCT' lastOp.error = lastOp.op !== 'RETURN' && lastOp.op !== 'STOP' && lastOp.op !== 'SELFDESTRUCT'
...@@ -127,20 +157,20 @@ web3VmProvider.prototype.txProcessed = function (self, data) { ...@@ -127,20 +157,20 @@ web3VmProvider.prototype.txProcessed = function (self, data) {
self.txsReceipt[self.processingHash].status = `0x${status}` self.txsReceipt[self.processingHash].status = `0x${status}`
if (data.createdAddress) { if (data.createdAddress) {
const address = util.hexConvert(data.createdAddress) const address = hexConvert(data.createdAddress)
self.vmTraces[self.processingHash].return = ethutil.toChecksumAddress(address) self.vmTraces[self.processingHash].return = toChecksumAddress(address)
self.txsReceipt[self.processingHash].contractAddress = ethutil.toChecksumAddress(address) self.txsReceipt[self.processingHash].contractAddress = toChecksumAddress(address)
} else if (data.execResult.returnValue) { } else if (data.execResult.returnValue) {
self.vmTraces[self.processingHash].return = util.hexConvert(data.execResult.returnValue) self.vmTraces[self.processingHash].return = hexConvert(data.execResult.returnValue)
} else { } else {
self.vmTraces[self.processingHash].return = '0x' self.vmTraces[self.processingHash].return = '0x'
} }
this.processingIndex = null this.processingIndex = null
this.processingAddress = null this.processingAddress = null
this.previousDepth = 0 this.previousDepth = 0
} }
web3VmProvider.prototype.pushTrace = function (self, data) { pushTrace (self, data) {
const depth = data.depth + 1 // geth starts the depth from 1 const depth = data.depth + 1 // geth starts the depth from 1
if (!self.processingHash) { if (!self.processingHash) {
console.log('no tx processing') console.log('no tx processing')
...@@ -156,8 +186,8 @@ web3VmProvider.prototype.pushTrace = function (self, data) { ...@@ -156,8 +186,8 @@ web3VmProvider.prototype.pushTrace = function (self, data) {
previousopcode.invalidDepthChange = previousopcode.op !== 'RETURN' && previousopcode.op !== 'STOP' previousopcode.invalidDepthChange = previousopcode.op !== 'RETURN' && previousopcode.op !== 'STOP'
} }
const step = { const step = {
stack: util.hexListFromBNs(data.stack), stack: hexListFromBNs(data.stack),
memory: util.formatMemory(data.memory), memory: formatMemory(data.memory),
storage: data.storage, storage: data.storage,
op: data.opcode.name, op: data.opcode.name,
pc: data.pc, pc: data.pc,
...@@ -173,10 +203,10 @@ web3VmProvider.prototype.pushTrace = function (self, data) { ...@@ -173,10 +203,10 @@ web3VmProvider.prototype.pushTrace = function (self, data) {
this.storageCache[this.processingHash][this.processingAddress] = {} this.storageCache[this.processingHash][this.processingAddress] = {}
this.lastProcessedStorageTxHash[this.processingAddress] = this.processingHash this.lastProcessedStorageTxHash[this.processingAddress] = this.processingHash
} else { } else {
this.processingAddress = uiutil.normalizeHexAddress(step.stack[step.stack.length - 2]) this.processingAddress = normalizeHexAddress(step.stack[step.stack.length - 2])
this.processingAddress = ethutil.toChecksumAddress(this.processingAddress) this.processingAddress = toChecksumAddress(this.processingAddress)
if (!self.storageCache[self.processingHash][this.processingAddress]) { if (!self.storageCache[self.processingHash][this.processingAddress]) {
const account = ethutil.toBuffer(this.processingAddress) const account = toBuffer(this.processingAddress)
self.vm.stateManager.dumpStorage(account, function (storage) { self.vm.stateManager.dumpStorage(account, function (storage) {
self.storageCache[self.processingHash][self.processingAddress] = storage self.storageCache[self.processingHash][self.processingAddress] = storage
self.lastProcessedStorageTxHash[self.processingAddress] = self.processingHash self.lastProcessedStorageTxHash[self.processingAddress] = self.processingHash
...@@ -185,7 +215,7 @@ web3VmProvider.prototype.pushTrace = function (self, data) { ...@@ -185,7 +215,7 @@ web3VmProvider.prototype.pushTrace = function (self, data) {
} }
} }
if (previousopcode && previousopcode.op === 'SHA3') { if (previousopcode && previousopcode.op === 'SHA3') {
const preimage = getSha3Input(previousopcode.stack, previousopcode.memory) const preimage = this.getSha3Input(previousopcode.stack, previousopcode.memory)
const imageHash = step.stack[step.stack.length - 1].replace('0x', '') const imageHash = step.stack[step.stack.length - 1].replace('0x', '')
self.sha3Preimages[imageHash] = { self.sha3Preimages[imageHash] = {
'preimage': preimage 'preimage': preimage
...@@ -194,19 +224,19 @@ web3VmProvider.prototype.pushTrace = function (self, data) { ...@@ -194,19 +224,19 @@ web3VmProvider.prototype.pushTrace = function (self, data) {
this.processingIndex++ this.processingIndex++
this.previousDepth = depth this.previousDepth = depth
} }
web3VmProvider.prototype.getCode = function (address, cb) { getCode (address, cb) {
address = ethutil.toChecksumAddress(address) address = toChecksumAddress(address)
const account = ethutil.toBuffer(address) const account = toBuffer(address)
this.vm.stateManager.getContractCode(account, (error, result) => { this.vm.stateManager.getContractCode(account, (error, result) => {
cb(error, util.hexConvert(result)) cb(error, hexConvert(result))
}) })
} }
web3VmProvider.prototype.setProvider = function (provider) {} setProvider (provider) {}
web3VmProvider.prototype.traceTransaction = function (txHash, options, cb) { traceTransaction (txHash, options, cb) {
if (this.vmTraces[txHash]) { if (this.vmTraces[txHash]) {
if (cb) { if (cb) {
cb(null, this.vmTraces[txHash]) cb(null, this.vmTraces[txHash])
...@@ -216,11 +246,11 @@ web3VmProvider.prototype.traceTransaction = function (txHash, options, cb) { ...@@ -216,11 +246,11 @@ web3VmProvider.prototype.traceTransaction = function (txHash, options, cb) {
if (cb) { if (cb) {
cb('unable to retrieve traces ' + txHash, null) cb('unable to retrieve traces ' + txHash, null)
} }
} }
web3VmProvider.prototype.storageRangeAt = function (blockNumber, txIndex, address, start, maxLength, cb) { // txIndex is the hash in the case of the VM storageRangeAt (blockNumber, txIndex, address, start, maxLength, cb) { // txIndex is the hash in the case of the VM
// we don't use the range params here // we don't use the range params here
address = ethutil.toChecksumAddress(address) address = toChecksumAddress(address)
if (txIndex === 'latest') { if (txIndex === 'latest') {
txIndex = this.lastProcessedStorageTxHash[address] txIndex = this.lastProcessedStorageTxHash[address]
...@@ -234,11 +264,11 @@ web3VmProvider.prototype.storageRangeAt = function (blockNumber, txIndex, addres ...@@ -234,11 +264,11 @@ web3VmProvider.prototype.storageRangeAt = function (blockNumber, txIndex, addres
}) })
} }
cb('unable to retrieve storage ' + txIndex + ' ' + address) cb('unable to retrieve storage ' + txIndex + ' ' + address)
} }
web3VmProvider.prototype.getBlockNumber = function (cb) { cb(null, 'vm provider') } getBlockNumber (cb) { cb(null, 'vm provider') }
web3VmProvider.prototype.getTransaction = function (txHash, cb) { getTransaction (txHash, cb) {
if (this.txs[txHash]) { if (this.txs[txHash]) {
if (cb) { if (cb) {
cb(null, this.txs[txHash]) cb(null, this.txs[txHash])
...@@ -248,9 +278,9 @@ web3VmProvider.prototype.getTransaction = function (txHash, cb) { ...@@ -248,9 +278,9 @@ web3VmProvider.prototype.getTransaction = function (txHash, cb) {
if (cb) { if (cb) {
cb('unable to retrieve tx ' + txHash, null) cb('unable to retrieve tx ' + txHash, null)
} }
} }
web3VmProvider.prototype.getTransactionReceipt = function (txHash, cb) { getTransactionReceipt (txHash, cb) {
// same as getTransaction but return the created address also // same as getTransaction but return the created address also
if (this.txsReceipt[txHash]) { if (this.txsReceipt[txHash]) {
if (cb) { if (cb) {
...@@ -261,49 +291,48 @@ web3VmProvider.prototype.getTransactionReceipt = function (txHash, cb) { ...@@ -261,49 +291,48 @@ web3VmProvider.prototype.getTransactionReceipt = function (txHash, cb) {
if (cb) { if (cb) {
cb('unable to retrieve txReceipt ' + txHash, null) cb('unable to retrieve txReceipt ' + txHash, null)
} }
} }
web3VmProvider.prototype.getTransactionFromBlock = function (blockNumber, txIndex, cb) { getTransactionFromBlock (blockNumber, txIndex, cb) {
const mes = 'not supposed to be needed by remix in vmmode' const mes = 'not supposed to be needed by remix in vmmode'
console.log(mes) console.log(mes)
if (cb) { if (cb) {
cb(mes, null) cb(mes, null)
} }
} }
web3VmProvider.prototype.preimage = function (hashedKey, cb) { preimage (hashedKey, cb) {
hashedKey = hashedKey.replace('0x', '') hashedKey = hashedKey.replace('0x', '')
cb(null, this.sha3Preimages[hashedKey] !== undefined ? this.sha3Preimages[hashedKey].preimage : null) cb(null, this.sha3Preimages[hashedKey] !== undefined ? this.sha3Preimages[hashedKey].preimage : null)
} }
function getSha3Input (stack, memory) { getSha3Input (stack, memory) {
let memoryStart = stack[stack.length - 1] let memoryStart = stack[stack.length - 1]
let memoryLength = stack[stack.length - 2] let memoryLength = stack[stack.length - 2]
const memStartDec = (new ethutil.BN(memoryStart.replace('0x', ''), 16)).toString(10) const memStartDec = (new BN(memoryStart.replace('0x', ''), 16)).toString(10)
memoryStart = parseInt(memStartDec) * 2 memoryStart = parseInt(memStartDec) * 2
const memLengthDec = (new ethutil.BN(memoryLength.replace('0x', ''), 16).toString(10)) const memLengthDec = (new BN(memoryLength.replace('0x', ''), 16).toString(10))
memoryLength = parseInt(memLengthDec) * 2 memoryLength = parseInt(memLengthDec) * 2
let i = Math.floor(memoryStart / 32) let i = Math.floor(memoryStart / 32)
const maxIndex = Math.floor(memoryLength / 32) + i const maxIndex = Math.floor(memoryLength / 32) + i
if (!memory[i]) { if (!memory[i]) {
return emptyFill(memoryLength) return this.emptyFill(memoryLength)
} }
let sha3Input = memory[i].slice(memoryStart - 32 * i) let sha3Input = memory[i].slice(memoryStart - 32 * i)
i++ i++
while (i < maxIndex) { while (i < maxIndex) {
sha3Input += memory[i] ? memory[i] : emptyFill(32) sha3Input += memory[i] ? memory[i] : this.emptyFill(32)
i++ i++
} }
if (sha3Input.length < memoryLength) { if (sha3Input.length < memoryLength) {
const leftSize = memoryLength - sha3Input.length const leftSize = memoryLength - sha3Input.length
sha3Input += memory[i] ? memory[i].slice(0, leftSize) : emptyFill(leftSize) sha3Input += memory[i] ? memory[i].slice(0, leftSize) : this.emptyFill(leftSize)
} }
return sha3Input return sha3Input
} }
function emptyFill (size) { emptyFill (size) {
return (new Array(size)).join('0') return (new Array(size)).join('0')
}
} }
module.exports = web3VmProvider
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment