use of org.ethereum.vm.program.Program in project rskj by rsksmart.
the class VMPerformanceTest method testLongOperation.
//
@Ignore
@Test
public void testLongOperation() {
/* bad example because requires ABI parsing
contract Fibonacci {
function fib() returns (uint r) {
uint256 a;
uint256 b;
uint256 c;
a=0;
b=1;
for (uint i = 1; i < 55; i++) {
c = a+b;
a = b;
b = c;
}
r = b;
}
} // contract
// Good example
contract Fibonacci {
function() {
uint256 a;
uint256 b;
uint256 c;
a=0;
b=1;
for (uint i = 1; i < 50; i++) {
c = a+b;
a = b;
b = c;
}
assembly {
mstore(0x0, b)
return(0x0, 32)
}
}
} // contract
*/
vm = new VM(config.getVmConfig(), new PrecompiledContracts(config));
// Strip the first 16 bytes which are added by Solidity to store the contract.
byte[] codePlusPrefix = Hex.decode(// ---------------------------------------------------------------------------------------------------------------------nn
"606060405260618060106000396000f360606040523615600d57600d565b605f5b6000600060006000600093508350600192508250600190505b60" + // "32"+ // 55
"FE" + // 254
"811015604f5782840191508150829350835081925082505b80806001019150506029565b8260005260206000f35b50505050565b00");
// "606060405260618060106000396000f360606040523615600d57600d565b605f5b6000600060006000600093508350600192508250600190505b600f811015604f5782840191508150829350835081925082505b80806001019150506029565b8260005260206000f35b50505050565b00"
/* Prefix code
Instr.# addrs. mnemonic operand xrefs description
------------------------------------------------------------------------------------------------------------------------------------------------------
[ 0] [0x00000000] PUSH1 0x60 ('`') # Place 1 byte item on stack.
[ 1] [0x00000002] PUSH1 0x40 ('@') # Place 1 byte item on stack.
[ 2] [0x00000004] MSTORE # Save word to memory.
[ 3] [0x00000005] PUSH1 0x61 ('a') This is the real contract length # Place 1 byte item on stack.
[ 4] [0x00000007] DUP1 # Duplicate 1st stack item.
[ 5] [0x00000008] PUSH1 0x10 # Place 1 byte item on stack.
[ 6] [0x0000000a] PUSH1 0x00 # Place 1 byte item on stack.
[ 7] [0x0000000c] CODECOPY # Copy code running in current environment to memory.
[ 8] [0x0000000d] PUSH1 0x00 # Place 1 byte item on stack.
[ 9] [0x0000000f] RETURN
------------------------------------------------------------------------------------------------------------------------------------------------------*/
byte[] code = Arrays.copyOfRange(codePlusPrefix, 16, codePlusPrefix.length);
program = new Program(vmConfig, precompiledContracts, blockchainConfig, code, invoke, null);
// String s_expected_1 = "000000000000000000000000000000000000000000000000000000033FFC1244"; // 55
// String s_expected_1 = "00000000000000000000000000000000000000000000000000000002EE333961";// 50
// 254
String s_expected_1 = "0000000000000000000090A7ED63052BFF49E105B6B7BC90D0B352C89BA1AD59";
startMeasure();
vm.steps(program, Long.MAX_VALUE);
endMeasure();
byte[] actualHReturn = null;
if (program.getResult().getHReturn() != null) {
actualHReturn = program.getResult().getHReturn();
}
// if (!Arrays.equals(expectedHReturn, actualHReturn)) {
// DataWord item1 = program.stackPop();
assertEquals(s_expected_1, Hex.toHexString(actualHReturn).toUpperCase());
}
use of org.ethereum.vm.program.Program in project rskj by rsksmart.
the class VMPerformanceTest method testRunTime.
/**
**************** RESULTS 30/12/2016 ******************************************
* Creating a large set of linked memory objects to force GC...
* Creating 10000000 linked objects..
* done.
* Starting test....
* Configuration: Program.useDataWordPool = true
* Time elapsed [ms]: 10062 [s]:10
* RealTime elapsed [ms]: 10263 [s]:10
* GCTime elapsed [ms]: 0 [s]:0
* Instructions executed: : 170400032
* Instructions per second: 16934898
* Avg Time per instructions [us]: 0
* Avg Time per instructions [ns]: 59
* -----------------------------------------------------------------------------
* Starting test....
* Configuration: Program.useDataWordPool = false
* Time elapsed [ms]: 16957 [s]:16
* RealTime elapsed [ms]: 28273 [s]:28
* GCTime elapsed [ms]: 10868 [s]:10
* Instructions executed: : 170400032
* Instructions per second: 10048766
* Avg Time per instructions [us]: 0
* Avg Time per instructions [ns]: 99
* -----------------------------------------------------------------------------
*/
public void testRunTime(byte[] code, String s_expected) {
program = new Program(vmConfig, precompiledContracts, blockchainConfig, code, invoke, null);
System.out.println("-----------------------------------------------------------------------------");
System.out.println("Starting test....");
System.out.println("Configuration: Program.useDataWordPool = " + Program.getUseDataWordPool().toString());
startMeasure();
vm.steps(program, Long.MAX_VALUE);
endMeasure();
System.out.println("Instructions executed: : " + Integer.toString(vm.getVmCounter()));
System.out.println("Gas consumed: " + Long.toString(program.getResult().getGasUsed()));
System.out.println("Average Gas per instruction: " + Long.toString(program.getResult().getGasUsed() / vm.getVmCounter()));
long M = 1000 * 1000;
long insPerSecond = vm.getVmCounter() * M / deltaTime;
System.out.println("Instructions per second: " + Long.toString(insPerSecond));
System.out.println("Avg Time per instructions [us]: " + Long.toString(M / insPerSecond));
System.out.println("Avg Time per instructions [ns]: " + Long.toString(1000 * M / insPerSecond));
byte[] actualHReturn = null;
if (program.getResult().getHReturn() != null) {
actualHReturn = program.getResult().getHReturn();
}
assertEquals(s_expected, Hex.toHexString(actualHReturn).toUpperCase());
System.out.println("-----------------------------------------------------------------------------");
}
use of org.ethereum.vm.program.Program in project rskj by rsksmart.
the class VMPerformanceTest method measureProgram.
public long measureProgram(String opcode, byte[] code, int insCount, int divisor, long refTime, int cloneCount, ResultLogger resultLogger) {
// Repeat program 100 times to reduce the overhead of clearing the stack
// the program must not loop.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int i = 0; i < cloneCount; i++) baos.write(code, 0, code.length);
byte[] newCode = baos.toByteArray();
program = new Program(vmConfig, precompiledContracts, blockchainConfig, newCode, invoke, null);
int sa = program.getStartAddr();
long myLoops = maxLoops / cloneCount;
insCount = insCount * cloneCount;
Runtime rt = Runtime.getRuntime();
PerfRes best = null;
forceGc();
PerfRes pr = new PerfRes();
for (int g = 0; g < maxGroups; g++) {
long startUsedMemory = (rt.totalMemory() - rt.freeMemory());
long startRealTime = System.currentTimeMillis();
// in nanoseconds.
long startTime = thread.getCurrentThreadCpuTime();
long startGas = program.getResult().getGasUsed();
long xUsedMemory;
// el menor tiempo logrado
for (int loops = 0; loops < myLoops; loops++) {
/*for (int i=0;i<insCount;i++) {
vm.step(program);
}*/
vm.steps(program, insCount);
// trick: Now force the program to restart, clear stack
if (loops == 0) {
long endGas = program.getResult().getGasUsed();
pr.gas = endGas - startGas;
}
program.restart();
}
long endTime = thread.getCurrentThreadCpuTime();
long endRealTime = System.currentTimeMillis();
// nano
pr.deltaTime = (endTime - startTime) / maxLoops / divisor;
pr.wallClockTimeMillis = (endRealTime - startRealTime);
// de milli a nano
pr.deltaRealTime = (endRealTime - startRealTime) * 1000 * 1000 / maxLoops / divisor;
long endUsedMemory = (rt.totalMemory() - rt.freeMemory());
pr.deltaUsedMemory = endUsedMemory - startUsedMemory;
if ((best == null) || (pr.deltaTime < best.deltaTime)) {
best = pr;
if (best.deltaTime == 0)
System.out.println("bad time");
pr = new PerfRes();
}
}
long percent;
if (refTime != 0)
percent = (best.deltaTime - refTime) * 100 / refTime;
else
percent = 0;
System.out.println(padRight(opcode, 12) + ":" + " wctime[msec]: " + padLeft(Long.toString(best.wallClockTimeMillis), 7) + " full: " + padLeft(Long.toString(best.deltaTime), 7) + " ref: " + padLeft(Long.toString(best.deltaTime - refTime), 7) + " (% ref): " + padLeft(Long.toString(percent), 5) + " gas: " + padLeft(Long.toString(best.gas), 6) + " time/gas: " + padLeft(Long.toString(best.deltaTime * 100 / best.gas), 6) + " fullReal: " + padLeft(Long.toString(best.deltaRealTime), 7) + " mem[Kb]: " + padLeft(Long.toString(best.deltaUsedMemory / 1000), 10));
if (resultLogger != null) {
resultLogger.log(opcode, best);
}
return best.deltaTime;
}
use of org.ethereum.vm.program.Program in project rskj by rsksmart.
the class TestRunner method runTestCase.
public List<String> runTestCase(TestCase testCase) {
logger.info("\n***");
logger.info(" Running test case: [" + testCase.getName() + "]");
logger.info("***\n");
List<String> results = new ArrayList<>();
logger.info("--------- PRE ---------");
Repository repository = loadRepository(new RepositoryImpl(config).startTracking(), testCase.getPre());
try {
/* 2. Create ProgramInvoke - Env/Exec */
Env env = testCase.getEnv();
Exec exec = testCase.getExec();
Logs logs = testCase.getLogs();
byte[] address = exec.getAddress();
byte[] origin = exec.getOrigin();
byte[] caller = exec.getCaller();
byte[] balance = ByteUtil.bigIntegerToBytes(repository.getBalance(new RskAddress(exec.getAddress())).asBigInteger());
byte[] gasPrice = exec.getGasPrice();
byte[] gas = exec.getGas();
byte[] callValue = exec.getValue();
byte[] msgData = exec.getData();
byte[] lastHash = env.getPreviousHash();
byte[] coinbase = env.getCurrentCoinbase();
long timestamp = ByteUtil.byteArrayToLong(env.getCurrentTimestamp());
long number = ByteUtil.byteArrayToLong(env.getCurrentNumber());
byte[] difficulty = env.getCurrentDifficulty();
byte[] gaslimit = env.getCurrentGasLimit();
// Origin and caller need to exist in order to be able to execute
if (repository.getAccountState(new RskAddress(origin)) == null)
repository.createAccount(new RskAddress(origin));
if (repository.getAccountState(new RskAddress(caller)) == null)
repository.createAccount(new RskAddress(caller));
ProgramInvoke programInvoke = new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, msgData, lastHash, coinbase, timestamp, number, 0, difficulty, gaslimit, repository, new BlockStoreDummy(), true);
/* 3. Create Program - exec.code */
/* 4. run VM */
VM vm = new VM(vmConfig, precompiledContracts);
Program program = new Program(vmConfig, precompiledContracts, mock(BlockchainConfig.class), exec.getCode(), programInvoke, null);
boolean vmDidThrowAnEception = false;
Exception e = null;
ThreadMXBean thread;
Boolean oldMode;
long startTime = 0;
thread = ManagementFactory.getThreadMXBean();
if (thread.isThreadCpuTimeSupported()) {
oldMode = thread.isThreadCpuTimeEnabled();
thread.setThreadCpuTimeEnabled(true);
// in nanoseconds.
startTime = thread.getCurrentThreadCpuTime();
}
try {
vm.steps(program, Long.MAX_VALUE);
;
} catch (RuntimeException ex) {
vmDidThrowAnEception = true;
e = ex;
}
if (startTime != 0) {
long endTime = thread.getCurrentThreadCpuTime();
// de nano a micro.
long deltaTime = (endTime - startTime) / 1000;
logger.info("Time elapsed [uS]: " + Long.toString(deltaTime));
}
try {
saveProgramTraceFile(config, testCase.getName(), program.getTrace());
} catch (IOException ioe) {
vmDidThrowAnEception = true;
e = ioe;
}
if (testCase.getPost().size() == 0) {
if (vmDidThrowAnEception != true) {
String output = "VM was expected to throw an exception";
logger.info(output);
results.add(output);
} else
logger.info("VM did throw an exception: " + e.toString());
} else {
if (vmDidThrowAnEception) {
String output = "VM threw an unexpected exception: " + e.toString();
logger.info(output, e);
results.add(output);
return results;
}
this.trace = program.getTrace();
logger.info("--------- POST --------");
/* 5. Assert Post values */
for (RskAddress addr : testCase.getPost().keySet()) {
AccountState accountState = testCase.getPost().get(addr);
long expectedNonce = accountState.getNonceLong();
Coin expectedBalance = accountState.getBalance();
byte[] expectedCode = accountState.getCode();
boolean accountExist = (null != repository.getAccountState(addr));
if (!accountExist) {
String output = String.format("The expected account does not exist. key: [ %s ]", addr);
logger.info(output);
results.add(output);
continue;
}
long actualNonce = repository.getNonce(addr).longValue();
Coin actualBalance = repository.getBalance(addr);
byte[] actualCode = repository.getCode(addr);
if (actualCode == null)
actualCode = "".getBytes();
if (expectedNonce != actualNonce) {
String output = String.format("The nonce result is different. key: [ %s ], expectedNonce: [ %d ] is actualNonce: [ %d ] ", addr, expectedNonce, actualNonce);
logger.info(output);
results.add(output);
}
if (!expectedBalance.equals(actualBalance)) {
String output = String.format("The balance result is different. key: [ %s ], expectedBalance: [ %s ] is actualBalance: [ %s ] ", addr, expectedBalance.toString(), actualBalance.toString());
logger.info(output);
results.add(output);
}
if (!Arrays.equals(expectedCode, actualCode)) {
String output = String.format("The code result is different. account: [ %s ], expectedCode: [ %s ] is actualCode: [ %s ] ", addr, Hex.toHexString(expectedCode), Hex.toHexString(actualCode));
logger.info(output);
results.add(output);
}
// assert storage
Map<DataWord, DataWord> storage = accountState.getStorage();
for (DataWord storageKey : storage.keySet()) {
byte[] expectedStValue = storage.get(storageKey).getData();
ContractDetails contractDetails = program.getStorage().getContractDetails(accountState.getAddress());
if (contractDetails == null) {
String output = String.format("Storage raw doesn't exist: key [ %s ], expectedValue: [ %s ]", Hex.toHexString(storageKey.getData()), Hex.toHexString(expectedStValue));
logger.info(output);
results.add(output);
continue;
}
Map<DataWord, DataWord> testStorage = contractDetails.getStorage();
DataWord actualValue = testStorage.get(new DataWord(storageKey.getData()));
if (actualValue == null || !Arrays.equals(expectedStValue, actualValue.getData())) {
String output = String.format("Storage value different: key [ %s ], expectedValue: [ %s ], actualValue: [ %s ]", Hex.toHexString(storageKey.getData()), Hex.toHexString(expectedStValue), actualValue == null ? "" : Hex.toHexString(actualValue.getNoLeadZeroesData()));
logger.info(output);
results.add(output);
}
}
/* asset logs */
List<LogInfo> logResult = program.getResult().getLogInfoList();
Iterator<LogInfo> postLogs = logs.getIterator();
int i = 0;
while (postLogs.hasNext()) {
LogInfo expectedLogInfo = postLogs.next();
LogInfo foundLogInfo = null;
if (logResult.size() > i) {
foundLogInfo = logResult.get(i);
}
if (foundLogInfo == null) {
String output = String.format("Expected log [ %s ]", expectedLogInfo.toString());
logger.info(output);
results.add(output);
} else {
if (!Arrays.equals(expectedLogInfo.getAddress(), foundLogInfo.getAddress())) {
String output = String.format("Expected address [ %s ], found [ %s ]", Hex.toHexString(expectedLogInfo.getAddress()), Hex.toHexString(foundLogInfo.getAddress()));
logger.info(output);
results.add(output);
}
if (!Arrays.equals(expectedLogInfo.getData(), foundLogInfo.getData())) {
String output = String.format("Expected data [ %s ], found [ %s ]", Hex.toHexString(expectedLogInfo.getData()), Hex.toHexString(foundLogInfo.getData()));
logger.info(output);
results.add(output);
}
if (!expectedLogInfo.getBloom().equals(foundLogInfo.getBloom())) {
String output = String.format("Expected bloom [ %s ], found [ %s ]", Hex.toHexString(expectedLogInfo.getBloom().getData()), Hex.toHexString(foundLogInfo.getBloom().getData()));
logger.info(output);
results.add(output);
}
if (expectedLogInfo.getTopics().size() != foundLogInfo.getTopics().size()) {
String output = String.format("Expected number of topics [ %d ], found [ %d ]", expectedLogInfo.getTopics().size(), foundLogInfo.getTopics().size());
logger.info(output);
results.add(output);
} else {
int j = 0;
for (DataWord topic : expectedLogInfo.getTopics()) {
byte[] foundTopic = foundLogInfo.getTopics().get(j).getData();
if (!Arrays.equals(topic.getData(), foundTopic)) {
String output = String.format("Expected topic [ %s ], found [ %s ]", Hex.toHexString(topic.getData()), Hex.toHexString(foundTopic));
logger.info(output);
results.add(output);
}
++j;
}
}
}
++i;
}
}
// TODO: assert that you have no extra accounts in the repository
// TODO: -> basically the deleted by suicide should be deleted
// TODO: -> and no unexpected created
List<org.ethereum.vm.CallCreate> resultCallCreates = program.getResult().getCallCreateList();
// assert call creates
for (int i = 0; i < testCase.getCallCreateList().size(); ++i) {
org.ethereum.vm.CallCreate resultCallCreate = null;
if (resultCallCreates != null && resultCallCreates.size() > i) {
resultCallCreate = resultCallCreates.get(i);
}
CallCreate expectedCallCreate = testCase.getCallCreateList().get(i);
if (resultCallCreate == null && expectedCallCreate != null) {
String output = String.format("Missing call/create invoke: to: [ %s ], data: [ %s ], gas: [ %s ], value: [ %s ]", Hex.toHexString(expectedCallCreate.getDestination()), Hex.toHexString(expectedCallCreate.getData()), Long.toHexString(expectedCallCreate.getGasLimit()), Hex.toHexString(expectedCallCreate.getValue()));
logger.info(output);
results.add(output);
continue;
}
boolean assertDestination = Arrays.equals(expectedCallCreate.getDestination(), resultCallCreate.getDestination());
if (!assertDestination) {
String output = String.format("Call/Create destination is different. Expected: [ %s ], result: [ %s ]", Hex.toHexString(expectedCallCreate.getDestination()), Hex.toHexString(resultCallCreate.getDestination()));
logger.info(output);
results.add(output);
}
boolean assertData = Arrays.equals(expectedCallCreate.getData(), resultCallCreate.getData());
if (!assertData) {
String output = String.format("Call/Create data is different. Expected: [ %s ], result: [ %s ]", Hex.toHexString(expectedCallCreate.getData()), Hex.toHexString(resultCallCreate.getData()));
logger.info(output);
results.add(output);
}
boolean assertGasLimit = expectedCallCreate.getGasLimit() == resultCallCreate.getGasLimit();
if (!assertGasLimit) {
String output = String.format("Call/Create gasLimit is different. Expected: [ %s ], result: [ %s ]", Long.toHexString(expectedCallCreate.getGasLimit()), Long.toHexString(resultCallCreate.getGasLimit()));
logger.info(output);
results.add(output);
}
boolean assertValue = Arrays.equals(expectedCallCreate.getValue(), resultCallCreate.getValue());
if (!assertValue) {
String output = String.format("Call/Create value is different. Expected: [ %s ], result: [ %s ]", Hex.toHexString(expectedCallCreate.getValue()), Hex.toHexString(resultCallCreate.getValue()));
logger.info(output);
results.add(output);
}
}
// assert out
byte[] expectedHReturn = testCase.getOut();
byte[] actualHReturn = EMPTY_BYTE_ARRAY;
if (program.getResult().getHReturn() != null) {
actualHReturn = program.getResult().getHReturn();
}
if (!Arrays.equals(expectedHReturn, actualHReturn)) {
String output = String.format("HReturn is different. Expected hReturn: [ %s ], actual hReturn: [ %s ]", Hex.toHexString(expectedHReturn), Hex.toHexString(actualHReturn));
logger.info(output);
results.add(output);
}
// assert gas
BigInteger expectedGas = new BigInteger(1, testCase.getGas());
BigInteger actualGas = new BigInteger(1, gas).subtract(BigInteger.valueOf(program.getResult().getGasUsed()));
if (validateGasUsed)
if (!expectedGas.equals(actualGas)) {
String output = String.format("Gas remaining is different. Expected gas remaining: [ %s ], actual gas remaining: [ %s ]", expectedGas.toString(), actualGas.toString());
logger.info(output);
results.add(output);
}
/*
* end of if(testCase.getPost().size() == 0)
*/
}
return results;
} finally {
// repository.close();
}
}
use of org.ethereum.vm.program.Program in project rskj by rsksmart.
the class VMComplexTest method test6.
@Ignore
// contractB call itself with code from contractA
@Test
public void test6() {
/**
* #The code will run
* ------------------
*
* contract A: 945304eb96065b2a98b57a48a06ae28d285a71b5
* ---------------
*
* PUSH1 0 CALLDATALOAD SLOAD NOT PUSH1 9 JUMPI STOP
* PUSH1 32 CALLDATALOAD PUSH1 0 CALLDATALOAD SSTORE
*
* contract B: 0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6
* -----------
* { (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
* (MSTORE 32 0xaaffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffaa)
* [[ 0 ]] (CALLSTATELESS 1000000 0x945304eb96065b2a98b57a48a06ae28d285a71b5 23 0 64 64 0)
* }
*/
// Set contract into Database
RskAddress caller_addr = new RskAddress("cd1722f3947def4cf144679da39c4c32bdc35681");
RskAddress contractA_addr = new RskAddress("945304eb96065b2a98b57a48a06ae28d285a71b5");
RskAddress contractB_addr = new RskAddress("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6");
byte[] codeA = Hex.decode("60003554156009570060203560003555");
byte[] codeB = Hex.decode("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6000527faaffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffaa6020526000604060406000601773945304eb96065b2a98b57a48a06ae28d285a71b5620f4240f3600055");
ProgramInvokeMockImpl pi = new ProgramInvokeMockImpl();
pi.setOwnerAddress(contractB_addr);
pi.setGasLimit(10000000000000l);
Repository repository = pi.getRepository();
repository.createAccount(contractA_addr);
repository.saveCode(contractA_addr, codeA);
repository.addBalance(contractA_addr, Coin.valueOf(23));
repository.createAccount(contractB_addr);
repository.saveCode(contractB_addr, codeB);
final BigInteger value = new BigInteger("1000000000000000000");
repository.addBalance(contractB_addr, new Coin(value));
repository.createAccount(caller_addr);
final BigInteger value1 = new BigInteger("100000000000000000000");
repository.addBalance(caller_addr, new Coin(value1));
// ****************** //
// Play the program //
// ****************** //
VM vm = getSubject();
Program program = getProgram(codeB, pi);
try {
while (!program.isStopped()) vm.step(program);
} catch (RuntimeException e) {
program.setRuntimeFailure(e);
}
System.out.println();
System.out.println("============ Results ============");
System.out.println("*** Used gas: " + program.getResult().getGasUsed());
DataWord memValue1 = program.memoryLoad(new DataWord(0));
DataWord memValue2 = program.memoryLoad(new DataWord(32));
DataWord storeValue1 = repository.getStorageValue(contractB_addr, new DataWord(00));
repository.close();
assertEquals("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", memValue1.toString());
assertEquals("aaffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffaa", memValue2.toString());
assertEquals("0x1", storeValue1.shortHex());
// TODO: check that the value pushed after exec is 1
}
Aggregations