diff --git a/ethereumj-core/build.gradle b/ethereumj-core/build.gradle index 7e90c808..5e9b8287 100644 --- a/ethereumj-core/build.gradle +++ b/ethereumj-core/build.gradle @@ -1,243 +1,144 @@ -buildscript { - repositories { - jcenter() - maven { url 'http://repo.spring.io/plugins-release-local' } - } - dependencies { - classpath 'org.springframework.build.gradle:propdeps-plugin:0.0.7' - classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:3.0.1' +apply plugin: 'com.android.library' + +repositories { + maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } + mavenCentral() + maven { url 'http://repo.spring.io/plugins-release-local' } + + flatDir { + dirs "libs" } } -plugins { - id 'application' - id 'jacoco' - id 'com.github.johnrengelman.shadow' version '1.2.0' - id 'me.champeau.gradle.antlr4' version '0.1' - id 'com.github.kt3k.coveralls' version '2.0.1x' - id 'com.jfrog.bintray' version '1.0' -} +android { + compileSdkVersion 21 + buildToolsVersion "21.1.2" -apply plugin: 'propdeps-maven' -apply plugin: 'com.jfrog.artifactory-upload' - -sourceCompatibility = 1.7 - -mainClassName = 'org.ethereum.Start' - -ext.generatedSrcDir = file('src/gen/java') - -sourceSets.main.java.srcDirs += generatedSrcDir - -antlr4 { - extraArgs = ['-package', 'org.ethereum.serpent'] - output = file("${generatedSrcDir}/org/ethereum/serpent") -} - -compileJava.dependsOn antlr4 - -test { - - useTestNG() - - jvmArgs '-Xss16m' - - testLogging { - events "failed" - exceptionFormat "short" + defaultConfig { + minSdkVersion 14 + targetSdkVersion 21 + versionCode 1 + versionName "1.0" } - systemProperty "file.encoding", "UTF-8" + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } } +//ext.generatedSrcDir = file('src/gen/java') -configurations { - compile.extendsFrom antlr4 -} +//sourceSets.main.java.srcDirs += generatedSrcDir + +//antlr4 { +// extraArgs = ['-package', 'org.ethereum.serpent'] +// output = file("${generatedSrcDir}/org/ethereum/serpent") +//} + +//compileJava.dependsOn antlr4 ext { slf4jVersion = '1.7.7' leveldbVersion = '0.7' scastleVersion = '1.51.0.0' log4jVersion = '1.2.17' - springVersion = '4.1.2.RELEASE' hibernateVersion = '4.3.7.Final' junitVersion = '4.11' } dependencies { - compile "io.netty:netty-all:4.0.23.Final" - compile "com.madgag.spongycastle:core:${scastleVersion}" // for SHA3 and SECP256K1 - compile "com.madgag.spongycastle:prov:${scastleVersion}" // for SHA3 and SECP256K1 + //compile 'com.android.support:appcompat-v7:+' + compile fileTree(include: ['*.jar'], dir: 'libs') + compile 'com.j256.ormlite:ormlite-core:4.48' + compile('com.j256.ormlite:ormlite-android:4.48') { + exclude group: 'commons-logging', module: 'commons-logging' + } + compile('com.j256.ormlite:ormlite-jdbc:4.48') { + exclude group: 'commons-logging', module: 'commons-logging' + } + //compile(name:'android-leveldb', ext:'aar') + //compile 'com.snappydb:snappydb-lib:0.5.0' + //compile files('./libs/android.jar') + + //compile files('./libs/commons-io-2.4.jar') + + //compile files('./libs/robospring-1.0.7.jar') + + //compile "com.octo.android.robospice:robospice-spring-android:1.4.14" + + //compile 'com.octo.android.robospice:robospice-ormlite:1.4.14' + compile('io.netty:netty-all:4.0.18.Final') { + exclude group: 'commons-logging', module: 'commons-logging' + } + compile "com.madgag.spongycastle:core:${scastleVersion}" + // for SHA3 and SECP256K1 + compile "com.madgag.spongycastle:prov:${scastleVersion}" + // for SHA3 and SECP256K1 + compile "org.iq80.leveldb:leveldb:${leveldbVersion}" - compile "com.cedarsoftware:java-util:1.8.0" // for deep equals - compile "org.antlr:antlr4-runtime:4.5" // for serpent compilation - compile "com.yuvalshavit:antlr-denter:1.1" - compile "org.javassist:javassist:3.15.0-GA" - compile "org.slf4j:slf4j-api:${slf4jVersion}" - compile "log4j:log4j:${log4jVersion}" - compile "org.codehaus.jackson:jackson-mapper-asl:1.9.13" - compile "com.google.code.findbugs:jsr305:3.0.0" - compile "com.fasterxml.jackson.core:jackson-databind:2.2.0" - compile "org.apache.commons:commons-collections4:4.0" - compile "commons-codec:commons-codec:1.10" - compile "org.springframework:spring-context:${springVersion}" - compile "org.springframework:spring-tx:${springVersion}" - compile "org.springframework:spring-orm:${springVersion}" - compile "org.hsqldb:hsqldb:1.8.0.10" // best performance - do not upgrade! - compile "org.hibernate:hibernate-core:${hibernateVersion}" - compile "org.hibernate:hibernate-entitymanager:${hibernateVersion}" - compile "commons-dbcp:commons-dbcp:1.4" - compile "redis.clients:jedis:2.6.0" - compile("com.googlecode.json-simple:json-simple:1.1.1") { + //compile "im.amomo.leveldb:leveldb:1.0.1" + //compile 'com.google.guava:guava:18.0' + compile('com.cedarsoftware:java-util:1.8.0') { + exclude group: 'commons-logging', module: 'commons-logging' + } + // for deep equals + + //compile 'org.antlr:antlr4-runtime:4.5' + + // for serpent compilation + + //compile 'com.yuvalshavit:antlr-denter:1.1' + + //compile 'org.javassist:javassist:3.15.0-GA' + compile 'org.slf4j:slf4j-android:1.6.1-RC1' + //compile "org.slf4j:slf4j-api:${slf4jVersion}" + + //compile "log4j:log4j:${log4jVersion}" + + //compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13' + compile 'com.google.code.findbugs:jsr305:3.0.0' + compile 'com.fasterxml.jackson.core:jackson-databind:2.2.0' + compile 'org.apache.commons:commons-collections4:4.0' + //compile 'commons-codec:commons-codec:1.10' + + // compile "org.springframework:spring-context:${springVersion}" + + //compile "org.springframework:spring-tx:${springVersion}" + + //compile "org.springframework:spring-orm:${springVersion}" + compile 'org.hsqldb:hsqldb:1.8.0.10' + // best performance - do not upgrade! + compile 'javax.el:javax.el-api:2.2.4' + compile 'org.glassfish.web:javax.el:2.2.4' + compile("org.hibernate:hibernate-core:${hibernateVersion}") { + exclude group: 'dom4j', module: 'dom4j' + exclude group: 'org.jboss.spec.javax.transaction', module: 'jboss-transaction-api_1.2_spec' + } + compile("org.hibernate:hibernate-entitymanager:${hibernateVersion}") { + exclude group: 'dom4j', module: 'dom4j' + exclude group: 'org.jboss.spec.javax.transaction', module: 'jboss-transaction-api_1.2_spec' + } + //compile ('commons-dbcp:commons-dbcp:1.4') { + + // exclude group: 'commons-logging', module: 'commons-logging' + + // } + compile('redis.clients:jedis:2.6.0') { + exclude group: 'org.apache.commons', module: 'commons-pool2' + } + compile('com.googlecode.json-simple:json-simple:1.1.1') { exclude group: 'junit', module: 'junit' + exclude group: 'xml-apis', module: 'xml-apis' } - optional "commons-logging:commons-logging:1.0" - optional "org.slf4j:jcl-over-slf4j:${slf4jVersion}" - optional "org.slf4j:slf4j-log4j12:${slf4jVersion}" - optional "log4j:apache-log4j-extras:${log4jVersion}" + //optional "org.slf4j:jcl-over-slf4j:${slf4jVersion}" + + //optional "de.mindpipe.android:android-logging-log4j:1.0.2" + + //optional "log4j:apache-log4j-extras:${log4jVersion}" testCompile "junit:junit:${junitVersion}" - testCompile "org.springframework:spring-test:${springVersion}" -} - -javadoc { - options.author = true - options.header = project.name - options.addStringOption('Xdoclint:all,-missing', '-quiet') - options.encoding = "UTF-8" - options.links( - "http://docs.oracle.com/javase/8/docs/api/", - "http://netty.io/4.0/api/" - ) -} - -task sourcesJar(type: Jar, dependsOn: classes) { - classifier = 'sources' - from sourceSets.main.allSource -} - -task javadocJar(type: Jar) { - classifier = "javadoc" - from javadoc -} - -artifacts { - archives sourcesJar - archives javadocJar -} - -jacocoTestReport { - reports { - xml.enabled = true - html.enabled = true - } -} - -def bintrayUsername = project.hasProperty('bintrayUser') ? project.bintrayUser : '' -def bintrayPassword = project.hasProperty('bintrayKey') ? project.bintrayKey : '' -def pullRequest = System.getenv('TRAVIS_PULL_REQUEST') -def branchName = System.getenv('TRAVIS_BRANCH') - -artifactory { - contextUrl = 'http://oss.jfrog.org/artifactory' - publish { - repository { - repoKey = 'oss-snapshot-local' - username = bintrayUsername - password = bintrayPassword - } - } - resolve { - repository { - repoKey = 'libs-release' - } - } + //testCompile "org.springframework:spring-test:${springVersion}" } - -artifactoryPublish.onlyIf { - (!pullRequest || pullRequest == 'false') && - project.version.endsWith('-SNAPSHOT') && - branchName.startsWith('master') -} - -bintray { - user = bintrayUsername - key = bintrayPassword - - configurations = ['archives'] - - dryRun = false //Whether to run this as dry-run, without deploying - publish = true //If version should be auto published after an upload - pkg { - userOrg = 'ethereum' //An optional organization name when the repo belongs to one of the user's orgs - repo = 'maven' - name = 'org.ethereum' - } -} - -bintrayUpload.onlyIf { - (!pullRequest || pullRequest == 'false') && !project.version.endsWith('-SNAPSHOT') -} - -install { - repositories.mavenInstaller { - customizePom(pom, project) - } -} - -task publish { - - println "publishing if master current branch: " + branchName - description = "Publishes snapshots to oss.jfrog.org and releases to Bintray/JCenter" - dependsOn artifactoryPublish, bintrayUpload -} - - -def customizePom(pom, gradleProject) { - pom.whenConfigured { generatedPom -> - // eliminate test-scoped dependencies (no need in maven central poms) - generatedPom.dependencies.removeAll { dep -> - dep.scope == "test" - } - - // sort to make pom dependencies order consistent to ease comparison of older poms - generatedPom.dependencies = generatedPom.dependencies.sort { dep -> - "$dep.scope:$dep.groupId:$dep.artifactId" - } - - // add all items necessary for maven central publication - generatedPom.project { - name = "ethereumj" - description = "Java implementation of the Ethereum protocol" - url = "https://github.com/ethereum/ethereumj" - organization { - name = "Ethereum" - url = "https://ethereum.org" - } - licenses { - license { - name "The MIT License" - url "http://mit-license.org/" - distribution "repo" - } - } - scm { - url = "https://github.com/ethereum/ethereumj" - connection = "scm:git:git://github.com/ethereum/ethereumj" - developerConnection = "scm:git:git://github.com/ethereum/ethereumj" - } - developers { - developer { - id = "rmandeleil" - name = "Roman Mandeleil" - email = "roman.mandeleil@gmail.com" - } - } - issueManagement { - system = "GitHub Issues" - url = "https://github.com/ethereum/ethereumj/issues" - } - } - } -} diff --git a/ethereumj-core/libs/commons-io-2.4.jar b/ethereumj-core/libs/commons-io-2.4.jar new file mode 100644 index 00000000..90035a4f Binary files /dev/null and b/ethereumj-core/libs/commons-io-2.4.jar differ diff --git a/ethereumj-core/libs/robospring-1.0.7.jar b/ethereumj-core/libs/robospring-1.0.7.jar new file mode 100644 index 00000000..75dfe1ad Binary files /dev/null and b/ethereumj-core/libs/robospring-1.0.7.jar differ diff --git a/ethereumj-core/src/main/AndroidManifest.xml b/ethereumj-core/src/main/AndroidManifest.xml new file mode 100644 index 00000000..ba5d1dbd --- /dev/null +++ b/ethereumj-core/src/main/AndroidManifest.xml @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/ethereumj-core/src/main/java/org/ethereum/MyClass.java b/ethereumj-core/src/main/java/org/ethereum/MyClass.java new file mode 100644 index 00000000..1bf623ce --- /dev/null +++ b/ethereumj-core/src/main/java/org/ethereum/MyClass.java @@ -0,0 +1,26 @@ +package org.ethereum; + +import org.ethereum.cli.CLIInterface; +import org.ethereum.config.SystemProperties; +import org.ethereum.facade.Ethereum; +import org.robospring.RoboSpring; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class MyClass { + + public static ApplicationContext context = null; + + public static void start(android.content.Context androidContext) { + + + //CLIInterface.call(args);RoboSpring.getContext("applicationContext.xml"); + RoboSpring.autowire(androidContext); + context = RoboSpring.getContext(); + Ethereum ethereum = context.getBean(Ethereum.class); + ethereum.setContext(context); + ethereum.connect(SystemProperties.CONFIG.activePeerIP(), + SystemProperties.CONFIG.activePeerPort()); + + } +} diff --git a/ethereumj-core/src/main/java/org/ethereum/cli/CLIInterface.java b/ethereumj-core/src/main/java/org/ethereum/cli/CLIInterface.java index 95bffec4..ab22cee0 100644 --- a/ethereumj-core/src/main/java/org/ethereum/cli/CLIInterface.java +++ b/ethereumj-core/src/main/java/org/ethereum/cli/CLIInterface.java @@ -3,7 +3,7 @@ package org.ethereum.cli; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; +//import org.springframework.stereotype.Component; import static org.ethereum.config.SystemProperties.CONFIG; @@ -11,7 +11,7 @@ import static org.ethereum.config.SystemProperties.CONFIG; * @author Roman Mandeleil * @since 13.11.2014 */ -@Component +//@Component public class CLIInterface { private static final Logger logger = LoggerFactory.getLogger("cli"); diff --git a/ethereumj-core/src/main/java/org/ethereum/core/Account.java b/ethereumj-core/src/main/java/org/ethereum/core/Account.java index 419109a6..40879266 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Account.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Account.java @@ -5,8 +5,8 @@ import org.ethereum.manager.WorldManager; import org.ethereum.util.Utils; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; +//import org.springframework.context.annotation.Scope; +//import org.springframework.stereotype.Component; import java.math.BigInteger; @@ -18,8 +18,8 @@ import java.util.Set; /** * Representation of an actual account or contract */ -@Component -@Scope("prototype") +//@Component +//@Scope("prototype") public class Account { private ECKey ecKey; diff --git a/ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java b/ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java index 61d704bc..0346d2b0 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java @@ -17,10 +17,11 @@ import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; -import org.springframework.util.FileSystemUtils; +//import org.springframework.stereotype.Component; +//import org.springframework.util.FileSystemUtils; +import org.apache.commons.io.FileUtils; -import javax.annotation.Resource; +//import javax.annotation.Resource; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -62,7 +63,7 @@ import static org.ethereum.core.Denomination.SZABO; * @author Nick Savers * @since 20.05.2014 */ -@Component +//@Component public class BlockchainImpl implements Blockchain { /* A scalar value equal to the minimum limit of gas expenditure per block */ @@ -74,8 +75,6 @@ public class BlockchainImpl implements Blockchain { // to avoid using minGasPrice=0 from Genesis for the wallet private static final long INITIAL_MIN_GAS_PRICE = 10 * SZABO.longValue(); - @Resource - @Qualifier("pendingTransactions") private Set pendingTransactions; @Autowired @@ -111,6 +110,10 @@ public class BlockchainImpl implements Blockchain { private List altChains = new ArrayList<>(); private List garbage = new ArrayList<>(); + public BlockchainImpl(final Set pendingTransactions) { + this.pendingTransactions = Collections.synchronizedSet(pendingTransactions); + } + @Override public byte[] getBestBlockHash() { return getBestBlock().getHash(); @@ -352,8 +355,8 @@ public class BlockchainImpl implements Blockchain { receipt.setPostTxState(repository.getRoot()); receipt.setTransaction(tx); - stateLogger.info("block: [{}] executed tx: [{}] \n state: [{}]", block.getNumber(), i, - Hex.toHexString(repository.getRoot())); + //stateLogger.info("block: [{}] executed tx: [{}] \n state: [{}]", block.getNumber(), i, + // Hex.toHexString(repository.getRoot())); stateLogger.info("[{}] ", receipt.toString()); @@ -376,7 +379,7 @@ public class BlockchainImpl implements Blockchain { long totalTime = System.nanoTime() - saveTime; adminInfo.addBlockExecTime(totalTime); - logger.info("block: num: [{}] hash: [{}], executed after: [{}]nano", block.getNumber(), block.getShortHash(), totalTime); + //logger.info("block: num: [{}] hash: [{}], executed after: [{}]nano", block.getNumber(), block.getShortHash(), totalTime); return receipts; } @@ -494,7 +497,12 @@ public class BlockchainImpl implements Blockchain { if (!CONFIG.recordBlocks()) return; if (bestBlock.isGenesis()) { - FileSystemUtils.deleteRecursively(new File(CONFIG.dumpDir())); + //FileSystemUtils.deleteRecursively(new File(CONFIG.dumpDir())); + try{ + FileUtils.forceDelete(new File(CONFIG.dumpDir())); + }catch(IOException e){ + e.printStackTrace(); + } } String dir = CONFIG.dumpDir() + "/"; diff --git a/ethereumj-core/src/main/java/org/ethereum/core/TransactionExecutor.java b/ethereumj-core/src/main/java/org/ethereum/core/TransactionExecutor.java index 392fa54b..cf146c03 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/TransactionExecutor.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/TransactionExecutor.java @@ -170,12 +170,13 @@ public class TransactionExecutor { track.addBalance(receiverAddress, txValue); // balance will be read again below track.addBalance(senderAddress, txValue.negate()); - if (stateLogger.isDebugEnabled()) + /*if (stateLogger.isDebugEnabled()) stateLogger.debug("Update value balance \n " + "sender={}, receiver={}, value={}", Hex.toHexString(senderAddress), Hex.toHexString(receiverAddress), new BigInteger(tx.getValue())); + */ } @@ -243,6 +244,7 @@ public class TransactionExecutor { if (CONFIG.vmTrace()) { String traceAsJson = "{}"; if (program != null) { + ProgramResult result = program.getResult(); ProgramTrace trace = program.getProgramTrace(); trace.setResult(result.getHReturn()); trace.setError(result.getException()); @@ -290,12 +292,13 @@ public class TransactionExecutor { result.getGasUsed()).multiply(gasPrice)); if (refund.signum() > 0) { - if (stateLogger.isDebugEnabled()) + /*if (stateLogger.isDebugEnabled()) stateLogger .debug("After contract execution the sender address refunded with gas leftover, " + "\n sender={} \n contract={} \n gas_refund= {}", Hex.toHexString(senderAddress), Hex.toHexString(contractAddress), refund); + */ // gas refund repository.addBalance(senderAddress, refund); repository.addBalance(coinbase, refund.negate()); @@ -307,12 +310,13 @@ public class TransactionExecutor { BigInteger futureRefundBI = BigInteger.valueOf(futureRefund); BigInteger futureRefundVal = futureRefundBI.multiply(gasPrice); - if (stateLogger.isDebugEnabled()) + /* if (stateLogger.isDebugEnabled()) stateLogger .debug("After contract execution the sender address refunded with storage save refunds, " + "\n sender={} \n contract={} \n gas_refund= {}", Hex.toHexString(senderAddress), Hex.toHexString(contractAddress), futureRefundVal); + */ repository.addBalance(senderAddress, futureRefundVal); repository.addBalance(coinbase, futureRefundVal.negate()); } diff --git a/ethereumj-core/src/main/java/org/ethereum/core/Wallet.java b/ethereumj-core/src/main/java/org/ethereum/core/Wallet.java index c16c50fe..7925f41e 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Wallet.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Wallet.java @@ -12,8 +12,8 @@ import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.DependsOn; -import org.springframework.stereotype.Component; +//import org.springframework.context.annotation.DependsOn; +//import org.springframework.stereotype.Component; import org.w3c.dom.Attr; import org.w3c.dom.Document; @@ -48,8 +48,8 @@ import javax.xml.transform.stream.StreamResult; * The Wallet handles the management of accounts with addresses and private keys. * New accounts can be generated and added to the wallet and existing accounts can be queried. */ -@Component -@DependsOn("worldManager") +//@Component +//@DependsOn("worldManager") public class Wallet { private Logger logger = LoggerFactory.getLogger("wallet"); diff --git a/ethereumj-core/src/main/java/org/ethereum/datasource/InMemoryDbDataSource.java b/ethereumj-core/src/main/java/org/ethereum/datasource/InMemoryDbDataSource.java new file mode 100644 index 00000000..eeb4230c --- /dev/null +++ b/ethereumj-core/src/main/java/org/ethereum/datasource/InMemoryDbDataSource.java @@ -0,0 +1,112 @@ +package org.ethereum.datasource; + +import android.content.Context; + +import org.ethereum.config.SystemProperties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +import static org.iq80.leveldb.impl.Iq80DBFactory.factory; + +/** + * @author Roman Mandeleil + * @since 18.01.2015 + */ +public class InMemoryDbDataSource implements KeyValueDataSource { + + private static final Logger logger = LoggerFactory.getLogger("db"); + + String name; + HashMap db; + private Context context; + + public InMemoryDbDataSource() { + } + + public InMemoryDbDataSource(String name) { + this.name = name; + } + + public void setContext(Context context) { + this.context = context; + } + + @Override + public void init() { + + db = new HashMap(); + } + + + public void destroyDB(File fileLocation) { + logger.debug("Destroying existing database"); + db = new HashMap(); + } + + + @Override + public void setName(String name) { + this.name = name; + } + + @Override + public byte[] get(byte[] key) { + return db.get(key); + } + + @Override + public byte[] put(byte[] key, byte[] value) { + ByteBuffer wrapped = ByteBuffer.wrap(key); + db.put(wrapped, value); + return value; + } + + @Override + public void delete(byte[] key) { + db.remove(key); + } + + @Override + public Set keys() { + + Set keys = new HashSet<>(); + Set bufferKeys = db.keySet(); + + for (Iterator i = bufferKeys.iterator(); i.hasNext();) + { + ByteBuffer key = (ByteBuffer) i.next(); + keys.add(key.array()); + } + + return keys; + } + + @Override + public void updateBatch(Map rows) { + + + for (Map.Entry row : rows.entrySet()) { + ByteBuffer wrapped = ByteBuffer.wrap(row.getKey()); + db.put(wrapped, row.getValue()); + } + } + + @Override + public void close() { + try { + logger.info("Close db: {}", name); + init(); + } catch (Exception e) { + logger.error("Failed to find the db file on the close: {} ", name); + } + } +} diff --git a/ethereumj-core/src/main/java/org/ethereum/datasource/LevelDbDataSource.java b/ethereumj-core/src/main/java/org/ethereum/datasource/LevelDbDataSource.java index d18e2426..f47262ea 100644 --- a/ethereumj-core/src/main/java/org/ethereum/datasource/LevelDbDataSource.java +++ b/ethereumj-core/src/main/java/org/ethereum/datasource/LevelDbDataSource.java @@ -17,8 +17,10 @@ import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.util.Set; +import org.iq80.leveldb.impl.Iq80DBFactory; import static org.iq80.leveldb.impl.Iq80DBFactory.factory; +import android.content.Context; /** * @author Roman Mandeleil @@ -30,6 +32,7 @@ public class LevelDbDataSource implements KeyValueDataSource { String name; private DB db; + private Context context; public LevelDbDataSource() { } @@ -38,6 +41,10 @@ public class LevelDbDataSource implements KeyValueDataSource { this.name = name; } + public void setContext(Context context) { + this.context = context; + } + @Override public void init() { @@ -46,20 +53,26 @@ public class LevelDbDataSource implements KeyValueDataSource { Options options = new Options(); options.createIfMissing(true); options.compressionType(CompressionType.NONE); + org.iq80.leveldb.Logger logger1 = new org.iq80.leveldb.Logger() { + public void log(String message) { + logger.debug(message); + } + }; + options.logger(logger1); try { logger.debug("Opening database"); - File dbLocation = new File(System.getProperty("user.dir") + "/" + - SystemProperties.CONFIG.databaseDir() + "/"); + File dbLocation = context.getDir(SystemProperties.CONFIG.databaseDir(), 0); File fileLocation = new File(dbLocation, name); if (SystemProperties.CONFIG.databaseReset()) { destroyDB(fileLocation); } - logger.debug("Initializing new or existing database: '{}'", name); + logger.debug("Initializing new or existing database: '{}'", fileLocation.getAbsolutePath()); db = factory.open(fileLocation, options); - } catch (IOException ioe) { + } catch (Exception ioe) { + logger.debug("x"); logger.error(ioe.getMessage(), ioe); throw new RuntimeException("Can't initialize database"); } diff --git a/ethereumj-core/src/main/java/org/ethereum/datasource/redis/RedisConnectionImpl.java b/ethereumj-core/src/main/java/org/ethereum/datasource/redis/RedisConnectionImpl.java index 9bca3854..09a2f191 100644 --- a/ethereumj-core/src/main/java/org/ethereum/datasource/redis/RedisConnectionImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/datasource/redis/RedisConnectionImpl.java @@ -5,34 +5,31 @@ import org.ethereum.core.Transaction; import org.ethereum.datasource.KeyValueDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; +//import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.Protocol; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import java.net.URI; import java.util.Map; import java.util.Set; -import static org.springframework.util.StringUtils.isEmpty; +import static org.springframework.util.StringUtils.hasLength; -@Component +//@Component public class RedisConnectionImpl implements RedisConnection { private static final Logger logger = LoggerFactory.getLogger("db"); private JedisPool jedisPool; - @PostConstruct public void tryConnect() { if (!SystemProperties.CONFIG.isRedisEnabled()) return; String redisCloudUrl = System.getenv(REDISCLOUD_URL); - if (isEmpty(redisCloudUrl)) { + if (hasLength(redisCloudUrl)) { logger.info("Cannot connect to Redis. 'REDISCLOUD_URL' environment variable is not defined."); return; } @@ -50,20 +47,23 @@ public class RedisConnectionImpl implements RedisConnection { private static JedisPool createJedisPool(URI redisUri) { String userInfo = redisUri.getUserInfo(); if (StringUtils.hasText(userInfo)) { + /* return new JedisPool(new JedisPoolConfig(), redisUri.getHost(), redisUri.getPort(), Protocol.DEFAULT_TIMEOUT, userInfo.split(":", 2)[1]); + */ } - +/* return new JedisPool(new JedisPoolConfig(), redisUri.getHost(), redisUri.getPort(), Protocol.DEFAULT_TIMEOUT); + */ + return null; } - @PreDestroy public void destroy() { if (jedisPool != null) { jedisPool.destroy(); diff --git a/ethereumj-core/src/main/java/org/ethereum/db/BlockStore.java b/ethereumj-core/src/main/java/org/ethereum/db/BlockStore.java index 1cbfc4a9..9b1f938c 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/BlockStore.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/BlockStore.java @@ -3,7 +3,7 @@ package org.ethereum.db; import org.ethereum.core.Block; import org.ethereum.core.TransactionReceipt; -import org.springframework.transaction.annotation.Transactional; +//import org.springframework.transaction.annotation.Transactional; import java.math.BigInteger; @@ -17,36 +17,36 @@ public interface BlockStore { public byte[] getBlockHashByNumber(long blockNumber); - @Transactional(readOnly = true) + //@Transactional(readOnly = true) Block getBlockByNumber(long blockNumber); - @Transactional(readOnly = true) + //@Transactional(readOnly = true) Block getBlockByHash(byte[] hash); - @Transactional(readOnly = true) + //@Transactional(readOnly = true) @SuppressWarnings("unchecked") List getListOfHashesStartFrom(byte[] hash, int qty); - @Transactional + //@Transactional void deleteBlocksSince(long number); - @Transactional + //@Transactional void saveBlock(Block block, List receipts); - @Transactional(readOnly = true) + //@Transactional(readOnly = true) BigInteger getTotalDifficultySince(long number); - @Transactional(readOnly = true) + //@Transactional(readOnly = true) BigInteger getTotalDifficulty(); - @Transactional(readOnly = true) + //@Transactional(readOnly = true) Block getBestBlock(); - @Transactional(readOnly = true) + //@Transactional(readOnly = true) @SuppressWarnings("unchecked") List getAllBlocks(); - @Transactional + //@Transactional void reset(); TransactionReceipt getTransactionReceiptByHash(byte[] hash); diff --git a/ethereumj-core/src/main/java/org/ethereum/db/BlockStoreImpl.java b/ethereumj-core/src/main/java/org/ethereum/db/BlockStoreImpl.javazz similarity index 89% rename from ethereumj-core/src/main/java/org/ethereum/db/BlockStoreImpl.java rename to ethereumj-core/src/main/java/org/ethereum/db/BlockStoreImpl.javazz index cdca6f36..ec950de1 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/BlockStoreImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/BlockStoreImpl.javazz @@ -8,9 +8,9 @@ import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; +//import org.springframework.stereotype.Repository; +//import org.springframework.transaction.annotation.Propagation; +//import org.springframework.transaction.annotation.Transactional; import java.math.BigInteger; @@ -23,10 +23,11 @@ import java.util.List; */ public class BlockStoreImpl implements BlockStore { + @Autowired private SessionFactory sessionFactory; - public BlockStoreImpl(SessionFactory sessionFactory) { - this.sessionFactory = sessionFactory; + public BlockStoreImpl() { + } @Override @@ -38,7 +39,7 @@ public class BlockStoreImpl implements BlockStore { } @Override - @Transactional(readOnly = true) + //@Transactional(readOnly = true) public Block getBlockByNumber(long blockNumber) { List result = sessionFactory.getCurrentSession(). @@ -52,7 +53,7 @@ public class BlockStoreImpl implements BlockStore { } @Override - @Transactional(readOnly = true) + //@Transactional(readOnly = true) public Block getBlockByHash(byte[] hash) { List result = sessionFactory.getCurrentSession(). @@ -66,7 +67,7 @@ public class BlockStoreImpl implements BlockStore { } @Override - @Transactional(readOnly = true) + //@Transactional(readOnly = true) @SuppressWarnings("unchecked") public List getListOfHashesStartFrom(byte[] hash, int qty) { @@ -89,7 +90,7 @@ public class BlockStoreImpl implements BlockStore { } @Override - @Transactional + //@Transactional public void deleteBlocksSince(long number) { sessionFactory.getCurrentSession(). @@ -100,7 +101,7 @@ public class BlockStoreImpl implements BlockStore { @Override - @Transactional + //@Transactional public void saveBlock(Block block, List receipts) { BlockVO blockVO = new BlockVO(block.getNumber(), block.getHash(), @@ -119,7 +120,7 @@ public class BlockStoreImpl implements BlockStore { } @Override - @Transactional(readOnly = true) + //@Transactional(readOnly = true) public BigInteger getTotalDifficultySince(long number) { return (BigInteger) sessionFactory.getCurrentSession(). @@ -130,7 +131,7 @@ public class BlockStoreImpl implements BlockStore { @Override - @Transactional(readOnly = true) + //@Transactional(readOnly = true) public BigInteger getTotalDifficulty() { return (BigInteger) sessionFactory.getCurrentSession(). @@ -139,7 +140,7 @@ public class BlockStoreImpl implements BlockStore { @Override - @Transactional(readOnly = true) + //@Transactional(readOnly = true) public Block getBestBlock() { Long bestNumber = (Long) @@ -154,7 +155,7 @@ public class BlockStoreImpl implements BlockStore { } @Override - @Transactional(readOnly = true) + //@Transactional(readOnly = true) @SuppressWarnings("unchecked") public List getAllBlocks() { @@ -170,7 +171,7 @@ public class BlockStoreImpl implements BlockStore { } @Override - @Transactional + //@Transactional public void reset() { sessionFactory.getCurrentSession(). createQuery("delete from BlockVO").executeUpdate(); diff --git a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryDummy.java b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryDummy.java index 05e1ebd4..af2fa412 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryDummy.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryDummy.java @@ -74,13 +74,14 @@ public class RepositoryDummy extends RepositoryImpl { accountState.setStateRoot(contractDetails.getStorageHash()); accountState.setCodeHash(sha3(contractDetails.getCode())); worldState.put(hash, accountState); - if (logger.isDebugEnabled()) { + /* if (logger.isDebugEnabled()) { logger.debug("update: [{}],nonce: [{}] balance: [{}] \n [{}]", Hex.toHexString(hash.getData()), accountState.getNonce(), accountState.getBalance(), contractDetails.getStorage()); } + */ } diff --git a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryImpl.java b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryImpl.java index 3d7d1015..53cd4e11 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryImpl.java @@ -18,8 +18,8 @@ import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; -import org.springframework.stereotype.Component; -import org.springframework.util.FileSystemUtils; +import org.apache.commons.io.FileUtils; +//import org.springframework.util.FileSystemUtils; import java.io.BufferedWriter; import java.io.File; @@ -65,17 +65,25 @@ public class RepositoryImpl implements Repository { public RepositoryImpl(KeyValueDataSource detailsDS, KeyValueDataSource stateDS) { + logger.debug("test1"); detailsDS.setName(DETAILS_DB); + logger.debug("test2"); detailsDS.init(); + logger.debug("test3"); this.detailsDS = detailsDS; stateDS.setName(STATE_DB); + logger.debug("test4"); stateDS.init(); + logger.debug("test5"); this.stateDS = stateDS; detailsDB = new DatabaseImpl(detailsDS); + logger.debug("test6"); stateDB = new DatabaseImpl(stateDS); + logger.debug("test7"); worldState = new TrieImpl(stateDB.getDb()); + logger.debug("test8"); } public RepositoryImpl(String detailsDbName, String stateDbName) { @@ -137,14 +145,14 @@ public class RepositoryImpl implements Repository { accountState.setStateRoot(contractDetails.getStorageHash()); accountState.setCodeHash(sha3(contractDetails.getCode())); worldState.update(hash.getData(), accountState.getEncoded()); - if (logger.isDebugEnabled()) { + /*if (logger.isDebugEnabled()) { logger.debug("update: [{}],nonce: [{}] balance: [{}] \n [{}]", Hex.toHexString(hash.getData()), accountState.getNonce(), accountState.getBalance(), contractDetails.getStorage()); } - +*/ } } @@ -193,7 +201,13 @@ public class RepositoryImpl implements Repository { if (block.getNumber() == 0 && txNumber == 0) if (CONFIG.dumpCleanOnRestart()) { - FileSystemUtils.deleteRecursively(new File(CONFIG.dumpDir())); + try{ + FileUtils.forceDelete(new File(CONFIG.dumpDir())); + }catch(IOException e){ + e.printStackTrace(); + } + + //FileSystemUtils.deleteRecursively(new File(CONFIG.dumpDir())); } String dir = CONFIG.dumpDir() + "/"; diff --git a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryTrack.java b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryTrack.java index 73462ea7..25696242 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryTrack.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryTrack.java @@ -125,8 +125,8 @@ public class RepositoryTrack implements Repository { BigInteger saveNonce = accountState.getNonce(); accountState.incrementNonce(); - logger.trace("increase nonce addr: [{}], from: [{}], to: [{}]", Hex.toHexString(addr), - saveNonce, accountState.getNonce()); + //logger.trace("increase nonce addr: [{}], from: [{}], to: [{}]", Hex.toHexString(addr), + // saveNonce, accountState.getNonce()); return accountState.getNonce(); } @@ -140,8 +140,8 @@ public class RepositoryTrack implements Repository { BigInteger saveNonce = accountState.getNonce(); accountState.setNonce(bigInteger); - logger.trace("increase nonce addr: [{}], from: [{}], to: [{}]", Hex.toHexString(addr), - saveNonce, accountState.getNonce()); + //logger.trace("increase nonce addr: [{}], from: [{}], to: [{}]", Hex.toHexString(addr), + // saveNonce, accountState.getNonce()); return accountState.getNonce(); @@ -170,8 +170,8 @@ public class RepositoryTrack implements Repository { BigInteger newBalance = accountState.addToBalance(value); - logger.trace("adding to balance addr: [{}], balance: [{}], delta: [{}]", Hex.toHexString(addr), - newBalance, value); + //logger.trace("adding to balance addr: [{}], balance: [{}], delta: [{}]", Hex.toHexString(addr), + // newBalance, value); return newBalance; } @@ -192,8 +192,8 @@ public class RepositoryTrack implements Repository { @Override public void addStorageRow(byte[] addr, DataWord key, DataWord value) { - logger.trace("add storage row, addr: [{}], key: [{}] val: [{}]", Hex.toHexString(addr), - key.toString(), value.toString()); + //logger.trace("add storage row, addr: [{}], key: [{}] val: [{}]", Hex.toHexString(addr), + // key.toString(), value.toString()); getContractDetails(addr).put(key, value); } diff --git a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryVMTestDummy.java b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryVMTestDummy.java index 2ca0dd3a..34c4a9fd 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryVMTestDummy.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryVMTestDummy.java @@ -71,13 +71,13 @@ public class RepositoryVMTestDummy extends RepositoryImpl{ accountState.setStateRoot(contractDetails.getStorageHash()); accountState.setCodeHash(sha3(contractDetails.getCode())); worldState.put(hash, accountState); - if (logger.isDebugEnabled()) { + /*if (logger.isDebugEnabled()) { logger.debug("update: [{}],nonce: [{}] balance: [{}] \n [{}]", Hex.toHexString(hash.getData()), accountState.getNonce(), accountState.getBalance(), contractDetails.getStorage()); - } + }*/ } diff --git a/ethereumj-core/src/main/java/org/ethereum/facade/CommonConfig.java b/ethereumj-core/src/main/java/org/ethereum/facade/CommonConfig.java index 373226b4..8433c93e 100644 --- a/ethereumj-core/src/main/java/org/ethereum/facade/CommonConfig.java +++ b/ethereumj-core/src/main/java/org/ethereum/facade/CommonConfig.java @@ -1,42 +1,30 @@ package org.ethereum.facade; import org.ethereum.config.SystemProperties; -import org.ethereum.core.Transaction; -import org.ethereum.datasource.KeyValueDataSource; -import org.ethereum.datasource.LevelDbDataSource; -import org.ethereum.datasource.redis.RedisConnection; -import org.ethereum.db.RepositoryImpl; -import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Scope; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.jdbc.datasource.DriverManagerDataSource; -import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; -import org.springframework.transaction.annotation.EnableTransactionManagement; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.ComponentScan; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.context.annotation.Scope; +//import org.springframework.jdbc.datasource.DataSourceTransactionManager; +//import org.springframework.jdbc.datasource.DriverManagerDataSource; +//import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; +//import org.springframework.transaction.annotation.EnableTransactionManagement; -import java.sql.SQLException; -import java.util.Collections; -import java.util.HashSet; import java.util.Properties; -import java.util.Set; -import static org.ethereum.config.SystemProperties.CONFIG; - -@Configuration -@EnableTransactionManagement -@ComponentScan(basePackages = "org.ethereum") +//@Configuration +//@EnableTransactionManagement +//@ComponentScan(basePackages = "org.ethereum") public class CommonConfig { private static final Logger logger = LoggerFactory.getLogger("general"); - @Autowired - private RedisConnection redisConnection; - + //@Autowired + //private RedisConnection redisConnection; +/* @Bean Repository repository() { return new RepositoryImpl(keyValueDataSource(), keyValueDataSource()); @@ -83,7 +71,7 @@ public class CommonConfig { return builder.buildSessionFactory(); } - +*/ private Properties getHibernateProperties() { Properties prop = new Properties(); @@ -100,7 +88,7 @@ public class CommonConfig { return prop; } - +/* @Bean public DataSourceTransactionManager transactionManager() { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); @@ -108,7 +96,8 @@ public class CommonConfig { return dataSourceTransactionManager; } - +*/ + /* @Bean(name = "dataSource") public DriverManagerDataSource dataSource() { @@ -131,5 +120,6 @@ public class CommonConfig { return ds; } + */ } diff --git a/ethereumj-core/src/main/java/org/ethereum/facade/DefaultConfig.java b/ethereumj-core/src/main/java/org/ethereum/facade/DefaultConfig.java index 7b7cf833..da73f8c7 100644 --- a/ethereumj-core/src/main/java/org/ethereum/facade/DefaultConfig.java +++ b/ethereumj-core/src/main/java/org/ethereum/facade/DefaultConfig.java @@ -1,29 +1,29 @@ package org.ethereum.facade; import org.ethereum.db.BlockStore; -import org.ethereum.db.BlockStoreImpl; +import org.ethereum.db.InMemoryBlockStore; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.context.annotation.Import; +//import org.springframework.transaction.annotation.Propagation; +//import org.springframework.transaction.annotation.Transactional; /** * * @author: Roman Mandeleil * Created on: 27/01/2015 01:05 */ -@Configuration -@Import(CommonConfig.class) +//@Configuration +//@Import(CommonConfig.class) public class DefaultConfig { @Autowired CommonConfig commonConfig; - @Bean - @Transactional(propagation = Propagation.SUPPORTS) + //@Bean + //@Transactional(propagation = Propagation.SUPPORTS) public BlockStore blockStore(SessionFactory sessionFactory){ - return new BlockStoreImpl(sessionFactory); + return new InMemoryBlockStore(); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/facade/Ethereum.java b/ethereumj-core/src/main/java/org/ethereum/facade/Ethereum.java index e7712e68..bbb81dc0 100644 --- a/ethereumj-core/src/main/java/org/ethereum/facade/Ethereum.java +++ b/ethereumj-core/src/main/java/org/ethereum/facade/Ethereum.java @@ -7,6 +7,7 @@ import org.ethereum.manager.AdminInfo; import org.ethereum.net.client.PeerClient; import org.ethereum.net.peerdiscovery.PeerInfo; import org.ethereum.net.server.ChannelManager; +import org.springframework.context.ApplicationContext; import java.math.BigInteger; @@ -63,6 +64,8 @@ public interface Ethereum { */ public Set getPeers(); + public void setContext(ApplicationContext context); + public void startPeerDiscovery(); public void stopPeerDiscovery(); diff --git a/ethereumj-core/src/main/java/org/ethereum/facade/EthereumImpl.java b/ethereumj-core/src/main/java/org/ethereum/facade/EthereumImpl.java index f36b8248..9e422772 100644 --- a/ethereumj-core/src/main/java/org/ethereum/facade/EthereumImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/facade/EthereumImpl.java @@ -8,6 +8,7 @@ import org.ethereum.manager.WorldManager; import org.ethereum.net.client.PeerClient; import org.ethereum.net.peerdiscovery.PeerInfo; import org.ethereum.net.server.ChannelManager; +import org.ethereum.net.server.EthereumChannelInitializer; import org.ethereum.net.server.PeerServer; import org.ethereum.net.submit.TransactionExecutor; import org.ethereum.net.submit.TransactionTask; @@ -16,9 +17,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Component; +//import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; import java.math.BigInteger; import java.net.InetAddress; import java.util.HashSet; @@ -26,13 +26,15 @@ import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import org.robospring.RoboSpring; + import static org.ethereum.config.SystemProperties.CONFIG; /** * @author Roman Mandeleil * @since 27.07.2014 */ -@Component +//@Component public class EthereumImpl implements Ethereum { private static final Logger logger = LoggerFactory.getLogger("facade"); @@ -54,9 +56,10 @@ public class EthereumImpl implements Ethereum { public EthereumImpl() { System.out.println(); + logger.info("EthereumImpl constructor"); + //RoboSpring.autowire(ctx); } - @PostConstruct public void init() { worldManager.loadBlockchain(); if (CONFIG.listenPort() > 0) { @@ -70,6 +73,10 @@ public class EthereumImpl implements Ethereum { } } + public void setContext(ApplicationContext ctx) { + this.ctx = ctx; + } + /** * Find a peer but not this one * @@ -180,7 +187,6 @@ public class EthereumImpl implements Ethereum { PeerClient peer = worldManager.getActivePeer(); if (peer == null) { - peer = new PeerClient(); worldManager.setActivePeer(peer); } diff --git a/ethereumj-core/src/main/java/org/ethereum/facade/RemoteConfig.java b/ethereumj-core/src/main/java/org/ethereum/facade/RemoteConfig.java index 31ff3611..e2b12872 100644 --- a/ethereumj-core/src/main/java/org/ethereum/facade/RemoteConfig.java +++ b/ethereumj-core/src/main/java/org/ethereum/facade/RemoteConfig.java @@ -4,19 +4,19 @@ import org.ethereum.db.BlockStore; import org.ethereum.db.InMemoryBlockStore; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.context.annotation.Import; +//import org.springframework.transaction.annotation.Propagation; +//import org.springframework.transaction.annotation.Transactional; /** * * @author: Roman Mandeleil * Created on: 27/01/2015 01:05 */ -@Configuration -@Import(CommonConfig.class) +//@Configuration +//@Import(CommonConfig.class) public class RemoteConfig { @Autowired CommonConfig commonConfig; @@ -24,8 +24,8 @@ public class RemoteConfig { // todo: init total difficulty // todo: init last 1000 blocks - @Bean - @Transactional(propagation = Propagation.SUPPORTS) + //@Bean + //@Transactional(propagation = Propagation.SUPPORTS) public BlockStore blockStore(SessionFactory sessionFactory){ return new InMemoryBlockStore(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/listener/CompositeEthereumListener.java b/ethereumj-core/src/main/java/org/ethereum/listener/CompositeEthereumListener.java index 70709a6f..50f6ffe6 100644 --- a/ethereumj-core/src/main/java/org/ethereum/listener/CompositeEthereumListener.java +++ b/ethereumj-core/src/main/java/org/ethereum/listener/CompositeEthereumListener.java @@ -6,7 +6,7 @@ import org.ethereum.core.TransactionReceipt; import org.ethereum.net.message.Message; import org.ethereum.net.p2p.HelloMessage; -import org.springframework.stereotype.Component; +//import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @@ -16,7 +16,7 @@ import java.util.Set; * @author Roman Mandeleil * @since 12.11.2014 */ -@Component(value = "EthereumListener") +//@Component(value = "EthereumListener") public class CompositeEthereumListener implements EthereumListener { List listeners = new ArrayList<>(); diff --git a/ethereumj-core/src/main/java/org/ethereum/manager/AdminInfo.java b/ethereumj-core/src/main/java/org/ethereum/manager/AdminInfo.java index 3ad36e08..d9e4cf90 100644 --- a/ethereumj-core/src/main/java/org/ethereum/manager/AdminInfo.java +++ b/ethereumj-core/src/main/java/org/ethereum/manager/AdminInfo.java @@ -1,8 +1,7 @@ package org.ethereum.manager; -import org.springframework.stereotype.Component; +//import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @@ -11,7 +10,7 @@ import java.util.List; * @author Roman Mandeleil * @since 11.12.2014 */ -@Component +//@Component public class AdminInfo { @@ -20,7 +19,6 @@ public class AdminInfo { private List blockExecTime = new LinkedList<>(); - @PostConstruct public void init() { startupTimeStamp = System.currentTimeMillis(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/manager/WorldManager.java b/ethereumj-core/src/main/java/org/ethereum/manager/WorldManager.java index bdd7c3c2..221b8757 100644 --- a/ethereumj-core/src/main/java/org/ethereum/manager/WorldManager.java +++ b/ethereumj-core/src/main/java/org/ethereum/manager/WorldManager.java @@ -17,7 +17,7 @@ import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; +//import org.springframework.stereotype.Component; import java.math.BigInteger; @@ -27,9 +27,6 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import static org.ethereum.config.SystemProperties.CONFIG; /** @@ -38,7 +35,7 @@ import static org.ethereum.config.SystemProperties.CONFIG; * @author Roman Mandeleil * @since 01.06.2014 */ -@Component +//@Component public class WorldManager { private static final Logger logger = LoggerFactory.getLogger("general"); @@ -52,7 +49,6 @@ public class WorldManager { @Autowired private Wallet wallet; - @Autowired private PeerClient activePeer; @Autowired @@ -71,7 +67,10 @@ public class WorldManager { @Autowired private EthereumListener listener; - @PostConstruct + public WorldManager() { + logger.info("World manager instantiated"); + } + public void init() { byte[] cowAddr = HashUtil.sha3("cow".getBytes()); wallet.importKey(cowAddr); @@ -164,10 +163,10 @@ public class WorldManager { BigInteger totalDifficulty = blockStore.getTotalDifficulty(); blockchain.setTotalDifficulty(totalDifficulty); - logger.info("*** Loaded up to block [{}] totalDifficulty [{}] with stateRoot [{}]", - blockchain.getBestBlock().getNumber(), - blockchain.getTotalDifficulty().toString(), - Hex.toHexString(blockchain.getBestBlock().getStateRoot())); + //logger.info("*** Loaded up to block [{}] totalDifficulty [{}] with stateRoot [{}]", + // blockchain.getBestBlock().getNumber(), + // blockchain.getTotalDifficulty().toString(), + // Hex.toHexString(blockchain.getBestBlock().getStateRoot())); } if (CONFIG.rootHashStart() != null) { @@ -200,7 +199,6 @@ public class WorldManager { } - @PreDestroy public void close() { stopPeerDiscovery(); repository.close(); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/BlockQueue.java b/ethereumj-core/src/main/java/org/ethereum/net/BlockQueue.java index fcab4b8f..216d3050 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/BlockQueue.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/BlockQueue.java @@ -9,7 +9,7 @@ import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; +//import org.springframework.stereotype.Component; import java.math.BigInteger; @@ -34,7 +34,7 @@ import static org.ethereum.config.SystemProperties.CONFIG; * @author Roman Mandeleil * @since 27.07.2014 */ -@Component +//@Component public class BlockQueue { private static final Logger logger = LoggerFactory.getLogger("blockqueue"); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/MessageQueue.java b/ethereumj-core/src/main/java/org/ethereum/net/MessageQueue.java index 8536a629..d0ffe1ae 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/MessageQueue.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/MessageQueue.java @@ -11,8 +11,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; +//import org.springframework.context.annotation.Scope; +//import org.springframework.stereotype.Component; import java.util.Queue; import java.util.Timer; @@ -36,8 +36,8 @@ import static org.ethereum.net.message.StaticMessages.DISCONNECT_MESSAGE; * * @author Roman Mandeleil */ -@Component -@Scope("prototype") +//@Component +//@Scope("prototype") public class MessageQueue { private static final Logger logger = LoggerFactory.getLogger("net"); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/client/PeerClient.java b/ethereumj-core/src/main/java/org/ethereum/net/client/PeerClient.java index a797c5ec..ad51cf8f 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/client/PeerClient.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/client/PeerClient.java @@ -16,8 +16,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; +//import org.springframework.context.annotation.Scope; +//import org.springframework.stereotype.Component; import static org.ethereum.config.SystemProperties.CONFIG; @@ -26,8 +26,8 @@ import static org.ethereum.config.SystemProperties.CONFIG; * * @see http://netty.io */ -@Component -@Scope("prototype") +//@Component +//@Scope("prototype") public class PeerClient { private static final Logger logger = LoggerFactory.getLogger("net"); @@ -43,6 +43,11 @@ public class PeerClient { @Autowired public EthereumChannelInitializer ethereumChannelInitializer; + + public PeerClient() { + logger.info("Peer client instantiated"); + } + public void connect(String host, int port) { EventLoopGroup workerGroup = new NioEventLoopGroup(); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/EthHandler.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/EthHandler.java index 43012421..8558eca1 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/EthHandler.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/EthHandler.java @@ -19,8 +19,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; +//import org.springframework.context.annotation.Scope; +//import org.springframework.stereotype.Component; import java.math.BigInteger; @@ -50,8 +50,8 @@ import static org.ethereum.net.message.StaticMessages.GET_TRANSACTIONS_MESSAGE; *
  • BLOCKS : Send a list of blocks
  • * */ -@Component -@Scope("prototype") +//@Component +//@Scope("prototype") public class EthHandler extends SimpleChannelInboundHandler { public final static byte VERSION = 54; diff --git a/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pHandler.java b/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pHandler.java index ca6ed13a..893a71e0 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pHandler.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pHandler.java @@ -22,8 +22,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; +//import org.springframework.context.annotation.Scope; +//import org.springframework.stereotype.Component; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -51,8 +51,8 @@ import static org.ethereum.net.message.StaticMessages.*; *
  • PONG : Confirm that they themselves are still alive
  • * */ -@Component -@Scope("prototype") +//@Component +//@Scope("prototype") public class P2pHandler extends SimpleChannelInboundHandler { public final static byte VERSION = 3; diff --git a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/DiscoveryChannel.java b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/DiscoveryChannel.java index 1cc6dc6f..f903adfa 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/DiscoveryChannel.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/DiscoveryChannel.java @@ -27,8 +27,8 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; +//import org.springframework.context.annotation.Scope; +//import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; @@ -39,8 +39,8 @@ import static org.ethereum.config.SystemProperties.CONFIG; * * @see http://netty.io */ -@Component -@Scope("prototype") +//@Component +//@Scope("prototype") public class DiscoveryChannel { private static final Logger logger = LoggerFactory.getLogger("net"); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/PeerDiscovery.java b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/PeerDiscovery.java index 3c9a1b4f..71e3d5a4 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/PeerDiscovery.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/PeerDiscovery.java @@ -7,7 +7,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Component; +//import org.springframework.stereotype.Component; import java.net.InetAddress; import java.net.UnknownHostException; @@ -33,7 +33,7 @@ import static org.ethereum.config.SystemProperties.CONFIG; * @author Roman Mandeleil * @since 22.05.2014 */ -@Component +//@Component public class PeerDiscovery { private static final Logger logger = LoggerFactory.getLogger("peerdiscovery"); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/WorkerThread.java b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/WorkerThread.java index 0b0adddf..d9eb3a20 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/WorkerThread.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/WorkerThread.java @@ -5,8 +5,8 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; +//import org.springframework.context.annotation.Scope; +//import org.springframework.stereotype.Component; import java.util.concurrent.ThreadPoolExecutor; @@ -14,8 +14,8 @@ import java.util.concurrent.ThreadPoolExecutor; * @author Roman Mandeleil * @since 22.05.2014 */ -@Component -@Scope("prototype") +//@Component +//@Scope("prototype") public class WorkerThread implements Runnable { private final static Logger logger = LoggerFactory.getLogger("peerdiscovery"); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/server/Channel.java b/ethereumj-core/src/main/java/org/ethereum/net/server/Channel.java index 15169f57..1fd2e0ed 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/server/Channel.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/server/Channel.java @@ -11,8 +11,8 @@ import org.ethereum.net.wire.MessageDecoder; import org.ethereum.net.wire.MessageEncoder; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; +//import org.springframework.context.annotation.Scope; +//import org.springframework.stereotype.Component; import java.math.BigInteger; @@ -22,8 +22,8 @@ import java.net.InetSocketAddress; * @author Roman Mandeleil * @since 01.11.2014 */ -@Component -@Scope("prototype") +//@Component +//@Scope("prototype") public class Channel { @Autowired diff --git a/ethereumj-core/src/main/java/org/ethereum/net/server/ChannelManager.java b/ethereumj-core/src/main/java/org/ethereum/net/server/ChannelManager.java index a28f9718..b251fbed 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/server/ChannelManager.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/server/ChannelManager.java @@ -9,7 +9,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; +//import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.Collections; @@ -20,13 +20,12 @@ import java.util.Map; import java.util.Timer; import java.util.TimerTask; -import javax.annotation.PostConstruct; /** * @author Roman Mandeleil * @since 11.11.2014 */ -@Component +//@Component public class ChannelManager { private static final Logger logger = LoggerFactory.getLogger("net"); @@ -43,7 +42,6 @@ public class ChannelManager { } - @PostConstruct public void init() { scheduleChannelCollector(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/server/EthereumChannelInitializer.java b/ethereumj-core/src/main/java/org/ethereum/net/server/EthereumChannelInitializer.java index 2c550188..7a6fd020 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/server/EthereumChannelInitializer.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/server/EthereumChannelInitializer.java @@ -15,7 +15,7 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Component; +//import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; @@ -25,7 +25,7 @@ import static org.ethereum.config.SystemProperties.CONFIG; * @author Roman Mandeleil * @since 01.11.2014 */ -@Component +//@Component public class EthereumChannelInitializer extends ChannelInitializer { private static final Logger logger = LoggerFactory.getLogger("net"); @@ -43,6 +43,7 @@ public class EthereumChannelInitializer extends ChannelInitializer { public final static byte VERSION = 1; diff --git a/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageDecoder.java b/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageDecoder.java index 68b5e98f..c35a63d2 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageDecoder.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageDecoder.java @@ -15,16 +15,16 @@ import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; +//import org.springframework.context.annotation.Scope; +//import org.springframework.stereotype.Component; import java.util.List; /** * The PacketDecoder parses every valid Ethereum packet to a Message object */ -@Component -@Scope("prototype") +//@Component +//@Scope("prototype") public class MessageDecoder extends ByteToMessageDecoder { private static final Logger loggerWire = LoggerFactory.getLogger("wire"); @@ -80,8 +80,8 @@ public class MessageDecoder extends ByteToMessageDecoder { // Don't have the full message yet long msgSize = in.getInt(in.readerIndex()); if (msgSize > in.readableBytes()) { - loggerWire.trace("msg decode: magicBytes: [{}], readBytes: [{}] / msgSize: [{}] ", - syncToken, in.readableBytes(), msgSize); + //loggerWire.trace("msg decode: magicBytes: [{}], readBytes: [{}] / msgSize: [{}] ", + // syncToken, in.readableBytes(), msgSize); in.resetReaderIndex(); return false; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageEncoder.java b/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageEncoder.java index 32f4b388..85d15b5b 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageEncoder.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageEncoder.java @@ -15,14 +15,14 @@ import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Scope; -import org.springframework.stereotype.Component; +//import org.springframework.context.annotation.Scope; +//import org.springframework.stereotype.Component; /** * The PacketEncoder encodes the message and adds a sync token to every packet. */ -@Component -@Scope("prototype") +//@Component +//@Scope("prototype") public class MessageEncoder extends MessageToByteEncoder { private static final Logger loggerWire = LoggerFactory.getLogger("wire"); diff --git a/ethereumj-core/src/main/java/org/ethereum/util/AdvancedDeviceUtils.java b/ethereumj-core/src/main/java/org/ethereum/util/AdvancedDeviceUtils.java index f5e0b9ee..f75f92f6 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/AdvancedDeviceUtils.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/AdvancedDeviceUtils.java @@ -1,6 +1,6 @@ package org.ethereum.util; -import org.apache.log4j.PropertyConfigurator; +//import org.apache.log4j.PropertyConfigurator; import java.net.URL; @@ -16,7 +16,7 @@ public class AdvancedDeviceUtils { // here we can turn on the detail tracing in the middle of the chain if (blockNum >= CONFIG.traceStartBlock() && CONFIG.traceStartBlock() != -1) { URL configFile = ClassLoader.getSystemResource("log4j-detailed.properties"); - PropertyConfigurator.configure(configFile); + //PropertyConfigurator.configure(configFile); } } } diff --git a/ethereumj-core/src/main/java/org/ethereum/util/Utils.java b/ethereumj-core/src/main/java/org/ethereum/util/Utils.java index 0d4eeb82..0c141b3a 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/Utils.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/Utils.java @@ -16,8 +16,6 @@ import java.util.Date; import java.util.List; import java.util.regex.Pattern; -import javax.swing.*; - public class Utils { private static SecureRandom random = new SecureRandom(); @@ -48,13 +46,7 @@ public class Utils { return formatter.format(date); } - public static ImageIcon getImageIcon(String resource) { - URL imageURL = ClassLoader.getSystemResource(resource); - ImageIcon image = new ImageIcon(imageURL); - return image; - } - - static BigInteger _1000_ = new BigInteger("1000"); + static BigInteger _1000_ = new BigInteger("1000"); public static String getValueShortString(BigInteger number) { BigInteger result = number; diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/Program.java b/ethereumj-core/src/main/java/org/ethereum/vm/Program.java index 8f13897d..f7244d38 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/Program.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/Program.java @@ -20,9 +20,10 @@ import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.*; +import static java.lang.String.format; import static org.ethereum.config.SystemProperties.CONFIG; import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; -import static org.springframework.util.StringUtils.isEmpty; +import static org.springframework.util.StringUtils.hasLength; /** * @author Roman Mandeleil @@ -190,8 +191,7 @@ public class Program { */ public void stackRequire(int stackSize) { if (stack.size() < stackSize) { - throw new StackTooSmallException("Expected: " + stackSize - + ", found: " + stack.size()); + throw Program.Exception.tooSmallStack(stackSize, stack.size()); } } @@ -445,17 +445,18 @@ public class Program { // FETCH THE CODE byte[] programCode = this.result.getRepository().getCode(codeAddress); - if (logger.isInfoEnabled()) +/* if (logger.isInfoEnabled()) logger.info(msg.getType().name() + " for existing contract: address: [{}], outDataOffs: [{}], outDataSize: [{}] ", Hex.toHexString(contextAddress), msg.getOutDataOffs().longValue(), msg.getOutDataSize().longValue()); - +*/ // 2.1 PERFORM THE GAS VALUE TX // (THIS STAGE IS NOT REVERTED BY ANY EXCEPTION) if (this.getGas().longValue() - msg.getGas().longValue() < 0) { - gasLogger.info("No gas for the internal call, \n" + - "fromAddress={}, codeAddress={}", + OutOfGasException ex = new OutOfGasException("Not enough gas for the internal call: fromAddress[%s], codeAddress[%s];", Hex.toHexString(senderAddress), Hex.toHexString(codeAddress)); - throw new OutOfGasException(); + gasLogger.info(ex.getMessage()); + + throw ex; } BigInteger endowment = msg.getEndowment().value(); @@ -545,11 +546,12 @@ public class Program { } public void spendGas(long gasValue, String cause) { - gasLogger.info("[{}] Spent for cause: [{}], gas: [{}]", invokeHash, cause, gasValue); + //gasLogger.info("[{}] Spent for cause: [{}], gas: [{}]", invokeHash, cause, gasValue); long afterSpend = invokeData.getGas().longValue() - gasValue - result.getGasUsed(); - if (afterSpend < 0) - throw new OutOfGasException(); + if (afterSpend < 0) { + throw Program.Exception.notEnoughSpendingGas(cause, gasValue, this); + } result.spendGas(gasValue); } @@ -558,7 +560,7 @@ public class Program { } public void refundGas(long gasValue, String cause) { - gasLogger.info("[{}] Refund for cause: [{}], gas: [{}]", invokeHash, cause, gasValue); + //gasLogger.info("[{}] Refund for cause: [{}], gas: [{}]", invokeHash, cause, gasValue); result.refundGas(gasValue); } @@ -700,7 +702,7 @@ public class Program { secondLine.append(ByteUtil.oneByteToHexString(value)).append(" "); if ((i + 1) % 8 == 0) { - String tmp = String.format("%4s", Integer.toString(i - 7, 16)).replace(" ", "0"); + String tmp = format("%4s", Integer.toString(i - 7, 16)).replace(" ", "0"); memoryData.append("").append(tmp).append(" "); memoryData.append(firstLine).append(" "); memoryData.append(secondLine); @@ -744,7 +746,7 @@ public class Program { oneLine.append(ByteUtil.oneByteToHexString(value)).append(" "); if ((i + 1) % 16 == 0) { - String tmp = String.format("[%4s]-[%4s]", Integer.toString(i - 15, 16), + String tmp = format("[%4s]-[%4s]", Integer.toString(i - 15, 16), Integer.toString(i, 16)).replace(" ", "0"); memoryData.append("").append(tmp).append(" "); memoryData.append(oneLine); @@ -773,11 +775,11 @@ public class Program { logger.trace(" -- STACK -- {}", stackData); logger.trace(" -- MEMORY -- {}", memoryData); logger.trace(" -- STORAGE -- {}\n", storageData); - logger.trace("\n Spent Gas: [{}]/[{}]\n Left Gas: [{}]\n", + /*logger.trace("\n Spent Gas: [{}]/[{}]\n Left Gas: [{}]\n", result.getGasUsed(), invokeData.getGas().longValue(), getGas().longValue()); - +*/ StringBuilder globalOutput = new StringBuilder("\n"); if (stackData.length() > 0) stackData.append("\n"); @@ -826,7 +828,7 @@ public class Program { public void saveProgramTraceToFile(String fileName) { - if (!CONFIG.vmTrace() || isEmpty(CONFIG.vmTraceDir())) return; + if (!CONFIG.vmTrace() || hasLength(CONFIG.vmTraceDir())) return; String dir = CONFIG.databaseDir() + "/" + CONFIG.vmTraceDir() + "/"; @@ -840,7 +842,7 @@ public class Program { fw = new FileWriter(dumpFile.getAbsoluteFile()); bw = new BufferedWriter(fw); - bw.write(programTrace.asJsonString()); + bw.write(programTrace.asJsonString(true)); } catch (IOException e) { logger.error(e.getMessage(), e); } finally { @@ -876,12 +878,13 @@ public class Program { if (code == null || code.length == 0) return result; - OpCode op = OpCode.code(code[index]); + final byte opCode = code[index]; + OpCode op = OpCode.code(opCode); + if (op == null) { + throw Program.Exception.invalidOpCode(opCode); + } + final byte[] continuedCode; - - if (op == null) throw new IllegalOperationException("Invalid operation: " + - Hex.toHexString(code, index, 1)); - switch(op) { case PUSH1: case PUSH2: case PUSH3: case PUSH4: case PUSH5: case PUSH6: case PUSH7: case PUSH8: case PUSH9: case PUSH10: case PUSH11: case PUSH12: case PUSH13: case PUSH14: case PUSH15: case PUSH16: @@ -909,7 +912,9 @@ public class Program { } public void validateJumpDest(int nextPC) { - if (!jumpdest.contains(nextPC)) throw new BadJumpDestinationException(); + if (!jumpdest.contains(nextPC)) { + throw Program.Exception.badJumpDestination(nextPC); + } } public void callToPrecompiledAddress(MessageCall msg, PrecompiledContract contract) { @@ -951,27 +956,68 @@ public class Program { } @SuppressWarnings("serial") - public class OutOfGasException extends RuntimeException { + public static class OutOfGasException extends RuntimeException { + + public OutOfGasException(String message, Object... args) { + super(format(message, args)); + } } @SuppressWarnings("serial") public static class IllegalOperationException extends RuntimeException { - public IllegalOperationException(String message) { - super(message); - } - - public IllegalOperationException() { + + public IllegalOperationException(String message, Object... args) { + super(format(message, args)); } } @SuppressWarnings("serial") - public class BadJumpDestinationException extends RuntimeException { + public static class BadJumpDestinationException extends RuntimeException { + + public BadJumpDestinationException(String message, Object... args) { + super(format(message, args)); + } } @SuppressWarnings("serial") - public class StackTooSmallException extends RuntimeException { - public StackTooSmallException(String message) { - super(message); + public static class StackTooSmallException extends RuntimeException { + + public StackTooSmallException(String message, Object... args) { + super(format(message, args)); + } + } + + public static class Exception { + + public static OutOfGasException notEnoughOpGas(OpCode op, long opGas, long programGas) { + return new OutOfGasException("Not enough gas for '%s' operation executing: opGas[%d], programGas[%d];", op, opGas, programGas); + } + public static OutOfGasException notEnoughOpGas(OpCode op, DataWord opGas, DataWord programGas) { + return notEnoughOpGas(op, opGas.longValue(), programGas.longValue()); + } + public static OutOfGasException notEnoughOpGas(OpCode op, BigInteger opGas, BigInteger programGas) { + return notEnoughOpGas(op, opGas.longValue(), programGas.longValue()); + } + + public static OutOfGasException notEnoughSpendingGas(String cause, long gasValue, Program program) { + return new OutOfGasException("Not enough gas for '%s' cause spending: invokeGas[%d], gas[%d], usedGas[%d];", + cause, program.invokeData.getGas().longValue(), gasValue, program.result.getGasUsed()); + } + + public static OutOfGasException gasOverflow(BigInteger actualGas, BigInteger gasLimit) { + return new OutOfGasException("Gas value overflow: actualGas[%d], gasLimit[%d];", actualGas.longValue(), gasLimit.longValue()); + } + + public static IllegalOperationException invalidOpCode(byte... opCode) { + return new IllegalOperationException("Invalid operation code: opCode[%s];", Hex.toHexString(opCode, 0, 1)); + } + + public static BadJumpDestinationException badJumpDestination(int pc) { + return new BadJumpDestinationException("Operation with pc isn't 'JUMPDEST': PC[%d];", pc); + } + + public static StackTooSmallException tooSmallStack(int expectedSize, int actualSize) { + return new StackTooSmallException("Expected stack size %d but actual %d;", expectedSize, actualSize); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactoryImpl.java b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactoryImpl.java index ae0957b6..b4d5cd42 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactoryImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactoryImpl.java @@ -13,7 +13,7 @@ import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; +//import org.springframework.stereotype.Component; import java.math.BigInteger; @@ -21,7 +21,7 @@ import java.math.BigInteger; * @author Roman Mandeleil * @since 08.06.2014 */ -@Component("ProgramInvokeFactory") +//@Component("ProgramInvokeFactory") public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { private static final Logger logger = LoggerFactory.getLogger("VM"); @@ -84,7 +84,7 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { /*** GASLIMIT op ***/ long gaslimit = block.getGasLimit(); - +/* if (logger.isInfoEnabled()) { logger.info("Top level call: \n" + "address={}\n" + @@ -117,7 +117,7 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { Hex.toHexString(difficulty), gaslimit); } - +*/ return new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, data, lastHash, coinbase, timestamp, number, difficulty, gaslimit, repository, blockStore); @@ -148,7 +148,7 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { DataWord number = program.getNumber(); DataWord difficulty = program.getDifficulty(); DataWord gasLimit = program.getGaslimit(); - +/* if (logger.isInfoEnabled()) { logger.info("Internal call: \n" + "address={}\n" + @@ -180,7 +180,7 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { Hex.toHexString(difficulty.getNoLeadZeroesData()), gasLimit.longValue()); } - +*/ return new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, data, lastHash, coinbase, timestamp, number, difficulty, gasLimit, repository, program.invokeData.getCallDeep() + 1, blockStore, byTestingSuite); diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/VM.java b/ethereumj-core/src/main/java/org/ethereum/vm/VM.java index e1cb791a..95b9109d 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/VM.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/VM.java @@ -4,16 +4,12 @@ import org.ethereum.crypto.HashUtil; import org.ethereum.db.ContractDetails; import org.ethereum.util.ByteUtil; import org.ethereum.vm.MessageCall.MsgType; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; - import org.spongycastle.util.encoders.Hex; import java.math.BigInteger; - import java.nio.ByteBuffer; - import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -79,8 +75,9 @@ public class VM { try { OpCode op = OpCode.code(program.getCurrentOp()); - if (op == null) - throw new Program.IllegalOperationException(); + if (op == null) { + throw Program.Exception.invalidOpCode(program.getCurrentOp()); + } program.setLastOp(op.val()); program.stackRequire(op.require()); @@ -161,7 +158,7 @@ public class VM { gasCost = GasCost.CALL; DataWord callGasWord = stack.get(stack.size() - 1); if (callGasWord.compareTo(program.getGas()) == 1) { - throw program.new OutOfGasException(); + throw Program.Exception.notEnoughOpGas(op, callGasWord, program.getGas()); } callGas = callGasWord.longValue(); BigInteger in = memNeeded(stack.get(stack.size() - 4), stack.get(stack.size() - 5)); // in offset+size @@ -184,7 +181,7 @@ public class VM { BigInteger dataSize = stack.get(stack.size() - 2).value(); BigInteger dataCost = dataSize.multiply(BigInteger.valueOf(GasCost.LOG_DATA_GAS)); if (program.getGas().value().compareTo(dataCost) < 0) { - throw program.new OutOfGasException(); + throw Program.Exception.notEnoughOpGas(op, dataCost, program.getGas().value()); } gasCost = GasCost.LOG_GAS + @@ -203,8 +200,9 @@ public class VM { program.spendGas(gasCost, op.name()); // Avoid overflows - if (newMemSize.compareTo(MAX_GAS) == 1) - throw program.new OutOfGasException(); + if (newMemSize.compareTo(MAX_GAS) == 1) { + throw Program.Exception.gasOverflow(newMemSize, MAX_GAS); + } // memory gas calc long memoryUsage = (newMemSize.longValue() + 31) / 32 * 32; @@ -1008,13 +1006,13 @@ public class VM { DataWord value = program.stackPop(); DataWord inOffset = program.stackPop(); DataWord inSize = program.stackPop(); - +/* if (logger.isInfoEnabled()) logger.info(logString, program.getPC(), String.format("%-12s", op.name()), program.getGas().value(), program.invokeData.getCallDeep(), hint); - +*/ program.createContract(value, inOffset, inSize); program.step(); @@ -1031,7 +1029,7 @@ public class VM { DataWord outDataOffs = program.stackPop(); DataWord outDataSize = program.stackPop(); - +/* if (logger.isInfoEnabled()) { hint = "addr: " + Hex.toHexString(codeAddress.getLast20Bytes()) + " gas: " + gas.shortHex() @@ -1042,7 +1040,7 @@ public class VM { program.getGas().value(), program.invokeData.getCallDeep(), hint); } - +*/ program.memoryExpand(outDataOffs, outDataSize); MessageCall msg = new MessageCall( @@ -1092,13 +1090,13 @@ public class VM { } program.setPreviouslyExecutedOp(op.val()); - +/* if (logger.isInfoEnabled() && !op.equals(CALL) && !op.equals(CREATE)) logger.info(logString, stepBefore, String.format("%-12s", op.name()), program.getGas().longValue(), program.invokeData.getCallDeep(), hint); - +*/ vmCounter++; } catch (RuntimeException e) { logger.warn("VM halted: [{}]", e.toString()); @@ -1183,7 +1181,7 @@ public class VM { String opString = Hex.toHexString(new byte[]{op.val()}); String gasString = Hex.toHexString(program.getGas().getNoLeadZeroesData()); - dumpLogger.trace("{} {} {} {}", addressString, pcString, opString, gasString); + //dumpLogger.trace("{} {} {} {}", addressString, pcString, opString, gasString); } else if (CONFIG.dumpStyle().equals("pretty")) { dumpLogger.trace(" STACK"); for (DataWord item : program.getStack()) { @@ -1209,9 +1207,9 @@ public class VM { int level = program.invokeData.getCallDeep(); String contract = Hex.toHexString(program.getOwnerAddress().getLast20Bytes()); String internalSteps = String.format("%4s", Integer.toHexString(program.getPC())).replace(' ', '0').toUpperCase(); - dumpLogger.trace("{} | {} | #{} | {} : {} | {} | -{} | {}x32", - level, contract, vmCounter, internalSteps, op, - gasBefore, gasCost, memWords); + //dumpLogger.trace("{} | {} | #{} | {} : {} | {} | -{} | {}x32", + // level, contract, vmCounter, internalSteps, op, + // gasBefore, gasCost, memWords); } } } diff --git a/ethereumj-core/src/main/java/org/ethereum/vmtrace/ProgramTrace.java b/ethereumj-core/src/main/java/org/ethereum/vmtrace/ProgramTrace.java index d530ffad..96f27648 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vmtrace/ProgramTrace.java +++ b/ethereumj-core/src/main/java/org/ethereum/vmtrace/ProgramTrace.java @@ -19,8 +19,8 @@ public class ProgramTrace { @JsonIgnore private byte[] txHash; private List ops = new ArrayList<>(); - private String result; - private String error; + private String result = ""; + private String error = ""; public void setTxHash(byte[] txHash) { this.txHash = txHash; @@ -31,7 +31,7 @@ public class ProgramTrace { } public void setError(Exception error) { - this.error = (error == null) ? "" : format("%s: %s", error.getClass(), error.getMessage()); + this.error = (error == null) ? "" : format("%s: %s", error.getClass().getSimpleName(), error.getMessage()); } public void addOp(Op op) { @@ -46,7 +46,11 @@ public class ProgramTrace { this.ops.addAll(programTrace.ops); } + public String asJsonString(boolean needPrettify) { + return serializeFieldsOnly(this, needPrettify); + } + public String asJsonString() { - return serializeFieldsOnly(this, true); + return asJsonString(false); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/wallet/EtherSaleWallet.java b/ethereumj-core/src/main/java/org/ethereum/wallet/EtherSaleWallet.java index 059f63a1..2b424d42 100644 --- a/ethereumj-core/src/main/java/org/ethereum/wallet/EtherSaleWallet.java +++ b/ethereumj-core/src/main/java/org/ethereum/wallet/EtherSaleWallet.java @@ -1,6 +1,6 @@ package org.ethereum.wallet; -import javax.xml.bind.DatatypeConverter; +//import javax.xml.bind.DatatypeConverter; public class EtherSaleWallet { @@ -14,7 +14,7 @@ public class EtherSaleWallet { } public byte[] getEncseedBytes() { - return DatatypeConverter.parseHexBinary(encseed); + return hexStringToByteArray(encseed); } public void setEncseed(String encseed) { @@ -26,7 +26,7 @@ public class EtherSaleWallet { } public byte[] getEthaddrBytes() { - return DatatypeConverter.parseHexBinary(ethaddr); + return hexStringToByteArray(ethaddr); } public void setEthaddr(String ethaddr) { @@ -58,4 +58,14 @@ public class EtherSaleWallet { ", btcaddr='" + btcaddr + '\'' + '}'; } + + public static byte[] hexStringToByteArray(String s) { + int len = s.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + + Character.digit(s.charAt(i+1), 16)); + } + return data; + } } diff --git a/ethereumj-core/src/main/res/values/strings.xml b/ethereumj-core/src/main/res/values/strings.xml new file mode 100644 index 00000000..da39591f --- /dev/null +++ b/ethereumj-core/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + ethereum-core + diff --git a/ethereumj-core/src/main/resources/applicationContext.xml b/ethereumj-core/src/main/resources/applicationContext.xml new file mode 100644 index 00000000..116e1896 --- /dev/null +++ b/ethereumj-core/src/main/resources/applicationContext.xml @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index 8b70caf6..41183122 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1 @@ -include ':app', ':ethereum-core' +include ':app', ':ethereumj-core'