Succesfull app run:

Replaced spring framework with robospring.
Changed ethereumj-core build to android-library.
Disabled BlockStoreImpl until we make it android compatible( use InMemoryBlockstore ).
Disabled antlr4 dependencies.
Commented some dependencies(needs testing before enabling).
Excluded dom4j and org.jboss.spec.javax.transaction dependencies (problems with android).
Change to netty 4.0.18.Final (this seems to work with android; latest 4.1 and 5.0 presented some problems; needs additional testing).
This commit is contained in:
Adrian Tiberius 2015-04-28 20:08:04 +02:00
parent 781e23ec70
commit 3d3e8f82c5
52 changed files with 776 additions and 501 deletions

View File

@ -1,243 +1,144 @@
buildscript { apply plugin: 'com.android.library'
repositories { repositories {
jcenter() maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
mavenCentral()
maven { url 'http://repo.spring.io/plugins-release-local' } maven { url 'http://repo.spring.io/plugins-release-local' }
}
dependencies { flatDir {
classpath 'org.springframework.build.gradle:propdeps-plugin:0.0.7' dirs "libs"
classpath 'org.jfrog.buildinfo:build-info-extractor-gradle:3.0.1'
} }
} }
plugins { android {
id 'application' compileSdkVersion 21
id 'jacoco' buildToolsVersion "21.1.2"
id 'com.github.johnrengelman.shadow' version '1.2.0'
id 'me.champeau.gradle.antlr4' version '0.1' defaultConfig {
id 'com.github.kt3k.coveralls' version '2.0.1x' minSdkVersion 14
id 'com.jfrog.bintray' version '1.0' targetSdkVersion 21
versionCode 1
versionName "1.0"
} }
apply plugin: 'propdeps-maven' buildTypes {
apply plugin: 'com.jfrog.artifactory-upload' release {
minifyEnabled false
sourceCompatibility = 1.7 proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
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"
} }
systemProperty "file.encoding", "UTF-8"
} }
//ext.generatedSrcDir = file('src/gen/java')
configurations { //sourceSets.main.java.srcDirs += generatedSrcDir
compile.extendsFrom antlr4
} //antlr4 {
// extraArgs = ['-package', 'org.ethereum.serpent']
// output = file("${generatedSrcDir}/org/ethereum/serpent")
//}
//compileJava.dependsOn antlr4
ext { ext {
slf4jVersion = '1.7.7' slf4jVersion = '1.7.7'
leveldbVersion = '0.7' leveldbVersion = '0.7'
scastleVersion = '1.51.0.0' scastleVersion = '1.51.0.0'
log4jVersion = '1.2.17' log4jVersion = '1.2.17'
springVersion = '4.1.2.RELEASE'
hibernateVersion = '4.3.7.Final' hibernateVersion = '4.3.7.Final'
junitVersion = '4.11' junitVersion = '4.11'
} }
dependencies { dependencies {
compile "io.netty:netty-all:4.0.23.Final" //compile 'com.android.support:appcompat-v7:+'
compile "com.madgag.spongycastle:core:${scastleVersion}" // for SHA3 and SECP256K1 compile fileTree(include: ['*.jar'], dir: 'libs')
compile "com.madgag.spongycastle:prov:${scastleVersion}" // for SHA3 and SECP256K1 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 "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: '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:jcl-over-slf4j:${slf4jVersion}"
optional "org.slf4j:slf4j-log4j12:${slf4jVersion}" //optional "de.mindpipe.android:android-logging-log4j:1.0.2"
optional "log4j:apache-log4j-extras:${log4jVersion}"
//optional "log4j:apache-log4j-extras:${log4jVersion}"
testCompile "junit:junit:${junitVersion}" testCompile "junit:junit:${junitVersion}"
testCompile "org.springframework:spring-test:${springVersion}" //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'
}
}
} }
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"
}
}
}
}

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.ethereum" >
<application android:allowBackup="true" android:label="@string/app_name">
</application>
</manifest>

View File

@ -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());
}
}

View File

@ -3,7 +3,7 @@ package org.ethereum.cli;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import static org.ethereum.config.SystemProperties.CONFIG; import static org.ethereum.config.SystemProperties.CONFIG;
@ -11,7 +11,7 @@ import static org.ethereum.config.SystemProperties.CONFIG;
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 13.11.2014 * @since 13.11.2014
*/ */
@Component //@Component
public class CLIInterface { public class CLIInterface {
private static final Logger logger = LoggerFactory.getLogger("cli"); private static final Logger logger = LoggerFactory.getLogger("cli");

View File

@ -5,8 +5,8 @@ import org.ethereum.manager.WorldManager;
import org.ethereum.util.Utils; import org.ethereum.util.Utils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.math.BigInteger; import java.math.BigInteger;
@ -18,8 +18,8 @@ import java.util.Set;
/** /**
* Representation of an actual account or contract * Representation of an actual account or contract
*/ */
@Component //@Component
@Scope("prototype") //@Scope("prototype")
public class Account { public class Account {
private ECKey ecKey; private ECKey ecKey;

View File

@ -17,10 +17,11 @@ import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import org.springframework.util.FileSystemUtils; //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.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
@ -62,7 +63,7 @@ import static org.ethereum.core.Denomination.SZABO;
* @author Nick Savers * @author Nick Savers
* @since 20.05.2014 * @since 20.05.2014
*/ */
@Component //@Component
public class BlockchainImpl implements Blockchain { public class BlockchainImpl implements Blockchain {
/* A scalar value equal to the minimum limit of gas expenditure per block */ /* 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 // to avoid using minGasPrice=0 from Genesis for the wallet
private static final long INITIAL_MIN_GAS_PRICE = 10 * SZABO.longValue(); private static final long INITIAL_MIN_GAS_PRICE = 10 * SZABO.longValue();
@Resource
@Qualifier("pendingTransactions")
private Set<Transaction> pendingTransactions; private Set<Transaction> pendingTransactions;
@Autowired @Autowired
@ -111,6 +110,10 @@ public class BlockchainImpl implements Blockchain {
private List<Chain> altChains = new ArrayList<>(); private List<Chain> altChains = new ArrayList<>();
private List<Block> garbage = new ArrayList<>(); private List<Block> garbage = new ArrayList<>();
public BlockchainImpl(final Set<Transaction> pendingTransactions) {
this.pendingTransactions = Collections.synchronizedSet(pendingTransactions);
}
@Override @Override
public byte[] getBestBlockHash() { public byte[] getBestBlockHash() {
return getBestBlock().getHash(); return getBestBlock().getHash();
@ -352,8 +355,8 @@ public class BlockchainImpl implements Blockchain {
receipt.setPostTxState(repository.getRoot()); receipt.setPostTxState(repository.getRoot());
receipt.setTransaction(tx); receipt.setTransaction(tx);
stateLogger.info("block: [{}] executed tx: [{}] \n state: [{}]", block.getNumber(), i, //stateLogger.info("block: [{}] executed tx: [{}] \n state: [{}]", block.getNumber(), i,
Hex.toHexString(repository.getRoot())); // Hex.toHexString(repository.getRoot()));
stateLogger.info("[{}] ", receipt.toString()); stateLogger.info("[{}] ", receipt.toString());
@ -376,7 +379,7 @@ public class BlockchainImpl implements Blockchain {
long totalTime = System.nanoTime() - saveTime; long totalTime = System.nanoTime() - saveTime;
adminInfo.addBlockExecTime(totalTime); 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; return receipts;
} }
@ -494,7 +497,12 @@ public class BlockchainImpl implements Blockchain {
if (!CONFIG.recordBlocks()) return; if (!CONFIG.recordBlocks()) return;
if (bestBlock.isGenesis()) { 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() + "/"; String dir = CONFIG.dumpDir() + "/";

View File

@ -170,12 +170,13 @@ public class TransactionExecutor {
track.addBalance(receiverAddress, txValue); // balance will be read again below track.addBalance(receiverAddress, txValue); // balance will be read again below
track.addBalance(senderAddress, txValue.negate()); track.addBalance(senderAddress, txValue.negate());
if (stateLogger.isDebugEnabled()) /*if (stateLogger.isDebugEnabled())
stateLogger.debug("Update value balance \n " stateLogger.debug("Update value balance \n "
+ "sender={}, receiver={}, value={}", + "sender={}, receiver={}, value={}",
Hex.toHexString(senderAddress), Hex.toHexString(senderAddress),
Hex.toHexString(receiverAddress), Hex.toHexString(receiverAddress),
new BigInteger(tx.getValue())); new BigInteger(tx.getValue()));
*/
} }
@ -243,6 +244,7 @@ public class TransactionExecutor {
if (CONFIG.vmTrace()) { if (CONFIG.vmTrace()) {
String traceAsJson = "{}"; String traceAsJson = "{}";
if (program != null) { if (program != null) {
ProgramResult result = program.getResult();
ProgramTrace trace = program.getProgramTrace(); ProgramTrace trace = program.getProgramTrace();
trace.setResult(result.getHReturn()); trace.setResult(result.getHReturn());
trace.setError(result.getException()); trace.setError(result.getException());
@ -290,12 +292,13 @@ public class TransactionExecutor {
result.getGasUsed()).multiply(gasPrice)); result.getGasUsed()).multiply(gasPrice));
if (refund.signum() > 0) { if (refund.signum() > 0) {
if (stateLogger.isDebugEnabled()) /*if (stateLogger.isDebugEnabled())
stateLogger stateLogger
.debug("After contract execution the sender address refunded with gas leftover, " .debug("After contract execution the sender address refunded with gas leftover, "
+ "\n sender={} \n contract={} \n gas_refund= {}", + "\n sender={} \n contract={} \n gas_refund= {}",
Hex.toHexString(senderAddress), Hex.toHexString(senderAddress),
Hex.toHexString(contractAddress), refund); Hex.toHexString(contractAddress), refund);
*/
// gas refund // gas refund
repository.addBalance(senderAddress, refund); repository.addBalance(senderAddress, refund);
repository.addBalance(coinbase, refund.negate()); repository.addBalance(coinbase, refund.negate());
@ -307,12 +310,13 @@ public class TransactionExecutor {
BigInteger futureRefundBI = BigInteger.valueOf(futureRefund); BigInteger futureRefundBI = BigInteger.valueOf(futureRefund);
BigInteger futureRefundVal = futureRefundBI.multiply(gasPrice); BigInteger futureRefundVal = futureRefundBI.multiply(gasPrice);
if (stateLogger.isDebugEnabled()) /* if (stateLogger.isDebugEnabled())
stateLogger stateLogger
.debug("After contract execution the sender address refunded with storage save refunds, " .debug("After contract execution the sender address refunded with storage save refunds, "
+ "\n sender={} \n contract={} \n gas_refund= {}", + "\n sender={} \n contract={} \n gas_refund= {}",
Hex.toHexString(senderAddress), Hex.toHexString(senderAddress),
Hex.toHexString(contractAddress), futureRefundVal); Hex.toHexString(contractAddress), futureRefundVal);
*/
repository.addBalance(senderAddress, futureRefundVal); repository.addBalance(senderAddress, futureRefundVal);
repository.addBalance(coinbase, futureRefundVal.negate()); repository.addBalance(coinbase, futureRefundVal.negate());
} }

View File

@ -12,8 +12,8 @@ import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.DependsOn; //import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import org.w3c.dom.Attr; import org.w3c.dom.Attr;
import org.w3c.dom.Document; 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. * 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. * New accounts can be generated and added to the wallet and existing accounts can be queried.
*/ */
@Component //@Component
@DependsOn("worldManager") //@DependsOn("worldManager")
public class Wallet { public class Wallet {
private Logger logger = LoggerFactory.getLogger("wallet"); private Logger logger = LoggerFactory.getLogger("wallet");

View File

@ -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<ByteBuffer, byte[]> 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<ByteBuffer, byte[]>();
}
public void destroyDB(File fileLocation) {
logger.debug("Destroying existing database");
db = new HashMap<ByteBuffer, byte[]>();
}
@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<byte[]> keys() {
Set<byte[]> 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<byte[], byte[]> rows) {
for (Map.Entry<byte[], byte[]> 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);
}
}
}

View File

@ -17,8 +17,10 @@ import java.io.IOException;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.iq80.leveldb.impl.Iq80DBFactory;
import static org.iq80.leveldb.impl.Iq80DBFactory.factory; import static org.iq80.leveldb.impl.Iq80DBFactory.factory;
import android.content.Context;
/** /**
* @author Roman Mandeleil * @author Roman Mandeleil
@ -30,6 +32,7 @@ public class LevelDbDataSource implements KeyValueDataSource {
String name; String name;
private DB db; private DB db;
private Context context;
public LevelDbDataSource() { public LevelDbDataSource() {
} }
@ -38,6 +41,10 @@ public class LevelDbDataSource implements KeyValueDataSource {
this.name = name; this.name = name;
} }
public void setContext(Context context) {
this.context = context;
}
@Override @Override
public void init() { public void init() {
@ -46,20 +53,26 @@ public class LevelDbDataSource implements KeyValueDataSource {
Options options = new Options(); Options options = new Options();
options.createIfMissing(true); options.createIfMissing(true);
options.compressionType(CompressionType.NONE); 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 { try {
logger.debug("Opening database"); logger.debug("Opening database");
File dbLocation = new File(System.getProperty("user.dir") + "/" + File dbLocation = context.getDir(SystemProperties.CONFIG.databaseDir(), 0);
SystemProperties.CONFIG.databaseDir() + "/");
File fileLocation = new File(dbLocation, name); File fileLocation = new File(dbLocation, name);
if (SystemProperties.CONFIG.databaseReset()) { if (SystemProperties.CONFIG.databaseReset()) {
destroyDB(fileLocation); destroyDB(fileLocation);
} }
logger.debug("Initializing new or existing database: '{}'", name); logger.debug("Initializing new or existing database: '{}'", fileLocation.getAbsolutePath());
db = factory.open(fileLocation, options); db = factory.open(fileLocation, options);
} catch (IOException ioe) { } catch (Exception ioe) {
logger.debug("x");
logger.error(ioe.getMessage(), ioe); logger.error(ioe.getMessage(), ioe);
throw new RuntimeException("Can't initialize database"); throw new RuntimeException("Can't initialize database");
} }

View File

@ -5,34 +5,31 @@ import org.ethereum.core.Transaction;
import org.ethereum.datasource.KeyValueDataSource; import org.ethereum.datasource.KeyValueDataSource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol; import redis.clients.jedis.Protocol;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.URI; import java.net.URI;
import java.util.Map; import java.util.Map;
import java.util.Set; 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 { public class RedisConnectionImpl implements RedisConnection {
private static final Logger logger = LoggerFactory.getLogger("db"); private static final Logger logger = LoggerFactory.getLogger("db");
private JedisPool jedisPool; private JedisPool jedisPool;
@PostConstruct
public void tryConnect() { public void tryConnect() {
if (!SystemProperties.CONFIG.isRedisEnabled()) return; if (!SystemProperties.CONFIG.isRedisEnabled()) return;
String redisCloudUrl = System.getenv(REDISCLOUD_URL); 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."); logger.info("Cannot connect to Redis. 'REDISCLOUD_URL' environment variable is not defined.");
return; return;
} }
@ -50,20 +47,23 @@ public class RedisConnectionImpl implements RedisConnection {
private static JedisPool createJedisPool(URI redisUri) { private static JedisPool createJedisPool(URI redisUri) {
String userInfo = redisUri.getUserInfo(); String userInfo = redisUri.getUserInfo();
if (StringUtils.hasText(userInfo)) { if (StringUtils.hasText(userInfo)) {
/*
return new JedisPool(new JedisPoolConfig(), return new JedisPool(new JedisPoolConfig(),
redisUri.getHost(), redisUri.getHost(),
redisUri.getPort(), redisUri.getPort(),
Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT,
userInfo.split(":", 2)[1]); userInfo.split(":", 2)[1]);
*/
} }
/*
return new JedisPool(new JedisPoolConfig(), return new JedisPool(new JedisPoolConfig(),
redisUri.getHost(), redisUri.getHost(),
redisUri.getPort(), redisUri.getPort(),
Protocol.DEFAULT_TIMEOUT); Protocol.DEFAULT_TIMEOUT);
*/
return null;
} }
@PreDestroy
public void destroy() { public void destroy() {
if (jedisPool != null) { if (jedisPool != null) {
jedisPool.destroy(); jedisPool.destroy();

View File

@ -3,7 +3,7 @@ package org.ethereum.db;
import org.ethereum.core.Block; import org.ethereum.core.Block;
import org.ethereum.core.TransactionReceipt; import org.ethereum.core.TransactionReceipt;
import org.springframework.transaction.annotation.Transactional; //import org.springframework.transaction.annotation.Transactional;
import java.math.BigInteger; import java.math.BigInteger;
@ -17,36 +17,36 @@ public interface BlockStore {
public byte[] getBlockHashByNumber(long blockNumber); public byte[] getBlockHashByNumber(long blockNumber);
@Transactional(readOnly = true) //@Transactional(readOnly = true)
Block getBlockByNumber(long blockNumber); Block getBlockByNumber(long blockNumber);
@Transactional(readOnly = true) //@Transactional(readOnly = true)
Block getBlockByHash(byte[] hash); Block getBlockByHash(byte[] hash);
@Transactional(readOnly = true) //@Transactional(readOnly = true)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<byte[]> getListOfHashesStartFrom(byte[] hash, int qty); List<byte[]> getListOfHashesStartFrom(byte[] hash, int qty);
@Transactional //@Transactional
void deleteBlocksSince(long number); void deleteBlocksSince(long number);
@Transactional //@Transactional
void saveBlock(Block block, List<TransactionReceipt> receipts); void saveBlock(Block block, List<TransactionReceipt> receipts);
@Transactional(readOnly = true) //@Transactional(readOnly = true)
BigInteger getTotalDifficultySince(long number); BigInteger getTotalDifficultySince(long number);
@Transactional(readOnly = true) //@Transactional(readOnly = true)
BigInteger getTotalDifficulty(); BigInteger getTotalDifficulty();
@Transactional(readOnly = true) //@Transactional(readOnly = true)
Block getBestBlock(); Block getBestBlock();
@Transactional(readOnly = true) //@Transactional(readOnly = true)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<Block> getAllBlocks(); List<Block> getAllBlocks();
@Transactional //@Transactional
void reset(); void reset();
TransactionReceipt getTransactionReceiptByHash(byte[] hash); TransactionReceipt getTransactionReceiptByHash(byte[] hash);

View File

@ -8,9 +8,9 @@ import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Repository; //import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation; //import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; //import org.springframework.transaction.annotation.Transactional;
import java.math.BigInteger; import java.math.BigInteger;
@ -23,10 +23,11 @@ import java.util.List;
*/ */
public class BlockStoreImpl implements BlockStore { public class BlockStoreImpl implements BlockStore {
@Autowired
private SessionFactory sessionFactory; private SessionFactory sessionFactory;
public BlockStoreImpl(SessionFactory sessionFactory) { public BlockStoreImpl() {
this.sessionFactory = sessionFactory;
} }
@Override @Override
@ -38,7 +39,7 @@ public class BlockStoreImpl implements BlockStore {
} }
@Override @Override
@Transactional(readOnly = true) //@Transactional(readOnly = true)
public Block getBlockByNumber(long blockNumber) { public Block getBlockByNumber(long blockNumber) {
List result = sessionFactory.getCurrentSession(). List result = sessionFactory.getCurrentSession().
@ -52,7 +53,7 @@ public class BlockStoreImpl implements BlockStore {
} }
@Override @Override
@Transactional(readOnly = true) //@Transactional(readOnly = true)
public Block getBlockByHash(byte[] hash) { public Block getBlockByHash(byte[] hash) {
List result = sessionFactory.getCurrentSession(). List result = sessionFactory.getCurrentSession().
@ -66,7 +67,7 @@ public class BlockStoreImpl implements BlockStore {
} }
@Override @Override
@Transactional(readOnly = true) //@Transactional(readOnly = true)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public List<byte[]> getListOfHashesStartFrom(byte[] hash, int qty) { public List<byte[]> getListOfHashesStartFrom(byte[] hash, int qty) {
@ -89,7 +90,7 @@ public class BlockStoreImpl implements BlockStore {
} }
@Override @Override
@Transactional //@Transactional
public void deleteBlocksSince(long number) { public void deleteBlocksSince(long number) {
sessionFactory.getCurrentSession(). sessionFactory.getCurrentSession().
@ -100,7 +101,7 @@ public class BlockStoreImpl implements BlockStore {
@Override @Override
@Transactional //@Transactional
public void saveBlock(Block block, List<TransactionReceipt> receipts) { public void saveBlock(Block block, List<TransactionReceipt> receipts) {
BlockVO blockVO = new BlockVO(block.getNumber(), block.getHash(), BlockVO blockVO = new BlockVO(block.getNumber(), block.getHash(),
@ -119,7 +120,7 @@ public class BlockStoreImpl implements BlockStore {
} }
@Override @Override
@Transactional(readOnly = true) //@Transactional(readOnly = true)
public BigInteger getTotalDifficultySince(long number) { public BigInteger getTotalDifficultySince(long number) {
return (BigInteger) sessionFactory.getCurrentSession(). return (BigInteger) sessionFactory.getCurrentSession().
@ -130,7 +131,7 @@ public class BlockStoreImpl implements BlockStore {
@Override @Override
@Transactional(readOnly = true) //@Transactional(readOnly = true)
public BigInteger getTotalDifficulty() { public BigInteger getTotalDifficulty() {
return (BigInteger) sessionFactory.getCurrentSession(). return (BigInteger) sessionFactory.getCurrentSession().
@ -139,7 +140,7 @@ public class BlockStoreImpl implements BlockStore {
@Override @Override
@Transactional(readOnly = true) //@Transactional(readOnly = true)
public Block getBestBlock() { public Block getBestBlock() {
Long bestNumber = (Long) Long bestNumber = (Long)
@ -154,7 +155,7 @@ public class BlockStoreImpl implements BlockStore {
} }
@Override @Override
@Transactional(readOnly = true) //@Transactional(readOnly = true)
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public List<Block> getAllBlocks() { public List<Block> getAllBlocks() {
@ -170,7 +171,7 @@ public class BlockStoreImpl implements BlockStore {
} }
@Override @Override
@Transactional //@Transactional
public void reset() { public void reset() {
sessionFactory.getCurrentSession(). sessionFactory.getCurrentSession().
createQuery("delete from BlockVO").executeUpdate(); createQuery("delete from BlockVO").executeUpdate();

View File

@ -74,13 +74,14 @@ public class RepositoryDummy extends RepositoryImpl {
accountState.setStateRoot(contractDetails.getStorageHash()); accountState.setStateRoot(contractDetails.getStorageHash());
accountState.setCodeHash(sha3(contractDetails.getCode())); accountState.setCodeHash(sha3(contractDetails.getCode()));
worldState.put(hash, accountState); worldState.put(hash, accountState);
if (logger.isDebugEnabled()) { /* if (logger.isDebugEnabled()) {
logger.debug("update: [{}],nonce: [{}] balance: [{}] \n [{}]", logger.debug("update: [{}],nonce: [{}] balance: [{}] \n [{}]",
Hex.toHexString(hash.getData()), Hex.toHexString(hash.getData()),
accountState.getNonce(), accountState.getNonce(),
accountState.getBalance(), accountState.getBalance(),
contractDetails.getStorage()); contractDetails.getStorage());
} }
*/
} }

View File

@ -18,8 +18,8 @@ import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex; import org.spongycastle.util.encoders.Hex;
import org.springframework.stereotype.Component; import org.apache.commons.io.FileUtils;
import org.springframework.util.FileSystemUtils; //import org.springframework.util.FileSystemUtils;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
@ -65,17 +65,25 @@ public class RepositoryImpl implements Repository {
public RepositoryImpl(KeyValueDataSource detailsDS, KeyValueDataSource stateDS) { public RepositoryImpl(KeyValueDataSource detailsDS, KeyValueDataSource stateDS) {
logger.debug("test1");
detailsDS.setName(DETAILS_DB); detailsDS.setName(DETAILS_DB);
logger.debug("test2");
detailsDS.init(); detailsDS.init();
logger.debug("test3");
this.detailsDS = detailsDS; this.detailsDS = detailsDS;
stateDS.setName(STATE_DB); stateDS.setName(STATE_DB);
logger.debug("test4");
stateDS.init(); stateDS.init();
logger.debug("test5");
this.stateDS = stateDS; this.stateDS = stateDS;
detailsDB = new DatabaseImpl(detailsDS); detailsDB = new DatabaseImpl(detailsDS);
logger.debug("test6");
stateDB = new DatabaseImpl(stateDS); stateDB = new DatabaseImpl(stateDS);
logger.debug("test7");
worldState = new TrieImpl(stateDB.getDb()); worldState = new TrieImpl(stateDB.getDb());
logger.debug("test8");
} }
public RepositoryImpl(String detailsDbName, String stateDbName) { public RepositoryImpl(String detailsDbName, String stateDbName) {
@ -137,14 +145,14 @@ public class RepositoryImpl implements Repository {
accountState.setStateRoot(contractDetails.getStorageHash()); accountState.setStateRoot(contractDetails.getStorageHash());
accountState.setCodeHash(sha3(contractDetails.getCode())); accountState.setCodeHash(sha3(contractDetails.getCode()));
worldState.update(hash.getData(), accountState.getEncoded()); worldState.update(hash.getData(), accountState.getEncoded());
if (logger.isDebugEnabled()) { /*if (logger.isDebugEnabled()) {
logger.debug("update: [{}],nonce: [{}] balance: [{}] \n [{}]", logger.debug("update: [{}],nonce: [{}] balance: [{}] \n [{}]",
Hex.toHexString(hash.getData()), Hex.toHexString(hash.getData()),
accountState.getNonce(), accountState.getNonce(),
accountState.getBalance(), accountState.getBalance(),
contractDetails.getStorage()); contractDetails.getStorage());
} }
*/
} }
} }
@ -193,7 +201,13 @@ public class RepositoryImpl implements Repository {
if (block.getNumber() == 0 && txNumber == 0) if (block.getNumber() == 0 && txNumber == 0)
if (CONFIG.dumpCleanOnRestart()) { 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() + "/"; String dir = CONFIG.dumpDir() + "/";

View File

@ -125,8 +125,8 @@ public class RepositoryTrack implements Repository {
BigInteger saveNonce = accountState.getNonce(); BigInteger saveNonce = accountState.getNonce();
accountState.incrementNonce(); accountState.incrementNonce();
logger.trace("increase nonce addr: [{}], from: [{}], to: [{}]", Hex.toHexString(addr), //logger.trace("increase nonce addr: [{}], from: [{}], to: [{}]", Hex.toHexString(addr),
saveNonce, accountState.getNonce()); // saveNonce, accountState.getNonce());
return accountState.getNonce(); return accountState.getNonce();
} }
@ -140,8 +140,8 @@ public class RepositoryTrack implements Repository {
BigInteger saveNonce = accountState.getNonce(); BigInteger saveNonce = accountState.getNonce();
accountState.setNonce(bigInteger); accountState.setNonce(bigInteger);
logger.trace("increase nonce addr: [{}], from: [{}], to: [{}]", Hex.toHexString(addr), //logger.trace("increase nonce addr: [{}], from: [{}], to: [{}]", Hex.toHexString(addr),
saveNonce, accountState.getNonce()); // saveNonce, accountState.getNonce());
return accountState.getNonce(); return accountState.getNonce();
@ -170,8 +170,8 @@ public class RepositoryTrack implements Repository {
BigInteger newBalance = accountState.addToBalance(value); BigInteger newBalance = accountState.addToBalance(value);
logger.trace("adding to balance addr: [{}], balance: [{}], delta: [{}]", Hex.toHexString(addr), //logger.trace("adding to balance addr: [{}], balance: [{}], delta: [{}]", Hex.toHexString(addr),
newBalance, value); // newBalance, value);
return newBalance; return newBalance;
} }
@ -192,8 +192,8 @@ public class RepositoryTrack implements Repository {
@Override @Override
public void addStorageRow(byte[] addr, DataWord key, DataWord value) { public void addStorageRow(byte[] addr, DataWord key, DataWord value) {
logger.trace("add storage row, addr: [{}], key: [{}] val: [{}]", Hex.toHexString(addr), //logger.trace("add storage row, addr: [{}], key: [{}] val: [{}]", Hex.toHexString(addr),
key.toString(), value.toString()); // key.toString(), value.toString());
getContractDetails(addr).put(key, value); getContractDetails(addr).put(key, value);
} }

View File

@ -71,13 +71,13 @@ public class RepositoryVMTestDummy extends RepositoryImpl{
accountState.setStateRoot(contractDetails.getStorageHash()); accountState.setStateRoot(contractDetails.getStorageHash());
accountState.setCodeHash(sha3(contractDetails.getCode())); accountState.setCodeHash(sha3(contractDetails.getCode()));
worldState.put(hash, accountState); worldState.put(hash, accountState);
if (logger.isDebugEnabled()) { /*if (logger.isDebugEnabled()) {
logger.debug("update: [{}],nonce: [{}] balance: [{}] \n [{}]", logger.debug("update: [{}],nonce: [{}] balance: [{}] \n [{}]",
Hex.toHexString(hash.getData()), Hex.toHexString(hash.getData()),
accountState.getNonce(), accountState.getNonce(),
accountState.getBalance(), accountState.getBalance(),
contractDetails.getStorage()); contractDetails.getStorage());
} }*/
} }

View File

@ -1,42 +1,30 @@
package org.ethereum.facade; package org.ethereum.facade;
import org.ethereum.config.SystemProperties; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan; //import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; //import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; //import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource; //import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; //import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement; //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.Properties;
import java.util.Set;
import static org.ethereum.config.SystemProperties.CONFIG; //@Configuration
//@EnableTransactionManagement
@Configuration //@ComponentScan(basePackages = "org.ethereum")
@EnableTransactionManagement
@ComponentScan(basePackages = "org.ethereum")
public class CommonConfig { public class CommonConfig {
private static final Logger logger = LoggerFactory.getLogger("general"); private static final Logger logger = LoggerFactory.getLogger("general");
@Autowired //@Autowired
private RedisConnection redisConnection; //private RedisConnection redisConnection;
/*
@Bean @Bean
Repository repository() { Repository repository() {
return new RepositoryImpl(keyValueDataSource(), keyValueDataSource()); return new RepositoryImpl(keyValueDataSource(), keyValueDataSource());
@ -83,7 +71,7 @@ public class CommonConfig {
return builder.buildSessionFactory(); return builder.buildSessionFactory();
} }
*/
private Properties getHibernateProperties() { private Properties getHibernateProperties() {
Properties prop = new Properties(); Properties prop = new Properties();
@ -100,7 +88,7 @@ public class CommonConfig {
return prop; return prop;
} }
/*
@Bean @Bean
public DataSourceTransactionManager transactionManager() { public DataSourceTransactionManager transactionManager() {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
@ -108,7 +96,8 @@ public class CommonConfig {
return dataSourceTransactionManager; return dataSourceTransactionManager;
} }
*/
/*
@Bean(name = "dataSource") @Bean(name = "dataSource")
public DriverManagerDataSource dataSource() { public DriverManagerDataSource dataSource() {
@ -131,5 +120,6 @@ public class CommonConfig {
return ds; return ds;
} }
*/
} }

View File

@ -1,29 +1,29 @@
package org.ethereum.facade; package org.ethereum.facade;
import org.ethereum.db.BlockStore; import org.ethereum.db.BlockStore;
import org.ethereum.db.BlockStoreImpl; import org.ethereum.db.InMemoryBlockStore;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; //import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; //import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.Propagation; //import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; //import org.springframework.transaction.annotation.Transactional;
/** /**
* *
* @author: Roman Mandeleil * @author: Roman Mandeleil
* Created on: 27/01/2015 01:05 * Created on: 27/01/2015 01:05
*/ */
@Configuration //@Configuration
@Import(CommonConfig.class) //@Import(CommonConfig.class)
public class DefaultConfig { public class DefaultConfig {
@Autowired CommonConfig commonConfig; @Autowired CommonConfig commonConfig;
@Bean //@Bean
@Transactional(propagation = Propagation.SUPPORTS) //@Transactional(propagation = Propagation.SUPPORTS)
public BlockStore blockStore(SessionFactory sessionFactory){ public BlockStore blockStore(SessionFactory sessionFactory){
return new BlockStoreImpl(sessionFactory); return new InMemoryBlockStore();
} }
} }

View File

@ -7,6 +7,7 @@ import org.ethereum.manager.AdminInfo;
import org.ethereum.net.client.PeerClient; import org.ethereum.net.client.PeerClient;
import org.ethereum.net.peerdiscovery.PeerInfo; import org.ethereum.net.peerdiscovery.PeerInfo;
import org.ethereum.net.server.ChannelManager; import org.ethereum.net.server.ChannelManager;
import org.springframework.context.ApplicationContext;
import java.math.BigInteger; import java.math.BigInteger;
@ -63,6 +64,8 @@ public interface Ethereum {
*/ */
public Set<PeerInfo> getPeers(); public Set<PeerInfo> getPeers();
public void setContext(ApplicationContext context);
public void startPeerDiscovery(); public void startPeerDiscovery();
public void stopPeerDiscovery(); public void stopPeerDiscovery();

View File

@ -8,6 +8,7 @@ import org.ethereum.manager.WorldManager;
import org.ethereum.net.client.PeerClient; import org.ethereum.net.client.PeerClient;
import org.ethereum.net.peerdiscovery.PeerInfo; import org.ethereum.net.peerdiscovery.PeerInfo;
import org.ethereum.net.server.ChannelManager; import org.ethereum.net.server.ChannelManager;
import org.ethereum.net.server.EthereumChannelInitializer;
import org.ethereum.net.server.PeerServer; import org.ethereum.net.server.PeerServer;
import org.ethereum.net.submit.TransactionExecutor; import org.ethereum.net.submit.TransactionExecutor;
import org.ethereum.net.submit.TransactionTask; import org.ethereum.net.submit.TransactionTask;
@ -16,9 +17,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; 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.math.BigInteger;
import java.net.InetAddress; import java.net.InetAddress;
import java.util.HashSet; import java.util.HashSet;
@ -26,13 +26,15 @@ import java.util.Set;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import org.robospring.RoboSpring;
import static org.ethereum.config.SystemProperties.CONFIG; import static org.ethereum.config.SystemProperties.CONFIG;
/** /**
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 27.07.2014 * @since 27.07.2014
*/ */
@Component //@Component
public class EthereumImpl implements Ethereum { public class EthereumImpl implements Ethereum {
private static final Logger logger = LoggerFactory.getLogger("facade"); private static final Logger logger = LoggerFactory.getLogger("facade");
@ -54,9 +56,10 @@ public class EthereumImpl implements Ethereum {
public EthereumImpl() { public EthereumImpl() {
System.out.println(); System.out.println();
logger.info("EthereumImpl constructor");
//RoboSpring.autowire(ctx);
} }
@PostConstruct
public void init() { public void init() {
worldManager.loadBlockchain(); worldManager.loadBlockchain();
if (CONFIG.listenPort() > 0) { 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 * Find a peer but not this one
* *
@ -180,7 +187,6 @@ public class EthereumImpl implements Ethereum {
PeerClient peer = worldManager.getActivePeer(); PeerClient peer = worldManager.getActivePeer();
if (peer == null) { if (peer == null) {
peer = new PeerClient(); peer = new PeerClient();
worldManager.setActivePeer(peer); worldManager.setActivePeer(peer);
} }

View File

@ -4,19 +4,19 @@ import org.ethereum.db.BlockStore;
import org.ethereum.db.InMemoryBlockStore; import org.ethereum.db.InMemoryBlockStore;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; //import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; //import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.Propagation; //import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; //import org.springframework.transaction.annotation.Transactional;
/** /**
* *
* @author: Roman Mandeleil * @author: Roman Mandeleil
* Created on: 27/01/2015 01:05 * Created on: 27/01/2015 01:05
*/ */
@Configuration //@Configuration
@Import(CommonConfig.class) //@Import(CommonConfig.class)
public class RemoteConfig { public class RemoteConfig {
@Autowired CommonConfig commonConfig; @Autowired CommonConfig commonConfig;
@ -24,8 +24,8 @@ public class RemoteConfig {
// todo: init total difficulty // todo: init total difficulty
// todo: init last 1000 blocks // todo: init last 1000 blocks
@Bean //@Bean
@Transactional(propagation = Propagation.SUPPORTS) //@Transactional(propagation = Propagation.SUPPORTS)
public BlockStore blockStore(SessionFactory sessionFactory){ public BlockStore blockStore(SessionFactory sessionFactory){
return new InMemoryBlockStore(); return new InMemoryBlockStore();
} }

View File

@ -6,7 +6,7 @@ import org.ethereum.core.TransactionReceipt;
import org.ethereum.net.message.Message; import org.ethereum.net.message.Message;
import org.ethereum.net.p2p.HelloMessage; import org.ethereum.net.p2p.HelloMessage;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -16,7 +16,7 @@ import java.util.Set;
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 12.11.2014 * @since 12.11.2014
*/ */
@Component(value = "EthereumListener") //@Component(value = "EthereumListener")
public class CompositeEthereumListener implements EthereumListener { public class CompositeEthereumListener implements EthereumListener {
List<EthereumListener> listeners = new ArrayList<>(); List<EthereumListener> listeners = new ArrayList<>();

View File

@ -1,8 +1,7 @@
package org.ethereum.manager; 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.ArrayList;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@ -11,7 +10,7 @@ import java.util.List;
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 11.12.2014 * @since 11.12.2014
*/ */
@Component //@Component
public class AdminInfo { public class AdminInfo {
@ -20,7 +19,6 @@ public class AdminInfo {
private List<Long> blockExecTime = new LinkedList<>(); private List<Long> blockExecTime = new LinkedList<>();
@PostConstruct
public void init() { public void init() {
startupTimeStamp = System.currentTimeMillis(); startupTimeStamp = System.currentTimeMillis();
} }

View File

@ -17,7 +17,7 @@ import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex; import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.math.BigInteger; import java.math.BigInteger;
@ -27,9 +27,6 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import static org.ethereum.config.SystemProperties.CONFIG; import static org.ethereum.config.SystemProperties.CONFIG;
/** /**
@ -38,7 +35,7 @@ import static org.ethereum.config.SystemProperties.CONFIG;
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 01.06.2014 * @since 01.06.2014
*/ */
@Component //@Component
public class WorldManager { public class WorldManager {
private static final Logger logger = LoggerFactory.getLogger("general"); private static final Logger logger = LoggerFactory.getLogger("general");
@ -52,7 +49,6 @@ public class WorldManager {
@Autowired @Autowired
private Wallet wallet; private Wallet wallet;
@Autowired
private PeerClient activePeer; private PeerClient activePeer;
@Autowired @Autowired
@ -71,7 +67,10 @@ public class WorldManager {
@Autowired @Autowired
private EthereumListener listener; private EthereumListener listener;
@PostConstruct public WorldManager() {
logger.info("World manager instantiated");
}
public void init() { public void init() {
byte[] cowAddr = HashUtil.sha3("cow".getBytes()); byte[] cowAddr = HashUtil.sha3("cow".getBytes());
wallet.importKey(cowAddr); wallet.importKey(cowAddr);
@ -164,10 +163,10 @@ public class WorldManager {
BigInteger totalDifficulty = blockStore.getTotalDifficulty(); BigInteger totalDifficulty = blockStore.getTotalDifficulty();
blockchain.setTotalDifficulty(totalDifficulty); blockchain.setTotalDifficulty(totalDifficulty);
logger.info("*** Loaded up to block [{}] totalDifficulty [{}] with stateRoot [{}]", //logger.info("*** Loaded up to block [{}] totalDifficulty [{}] with stateRoot [{}]",
blockchain.getBestBlock().getNumber(), // blockchain.getBestBlock().getNumber(),
blockchain.getTotalDifficulty().toString(), // blockchain.getTotalDifficulty().toString(),
Hex.toHexString(blockchain.getBestBlock().getStateRoot())); // Hex.toHexString(blockchain.getBestBlock().getStateRoot()));
} }
if (CONFIG.rootHashStart() != null) { if (CONFIG.rootHashStart() != null) {
@ -200,7 +199,6 @@ public class WorldManager {
} }
@PreDestroy
public void close() { public void close() {
stopPeerDiscovery(); stopPeerDiscovery();
repository.close(); repository.close();

View File

@ -9,7 +9,7 @@ import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex; import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.math.BigInteger; import java.math.BigInteger;
@ -34,7 +34,7 @@ import static org.ethereum.config.SystemProperties.CONFIG;
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 27.07.2014 * @since 27.07.2014
*/ */
@Component //@Component
public class BlockQueue { public class BlockQueue {
private static final Logger logger = LoggerFactory.getLogger("blockqueue"); private static final Logger logger = LoggerFactory.getLogger("blockqueue");

View File

@ -11,8 +11,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.util.Queue; import java.util.Queue;
import java.util.Timer; import java.util.Timer;
@ -36,8 +36,8 @@ import static org.ethereum.net.message.StaticMessages.DISCONNECT_MESSAGE;
* *
* @author Roman Mandeleil * @author Roman Mandeleil
*/ */
@Component //@Component
@Scope("prototype") //@Scope("prototype")
public class MessageQueue { public class MessageQueue {
private static final Logger logger = LoggerFactory.getLogger("net"); private static final Logger logger = LoggerFactory.getLogger("net");

View File

@ -16,8 +16,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import static org.ethereum.config.SystemProperties.CONFIG; import static org.ethereum.config.SystemProperties.CONFIG;
@ -26,8 +26,8 @@ import static org.ethereum.config.SystemProperties.CONFIG;
* *
* @see <a href="http://netty.io">http://netty.io</a> * @see <a href="http://netty.io">http://netty.io</a>
*/ */
@Component //@Component
@Scope("prototype") //@Scope("prototype")
public class PeerClient { public class PeerClient {
private static final Logger logger = LoggerFactory.getLogger("net"); private static final Logger logger = LoggerFactory.getLogger("net");
@ -43,6 +43,11 @@ public class PeerClient {
@Autowired @Autowired
public EthereumChannelInitializer ethereumChannelInitializer; public EthereumChannelInitializer ethereumChannelInitializer;
public PeerClient() {
logger.info("Peer client instantiated");
}
public void connect(String host, int port) { public void connect(String host, int port) {
EventLoopGroup workerGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup();

View File

@ -19,8 +19,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.math.BigInteger; import java.math.BigInteger;
@ -50,8 +50,8 @@ import static org.ethereum.net.message.StaticMessages.GET_TRANSACTIONS_MESSAGE;
* <li>BLOCKS : Send a list of blocks</li> * <li>BLOCKS : Send a list of blocks</li>
* </ul> * </ul>
*/ */
@Component //@Component
@Scope("prototype") //@Scope("prototype")
public class EthHandler extends SimpleChannelInboundHandler<EthMessage> { public class EthHandler extends SimpleChannelInboundHandler<EthMessage> {
public final static byte VERSION = 54; public final static byte VERSION = 54;

View File

@ -22,8 +22,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
@ -51,8 +51,8 @@ import static org.ethereum.net.message.StaticMessages.*;
* <li>PONG : Confirm that they themselves are still alive</li> * <li>PONG : Confirm that they themselves are still alive</li>
* </ul> * </ul>
*/ */
@Component //@Component
@Scope("prototype") //@Scope("prototype")
public class P2pHandler extends SimpleChannelInboundHandler<P2pMessage> { public class P2pHandler extends SimpleChannelInboundHandler<P2pMessage> {
public final static byte VERSION = 3; public final static byte VERSION = 3;

View File

@ -27,8 +27,8 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -39,8 +39,8 @@ import static org.ethereum.config.SystemProperties.CONFIG;
* *
* @see <a href="http://netty.io">http://netty.io</a> * @see <a href="http://netty.io">http://netty.io</a>
*/ */
@Component //@Component
@Scope("prototype") //@Scope("prototype")
public class DiscoveryChannel { public class DiscoveryChannel {
private static final Logger logger = LoggerFactory.getLogger("net"); private static final Logger logger = LoggerFactory.getLogger("net");

View File

@ -7,7 +7,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
@ -33,7 +33,7 @@ import static org.ethereum.config.SystemProperties.CONFIG;
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 22.05.2014 * @since 22.05.2014
*/ */
@Component //@Component
public class PeerDiscovery { public class PeerDiscovery {
private static final Logger logger = LoggerFactory.getLogger("peerdiscovery"); private static final Logger logger = LoggerFactory.getLogger("peerdiscovery");

View File

@ -5,8 +5,8 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
@ -14,8 +14,8 @@ import java.util.concurrent.ThreadPoolExecutor;
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 22.05.2014 * @since 22.05.2014
*/ */
@Component //@Component
@Scope("prototype") //@Scope("prototype")
public class WorkerThread implements Runnable { public class WorkerThread implements Runnable {
private final static Logger logger = LoggerFactory.getLogger("peerdiscovery"); private final static Logger logger = LoggerFactory.getLogger("peerdiscovery");

View File

@ -11,8 +11,8 @@ import org.ethereum.net.wire.MessageDecoder;
import org.ethereum.net.wire.MessageEncoder; import org.ethereum.net.wire.MessageEncoder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.math.BigInteger; import java.math.BigInteger;
@ -22,8 +22,8 @@ import java.net.InetSocketAddress;
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 01.11.2014 * @since 01.11.2014
*/ */
@Component //@Component
@Scope("prototype") //@Scope("prototype")
public class Channel { public class Channel {
@Autowired @Autowired

View File

@ -9,7 +9,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -20,13 +20,12 @@ import java.util.Map;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import javax.annotation.PostConstruct;
/** /**
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 11.11.2014 * @since 11.11.2014
*/ */
@Component //@Component
public class ChannelManager { public class ChannelManager {
private static final Logger logger = LoggerFactory.getLogger("net"); private static final Logger logger = LoggerFactory.getLogger("net");
@ -43,7 +42,6 @@ public class ChannelManager {
} }
@PostConstruct
public void init() { public void init() {
scheduleChannelCollector(); scheduleChannelCollector();
} }

View File

@ -15,7 +15,7 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -25,7 +25,7 @@ import static org.ethereum.config.SystemProperties.CONFIG;
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 01.11.2014 * @since 01.11.2014
*/ */
@Component //@Component
public class EthereumChannelInitializer extends ChannelInitializer<NioSocketChannel> { public class EthereumChannelInitializer extends ChannelInitializer<NioSocketChannel> {
private static final Logger logger = LoggerFactory.getLogger("net"); private static final Logger logger = LoggerFactory.getLogger("net");
@ -43,6 +43,7 @@ public class EthereumChannelInitializer extends ChannelInitializer<NioSocketChan
WorldManager worldManager; WorldManager worldManager;
public EthereumChannelInitializer() { public EthereumChannelInitializer() {
logger.info("Channel initializer instantiated");
} }
public void initChannel(NioSocketChannel ch) throws Exception { public void initChannel(NioSocketChannel ch) throws Exception {

View File

@ -15,7 +15,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import static org.ethereum.config.SystemProperties.CONFIG; import static org.ethereum.config.SystemProperties.CONFIG;
@ -26,7 +26,7 @@ import static org.ethereum.config.SystemProperties.CONFIG;
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 01.11.2014 * @since 01.11.2014
*/ */
@Component //@Component
public class PeerServer { public class PeerServer {
private static final Logger logger = LoggerFactory.getLogger("net"); private static final Logger logger = LoggerFactory.getLogger("net");

View File

@ -10,16 +10,16 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
/** /**
* Process the messages between peers with 'shh' capability on the network. * Process the messages between peers with 'shh' capability on the network.
* *
* Peers with 'shh' capability can send/receive: * Peers with 'shh' capability can send/receive:
*/ */
@Component //@Component
@Scope("prototype") //@Scope("prototype")
public class ShhHandler extends SimpleChannelInboundHandler<ShhMessage> { public class ShhHandler extends SimpleChannelInboundHandler<ShhMessage> {
public final static byte VERSION = 1; public final static byte VERSION = 1;

View File

@ -15,16 +15,16 @@ import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex; import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.util.List; import java.util.List;
/** /**
* The PacketDecoder parses every valid Ethereum packet to a Message object * The PacketDecoder parses every valid Ethereum packet to a Message object
*/ */
@Component //@Component
@Scope("prototype") //@Scope("prototype")
public class MessageDecoder extends ByteToMessageDecoder { public class MessageDecoder extends ByteToMessageDecoder {
private static final Logger loggerWire = LoggerFactory.getLogger("wire"); private static final Logger loggerWire = LoggerFactory.getLogger("wire");
@ -80,8 +80,8 @@ public class MessageDecoder extends ByteToMessageDecoder {
// Don't have the full message yet // Don't have the full message yet
long msgSize = in.getInt(in.readerIndex()); long msgSize = in.getInt(in.readerIndex());
if (msgSize > in.readableBytes()) { if (msgSize > in.readableBytes()) {
loggerWire.trace("msg decode: magicBytes: [{}], readBytes: [{}] / msgSize: [{}] ", //loggerWire.trace("msg decode: magicBytes: [{}], readBytes: [{}] / msgSize: [{}] ",
syncToken, in.readableBytes(), msgSize); // syncToken, in.readableBytes(), msgSize);
in.resetReaderIndex(); in.resetReaderIndex();
return false; return false;
} }

View File

@ -15,14 +15,14 @@ import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex; import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; //import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
/** /**
* The PacketEncoder encodes the message and adds a sync token to every packet. * The PacketEncoder encodes the message and adds a sync token to every packet.
*/ */
@Component //@Component
@Scope("prototype") //@Scope("prototype")
public class MessageEncoder extends MessageToByteEncoder<Message> { public class MessageEncoder extends MessageToByteEncoder<Message> {
private static final Logger loggerWire = LoggerFactory.getLogger("wire"); private static final Logger loggerWire = LoggerFactory.getLogger("wire");

View File

@ -1,6 +1,6 @@
package org.ethereum.util; package org.ethereum.util;
import org.apache.log4j.PropertyConfigurator; //import org.apache.log4j.PropertyConfigurator;
import java.net.URL; 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 // here we can turn on the detail tracing in the middle of the chain
if (blockNum >= CONFIG.traceStartBlock() && CONFIG.traceStartBlock() != -1) { if (blockNum >= CONFIG.traceStartBlock() && CONFIG.traceStartBlock() != -1) {
URL configFile = ClassLoader.getSystemResource("log4j-detailed.properties"); URL configFile = ClassLoader.getSystemResource("log4j-detailed.properties");
PropertyConfigurator.configure(configFile); //PropertyConfigurator.configure(configFile);
} }
} }
} }

View File

@ -16,8 +16,6 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.swing.*;
public class Utils { public class Utils {
private static SecureRandom random = new SecureRandom(); private static SecureRandom random = new SecureRandom();
@ -48,12 +46,6 @@ public class Utils {
return formatter.format(date); 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) { public static String getValueShortString(BigInteger number) {

View File

@ -20,9 +20,10 @@ import java.math.BigInteger;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.*; import java.util.*;
import static java.lang.String.format;
import static org.ethereum.config.SystemProperties.CONFIG; import static org.ethereum.config.SystemProperties.CONFIG;
import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; 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 * @author Roman Mandeleil
@ -190,8 +191,7 @@ public class Program {
*/ */
public void stackRequire(int stackSize) { public void stackRequire(int stackSize) {
if (stack.size() < stackSize) { if (stack.size() < stackSize) {
throw new StackTooSmallException("Expected: " + stackSize throw Program.Exception.tooSmallStack(stackSize, stack.size());
+ ", found: " + stack.size());
} }
} }
@ -445,17 +445,18 @@ public class Program {
// FETCH THE CODE // FETCH THE CODE
byte[] programCode = this.result.getRepository().getCode(codeAddress); byte[] programCode = this.result.getRepository().getCode(codeAddress);
if (logger.isInfoEnabled()) /* if (logger.isInfoEnabled())
logger.info(msg.getType().name() + " for existing contract: address: [{}], outDataOffs: [{}], outDataSize: [{}] ", logger.info(msg.getType().name() + " for existing contract: address: [{}], outDataOffs: [{}], outDataSize: [{}] ",
Hex.toHexString(contextAddress), msg.getOutDataOffs().longValue(), msg.getOutDataSize().longValue()); Hex.toHexString(contextAddress), msg.getOutDataOffs().longValue(), msg.getOutDataSize().longValue());
*/
// 2.1 PERFORM THE GAS VALUE TX // 2.1 PERFORM THE GAS VALUE TX
// (THIS STAGE IS NOT REVERTED BY ANY EXCEPTION) // (THIS STAGE IS NOT REVERTED BY ANY EXCEPTION)
if (this.getGas().longValue() - msg.getGas().longValue() < 0) { if (this.getGas().longValue() - msg.getGas().longValue() < 0) {
gasLogger.info("No gas for the internal call, \n" + OutOfGasException ex = new OutOfGasException("Not enough gas for the internal call: fromAddress[%s], codeAddress[%s];",
"fromAddress={}, codeAddress={}",
Hex.toHexString(senderAddress), Hex.toHexString(codeAddress)); Hex.toHexString(senderAddress), Hex.toHexString(codeAddress));
throw new OutOfGasException(); gasLogger.info(ex.getMessage());
throw ex;
} }
BigInteger endowment = msg.getEndowment().value(); BigInteger endowment = msg.getEndowment().value();
@ -545,11 +546,12 @@ public class Program {
} }
public void spendGas(long gasValue, String cause) { 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(); long afterSpend = invokeData.getGas().longValue() - gasValue - result.getGasUsed();
if (afterSpend < 0) if (afterSpend < 0) {
throw new OutOfGasException(); throw Program.Exception.notEnoughSpendingGas(cause, gasValue, this);
}
result.spendGas(gasValue); result.spendGas(gasValue);
} }
@ -558,7 +560,7 @@ public class Program {
} }
public void refundGas(long gasValue, String cause) { 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); result.refundGas(gasValue);
} }
@ -700,7 +702,7 @@ public class Program {
secondLine.append(ByteUtil.oneByteToHexString(value)).append(" "); secondLine.append(ByteUtil.oneByteToHexString(value)).append(" ");
if ((i + 1) % 8 == 0) { 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("").append(tmp).append(" ");
memoryData.append(firstLine).append(" "); memoryData.append(firstLine).append(" ");
memoryData.append(secondLine); memoryData.append(secondLine);
@ -744,7 +746,7 @@ public class Program {
oneLine.append(ByteUtil.oneByteToHexString(value)).append(" "); oneLine.append(ByteUtil.oneByteToHexString(value)).append(" ");
if ((i + 1) % 16 == 0) { 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"); Integer.toString(i, 16)).replace(" ", "0");
memoryData.append("").append(tmp).append(" "); memoryData.append("").append(tmp).append(" ");
memoryData.append(oneLine); memoryData.append(oneLine);
@ -773,11 +775,11 @@ public class Program {
logger.trace(" -- STACK -- {}", stackData); logger.trace(" -- STACK -- {}", stackData);
logger.trace(" -- MEMORY -- {}", memoryData); logger.trace(" -- MEMORY -- {}", memoryData);
logger.trace(" -- STORAGE -- {}\n", storageData); 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(), result.getGasUsed(),
invokeData.getGas().longValue(), invokeData.getGas().longValue(),
getGas().longValue()); getGas().longValue());
*/
StringBuilder globalOutput = new StringBuilder("\n"); StringBuilder globalOutput = new StringBuilder("\n");
if (stackData.length() > 0) stackData.append("\n"); if (stackData.length() > 0) stackData.append("\n");
@ -826,7 +828,7 @@ public class Program {
public void saveProgramTraceToFile(String fileName) { 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() + "/"; String dir = CONFIG.databaseDir() + "/" + CONFIG.vmTraceDir() + "/";
@ -840,7 +842,7 @@ public class Program {
fw = new FileWriter(dumpFile.getAbsoluteFile()); fw = new FileWriter(dumpFile.getAbsoluteFile());
bw = new BufferedWriter(fw); bw = new BufferedWriter(fw);
bw.write(programTrace.asJsonString()); bw.write(programTrace.asJsonString(true));
} catch (IOException e) { } catch (IOException e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} finally { } finally {
@ -876,12 +878,13 @@ public class Program {
if (code == null || code.length == 0) if (code == null || code.length == 0)
return result; 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; final byte[] continuedCode;
if (op == null) throw new IllegalOperationException("Invalid operation: " +
Hex.toHexString(code, index, 1));
switch(op) { switch(op) {
case PUSH1: case PUSH2: case PUSH3: case PUSH4: case PUSH5: case PUSH6: case PUSH7: case PUSH8: 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: 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) { 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) { public void callToPrecompiledAddress(MessageCall msg, PrecompiledContract contract) {
@ -951,27 +956,68 @@ public class Program {
} }
@SuppressWarnings("serial") @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") @SuppressWarnings("serial")
public static class IllegalOperationException extends RuntimeException { 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") @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") @SuppressWarnings("serial")
public class StackTooSmallException extends RuntimeException { public static class StackTooSmallException extends RuntimeException {
public StackTooSmallException(String message) {
super(message); 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);
} }
} }

View File

@ -13,7 +13,7 @@ import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex; import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; //import org.springframework.stereotype.Component;
import java.math.BigInteger; import java.math.BigInteger;
@ -21,7 +21,7 @@ import java.math.BigInteger;
* @author Roman Mandeleil * @author Roman Mandeleil
* @since 08.06.2014 * @since 08.06.2014
*/ */
@Component("ProgramInvokeFactory") //@Component("ProgramInvokeFactory")
public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory {
private static final Logger logger = LoggerFactory.getLogger("VM"); private static final Logger logger = LoggerFactory.getLogger("VM");
@ -84,7 +84,7 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory {
/*** GASLIMIT op ***/ /*** GASLIMIT op ***/
long gaslimit = block.getGasLimit(); long gaslimit = block.getGasLimit();
/*
if (logger.isInfoEnabled()) { if (logger.isInfoEnabled()) {
logger.info("Top level call: \n" + logger.info("Top level call: \n" +
"address={}\n" + "address={}\n" +
@ -117,7 +117,7 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory {
Hex.toHexString(difficulty), Hex.toHexString(difficulty),
gaslimit); gaslimit);
} }
*/
return new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, data, return new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, data,
lastHash, coinbase, timestamp, number, difficulty, gaslimit, lastHash, coinbase, timestamp, number, difficulty, gaslimit,
repository, blockStore); repository, blockStore);
@ -148,7 +148,7 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory {
DataWord number = program.getNumber(); DataWord number = program.getNumber();
DataWord difficulty = program.getDifficulty(); DataWord difficulty = program.getDifficulty();
DataWord gasLimit = program.getGaslimit(); DataWord gasLimit = program.getGaslimit();
/*
if (logger.isInfoEnabled()) { if (logger.isInfoEnabled()) {
logger.info("Internal call: \n" + logger.info("Internal call: \n" +
"address={}\n" + "address={}\n" +
@ -180,7 +180,7 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory {
Hex.toHexString(difficulty.getNoLeadZeroesData()), Hex.toHexString(difficulty.getNoLeadZeroesData()),
gasLimit.longValue()); gasLimit.longValue());
} }
*/
return new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, return new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue,
data, lastHash, coinbase, timestamp, number, difficulty, gasLimit, data, lastHash, coinbase, timestamp, number, difficulty, gasLimit,
repository, program.invokeData.getCallDeep() + 1, blockStore, byTestingSuite); repository, program.invokeData.getCallDeep() + 1, blockStore, byTestingSuite);

View File

@ -4,16 +4,12 @@ import org.ethereum.crypto.HashUtil;
import org.ethereum.db.ContractDetails; import org.ethereum.db.ContractDetails;
import org.ethereum.util.ByteUtil; import org.ethereum.util.ByteUtil;
import org.ethereum.vm.MessageCall.MsgType; import org.ethereum.vm.MessageCall.MsgType;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex; import org.spongycastle.util.encoders.Hex;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -79,8 +75,9 @@ public class VM {
try { try {
OpCode op = OpCode.code(program.getCurrentOp()); OpCode op = OpCode.code(program.getCurrentOp());
if (op == null) if (op == null) {
throw new Program.IllegalOperationException(); throw Program.Exception.invalidOpCode(program.getCurrentOp());
}
program.setLastOp(op.val()); program.setLastOp(op.val());
program.stackRequire(op.require()); program.stackRequire(op.require());
@ -161,7 +158,7 @@ public class VM {
gasCost = GasCost.CALL; gasCost = GasCost.CALL;
DataWord callGasWord = stack.get(stack.size() - 1); DataWord callGasWord = stack.get(stack.size() - 1);
if (callGasWord.compareTo(program.getGas()) == 1) { if (callGasWord.compareTo(program.getGas()) == 1) {
throw program.new OutOfGasException(); throw Program.Exception.notEnoughOpGas(op, callGasWord, program.getGas());
} }
callGas = callGasWord.longValue(); callGas = callGasWord.longValue();
BigInteger in = memNeeded(stack.get(stack.size() - 4), stack.get(stack.size() - 5)); // in offset+size 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 dataSize = stack.get(stack.size() - 2).value();
BigInteger dataCost = dataSize.multiply(BigInteger.valueOf(GasCost.LOG_DATA_GAS)); BigInteger dataCost = dataSize.multiply(BigInteger.valueOf(GasCost.LOG_DATA_GAS));
if (program.getGas().value().compareTo(dataCost) < 0) { if (program.getGas().value().compareTo(dataCost) < 0) {
throw program.new OutOfGasException(); throw Program.Exception.notEnoughOpGas(op, dataCost, program.getGas().value());
} }
gasCost = GasCost.LOG_GAS + gasCost = GasCost.LOG_GAS +
@ -203,8 +200,9 @@ public class VM {
program.spendGas(gasCost, op.name()); program.spendGas(gasCost, op.name());
// Avoid overflows // Avoid overflows
if (newMemSize.compareTo(MAX_GAS) == 1) if (newMemSize.compareTo(MAX_GAS) == 1) {
throw program.new OutOfGasException(); throw Program.Exception.gasOverflow(newMemSize, MAX_GAS);
}
// memory gas calc // memory gas calc
long memoryUsage = (newMemSize.longValue() + 31) / 32 * 32; long memoryUsage = (newMemSize.longValue() + 31) / 32 * 32;
@ -1008,13 +1006,13 @@ public class VM {
DataWord value = program.stackPop(); DataWord value = program.stackPop();
DataWord inOffset = program.stackPop(); DataWord inOffset = program.stackPop();
DataWord inSize = program.stackPop(); DataWord inSize = program.stackPop();
/*
if (logger.isInfoEnabled()) if (logger.isInfoEnabled())
logger.info(logString, program.getPC(), logger.info(logString, program.getPC(),
String.format("%-12s", op.name()), String.format("%-12s", op.name()),
program.getGas().value(), program.getGas().value(),
program.invokeData.getCallDeep(), hint); program.invokeData.getCallDeep(), hint);
*/
program.createContract(value, inOffset, inSize); program.createContract(value, inOffset, inSize);
program.step(); program.step();
@ -1031,7 +1029,7 @@ public class VM {
DataWord outDataOffs = program.stackPop(); DataWord outDataOffs = program.stackPop();
DataWord outDataSize = program.stackPop(); DataWord outDataSize = program.stackPop();
/*
if (logger.isInfoEnabled()) { if (logger.isInfoEnabled()) {
hint = "addr: " + Hex.toHexString(codeAddress.getLast20Bytes()) hint = "addr: " + Hex.toHexString(codeAddress.getLast20Bytes())
+ " gas: " + gas.shortHex() + " gas: " + gas.shortHex()
@ -1042,7 +1040,7 @@ public class VM {
program.getGas().value(), program.getGas().value(),
program.invokeData.getCallDeep(), hint); program.invokeData.getCallDeep(), hint);
} }
*/
program.memoryExpand(outDataOffs, outDataSize); program.memoryExpand(outDataOffs, outDataSize);
MessageCall msg = new MessageCall( MessageCall msg = new MessageCall(
@ -1092,13 +1090,13 @@ public class VM {
} }
program.setPreviouslyExecutedOp(op.val()); program.setPreviouslyExecutedOp(op.val());
/*
if (logger.isInfoEnabled() && !op.equals(CALL) if (logger.isInfoEnabled() && !op.equals(CALL)
&& !op.equals(CREATE)) && !op.equals(CREATE))
logger.info(logString, stepBefore, String.format("%-12s", logger.info(logString, stepBefore, String.format("%-12s",
op.name()), program.getGas().longValue(), op.name()), program.getGas().longValue(),
program.invokeData.getCallDeep(), hint); program.invokeData.getCallDeep(), hint);
*/
vmCounter++; vmCounter++;
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.warn("VM halted: [{}]", e.toString()); logger.warn("VM halted: [{}]", e.toString());
@ -1183,7 +1181,7 @@ public class VM {
String opString = Hex.toHexString(new byte[]{op.val()}); String opString = Hex.toHexString(new byte[]{op.val()});
String gasString = Hex.toHexString(program.getGas().getNoLeadZeroesData()); 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")) { } else if (CONFIG.dumpStyle().equals("pretty")) {
dumpLogger.trace(" STACK"); dumpLogger.trace(" STACK");
for (DataWord item : program.getStack()) { for (DataWord item : program.getStack()) {
@ -1209,9 +1207,9 @@ public class VM {
int level = program.invokeData.getCallDeep(); int level = program.invokeData.getCallDeep();
String contract = Hex.toHexString(program.getOwnerAddress().getLast20Bytes()); String contract = Hex.toHexString(program.getOwnerAddress().getLast20Bytes());
String internalSteps = String.format("%4s", Integer.toHexString(program.getPC())).replace(' ', '0').toUpperCase(); String internalSteps = String.format("%4s", Integer.toHexString(program.getPC())).replace(' ', '0').toUpperCase();
dumpLogger.trace("{} | {} | #{} | {} : {} | {} | -{} | {}x32", //dumpLogger.trace("{} | {} | #{} | {} : {} | {} | -{} | {}x32",
level, contract, vmCounter, internalSteps, op, // level, contract, vmCounter, internalSteps, op,
gasBefore, gasCost, memWords); // gasBefore, gasCost, memWords);
} }
} }
} }

View File

@ -19,8 +19,8 @@ public class ProgramTrace {
@JsonIgnore @JsonIgnore
private byte[] txHash; private byte[] txHash;
private List<Op> ops = new ArrayList<>(); private List<Op> ops = new ArrayList<>();
private String result; private String result = "";
private String error; private String error = "";
public void setTxHash(byte[] txHash) { public void setTxHash(byte[] txHash) {
this.txHash = txHash; this.txHash = txHash;
@ -31,7 +31,7 @@ public class ProgramTrace {
} }
public void setError(Exception error) { 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) { public void addOp(Op op) {
@ -46,7 +46,11 @@ public class ProgramTrace {
this.ops.addAll(programTrace.ops); this.ops.addAll(programTrace.ops);
} }
public String asJsonString(boolean needPrettify) {
return serializeFieldsOnly(this, needPrettify);
}
public String asJsonString() { public String asJsonString() {
return serializeFieldsOnly(this, true); return asJsonString(false);
} }
} }

View File

@ -1,6 +1,6 @@
package org.ethereum.wallet; package org.ethereum.wallet;
import javax.xml.bind.DatatypeConverter; //import javax.xml.bind.DatatypeConverter;
public class EtherSaleWallet { public class EtherSaleWallet {
@ -14,7 +14,7 @@ public class EtherSaleWallet {
} }
public byte[] getEncseedBytes() { public byte[] getEncseedBytes() {
return DatatypeConverter.parseHexBinary(encseed); return hexStringToByteArray(encseed);
} }
public void setEncseed(String encseed) { public void setEncseed(String encseed) {
@ -26,7 +26,7 @@ public class EtherSaleWallet {
} }
public byte[] getEthaddrBytes() { public byte[] getEthaddrBytes() {
return DatatypeConverter.parseHexBinary(ethaddr); return hexStringToByteArray(ethaddr);
} }
public void setEthaddr(String ethaddr) { public void setEthaddr(String ethaddr) {
@ -58,4 +58,14 @@ public class EtherSaleWallet {
", btcaddr='" + btcaddr + '\'' + ", 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;
}
} }

View File

@ -0,0 +1,3 @@
<resources>
<string name="app_name">ethereum-core</string>
</resources>

View File

@ -0,0 +1,134 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config />
<bean id="adminInfo" class="org.ethereum.manager.AdminInfo" init-method="init">
</bean>
<bean id="detailsDS" class="org.ethereum.datasource.LevelDbDataSource">
<property name="context" ref="androidContext" />
</bean>
<bean id="stateDS" class="org.ethereum.datasource.LevelDbDataSource">
<property name="context" ref="androidContext" />
</bean>
<bean id="repository" class="org.ethereum.db.RepositoryImpl">
<constructor-arg>
<ref bean="detailsDS" />
</constructor-arg>
<constructor-arg>
<ref bean="stateDS" />
</constructor-arg>
</bean>
<bean id="wallet" class="org.ethereum.core.Wallet" depends-on="worldManager">
</bean>
<bean id="PeerClient" class="org.ethereum.net.client.PeerClient" scope="prototype">
</bean>
<bean id="peerDiscovery" class="org.ethereum.net.peerdiscovery.PeerDiscovery">
</bean>
<bean id="channelManager" class="org.ethereum.net.server.ChannelManager" init-method="init">
</bean>
<bean id="cliInterface" class="org.ethereum.cli.CLIInterface">
</bean>
<bean id="account" class="org.ethereum.core.Account" scope="prototype">
</bean>
<bean id="blockchain" class="org.ethereum.core.BlockchainImpl">
<constructor-arg>
<set value-type="org.ethereum.core.Transaction">
</set>
</constructor-arg>
</bean>
<bean id="redisConnectionImpl" class="org.ethereum.datasource.redis.RedisConnectionImpl" init-method="tryConnect" destroy-method="destroy">
</bean>
<bean id="worldManager" class="org.ethereum.manager.WorldManager" init-method="init" destroy-method="close">
</bean>
<bean id="ethereumImpl" class="org.ethereum.facade.EthereumImpl" init-method="init">
</bean>
<bean id="blockQueue" class="org.ethereum.net.BlockQueue">
</bean>
<bean id="messageQueue" class="org.ethereum.net.MessageQueue" scope="prototype">
</bean>
<bean id="ethHandler" class="org.ethereum.net.eth.EthHandler" scope="prototype">
</bean>
<bean id="p2pHandler" class="org.ethereum.net.p2p.P2pHandler" scope="prototype">
</bean>
<bean id="discoveryChannel" class="org.ethereum.net.peerdiscovery.DiscoveryChannel" scope="prototype">
</bean>
<bean id="workerThread" class="org.ethereum.net.peerdiscovery.WorkerThread" scope="prototype">
</bean>
<bean id="channel" class="org.ethereum.net.server.Channel" scope="prototype">
</bean>
<bean id="ethereumChannelInitializer" class="org.ethereum.net.server.EthereumChannelInitializer">
</bean>
<bean id="peerServer" class="org.ethereum.net.server.PeerServer">
</bean>
<bean id="shhHandler" class="org.ethereum.net.shh.ShhHandler" scope="prototype">
</bean>
<bean id="messageDecoder" class="org.ethereum.net.wire.MessageDecoder" scope="prototype">
</bean>
<bean id="messageEncoder" class="org.ethereum.net.wire.MessageEncoder" scope="prototype">
</bean>
<bean id="programInvokeFactory" class="org.ethereum.vm.ProgramInvokeFactoryImpl">
</bean>
<bean id="listener" class="org.ethereum.listener.CompositeEthereumListener">
</bean>
<bean id="blockStore" class="org.ethereum.db.InMemoryBlockStore">
</bean>
<bean id="dataSource" class="org.robospring.ormlite.ios.IosJdbcSqliteDatabaseType">
<!--
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:file:./${database.dir}/blockchain/blockchain.db;create=${database.reset};hsqldb.default_table_type=cached"/>
<property name="username" value="sa"/>
-->
</bean>
<!-- define your beans here, use 'androidContext' to get a reference to your app's application context -->
</beans>

View File

@ -1 +1 @@
include ':app', ':ethereum-core' include ':app', ':ethereumj-core'