From 58874cfc7e1fcdf65a11d56f3034fde57bb6a1cc Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 26 Dec 2014 11:07:01 +0100 Subject: [PATCH] Apply basic formatting - Do not align assignments on equals signs - Use spaces before opening curly braces - Add spaces between parameters as necessary - Insert newlines between method declarations - Other minor changes This formatting pass is not comprehensive. For the most part, it does not deal with Javadoc formatting, line wrapping, parameter alignment rules or a number of other items that can be addressed later. --- ethereumj-core/bintray-publish-version.xml | 37 +- ethereumj-core/pom.xml | 28 +- .../src/main/java/org/ethereum/Start.java | 2 +- .../java/org/ethereum/cli/CLIInterface.java | 28 +- .../org/ethereum/config/SystemProperties.java | 72 +-- .../main/java/org/ethereum/core/Account.java | 26 +- .../java/org/ethereum/core/AccountState.java | 28 +- .../main/java/org/ethereum/core/Block.java | 34 +- .../java/org/ethereum/core/BlockHeader.java | 148 +++-- .../org/ethereum/core/BlockchainImpl.java | 75 +-- .../main/java/org/ethereum/core/Bloom.java | 8 +- .../main/java/org/ethereum/core/Chain.java | 18 +- .../main/java/org/ethereum/core/Genesis.java | 10 +- .../java/org/ethereum/core/Transaction.java | 79 +-- .../ethereum/core/TransactionExecutor.java | 21 +- .../org/ethereum/core/TransactionReceipt.java | 28 +- .../main/java/org/ethereum/core/Wallet.java | 32 +- .../main/java/org/ethereum/crypto/ECKey.java | 40 +- .../java/org/ethereum/crypto/HashUtil.java | 4 +- .../main/java/org/ethereum/db/BlockStore.java | 36 +- .../main/java/org/ethereum/db/BlockVO.java | 6 +- .../java/org/ethereum/db/ContractDetails.java | 20 +- .../java/org/ethereum/db/DatabaseImpl.java | 26 +- .../java/org/ethereum/db/RepositoryDummy.java | 54 +- .../java/org/ethereum/db/RepositoryImpl.java | 72 +-- .../java/org/ethereum/db/RepositoryTrack.java | 34 +- .../java/org/ethereum/db/TrackDatabase.java | 12 +- .../org/ethereum/db/TransactionReceiptVO.java | 4 +- .../java/org/ethereum/facade/Blockchain.java | 19 +- .../java/org/ethereum/facade/Ethereum.java | 7 +- .../org/ethereum/facade/EthereumFactory.java | 16 +- .../org/ethereum/facade/EthereumImpl.java | 37 +- .../java/org/ethereum/facade/Repository.java | 6 +- .../org/ethereum/json/EtherObjectMapper.java | 42 +- .../java/org/ethereum/json/JSONHelper.java | 6 +- .../ethereum/jsontestsuite/AccountState.java | 32 +- .../ethereum/jsontestsuite/CallCreate.java | 18 +- .../java/org/ethereum/jsontestsuite/Env.java | 18 +- .../java/org/ethereum/jsontestsuite/Exec.java | 27 +- .../org/ethereum/jsontestsuite/Helper.java | 33 +- .../ethereum/jsontestsuite/JSONReader.java | 7 +- .../java/org/ethereum/jsontestsuite/Logs.java | 28 +- .../ethereum/jsontestsuite/StateTestCase.java | 34 +- .../jsontestsuite/StateTestSuite.java | 10 +- .../org/ethereum/jsontestsuite/TestCase.java | 53 +- .../TestProgramInvokeFactory.java | 14 +- .../ethereum/jsontestsuite/TestRunner.java | 128 ++-- .../org/ethereum/jsontestsuite/TestSuite.java | 4 +- .../ethereum/jsontestsuite/Transaction.java | 34 +- .../org/ethereum/jsontestsuite/Utils.java | 6 +- .../ethereum/listener/EthereumListener.java | 7 + .../listener/EthereumListenerAdapter.java | 2 +- .../listener/EthereumListenerWrapper.java | 8 +- .../java/org/ethereum/manager/AdminInfo.java | 2 +- .../org/ethereum/manager/WorldManager.java | 20 +- .../main/java/org/ethereum/mine/Miner.java | 10 +- .../java/org/ethereum/net/BlockQueue.java | 51 +- .../java/org/ethereum/net/MessageQueue.java | 13 +- .../org/ethereum/net/client/Capability.java | 2 +- .../org/ethereum/net/client/PeerClient.java | 1 + .../ethereum/net/eth/BlockHashesMessage.java | 6 +- .../org/ethereum/net/eth/BlocksMessage.java | 6 +- .../java/org/ethereum/net/eth/EthHandler.java | 66 +- .../java/org/ethereum/net/eth/EthMessage.java | 3 +- .../org/ethereum/net/eth/EthMessageCodes.java | 53 +- .../net/eth/GetBlockHashesMessage.java | 14 +- .../ethereum/net/eth/GetBlocksMessage.java | 6 +- .../net/eth/GetTransactionsMessage.java | 6 +- .../org/ethereum/net/eth/NewBlockMessage.java | 16 +- .../ethereum/net/eth/PacketCountMessage.java | 5 +- .../org/ethereum/net/eth/StatusMessage.java | 40 +- .../ethereum/net/eth/TransactionsMessage.java | 6 +- .../org/ethereum/net/message/Message.java | 5 +- .../ethereum/net/message/MessageFactory.java | 2 +- .../org/ethereum/net/message/ReasonCode.java | 41 +- .../org/ethereum/net/message/ShhMessage.java | 3 +- .../ethereum/net/message/StaticMessages.java | 8 +- .../ethereum/net/p2p/DisconnectMessage.java | 2 +- .../org/ethereum/net/p2p/GetPeersMessage.java | 6 +- .../org/ethereum/net/p2p/HelloMessage.java | 30 +- .../java/org/ethereum/net/p2p/P2pHandler.java | 32 +- .../java/org/ethereum/net/p2p/P2pMessage.java | 3 +- .../org/ethereum/net/p2p/P2pMessageCodes.java | 36 +- .../main/java/org/ethereum/net/p2p/Peer.java | 2 +- .../org/ethereum/net/p2p/PeersMessage.java | 4 +- .../org/ethereum/net/p2p/PingMessage.java | 6 +- .../org/ethereum/net/p2p/PongMessage.java | 6 +- .../net/peerdiscovery/DiscoveryChannel.java | 10 +- .../net/peerdiscovery/PeerDiscovery.java | 12 +- .../ethereum/net/peerdiscovery/PeerInfo.java | 4 +- .../net/peerdiscovery/WorkerThread.java | 6 +- .../java/org/ethereum/net/server/Channel.java | 12 +- .../ethereum/net/server/ChannelManager.java | 34 +- .../java/org/ethereum/net/shh/ShhHandler.java | 8 +- .../java/org/ethereum/net/shh/ShhMessage.java | 3 +- .../org/ethereum/net/shh/ShhMessageCodes.java | 27 +- .../net/submit/TransactionExecutor.java | 1 + .../org/ethereum/net/wire/MessageDecoder.java | 8 +- .../org/ethereum/net/wire/MessageEncoder.java | 2 +- .../org/ethereum/serpent/ParserGenerator.java | 3 +- .../org/ethereum/serpent/ParserUtils.java | 80 +-- .../org/ethereum/serpent/SerpentCompiler.java | 24 +- .../serpent/SerpentToAssemblyCompiler.java | 182 +++--- .../main/java/org/ethereum/trie/Cache.java | 7 +- .../ethereum/trie/CollectFullSetOfNodes.java | 2 +- .../java/org/ethereum/trie/CountAllNodes.java | 4 +- .../src/main/java/org/ethereum/trie/Node.java | 7 +- .../main/java/org/ethereum/trie/TrieImpl.java | 39 +- .../java/org/ethereum/trie/TrieIterator.java | 3 +- .../main/java/org/ethereum/util/ByteUtil.java | 45 +- .../org/ethereum/util/CompactEncoder.java | 50 +- .../java/org/ethereum/util/DecodeResult.java | 3 +- .../ethereum/util/FastByteComparisons.java | 360 +++++------ .../main/java/org/ethereum/util/LRUMap.java | 2 +- .../src/main/java/org/ethereum/util/RLP.java | 86 +-- .../java/org/ethereum/util/RLPElement.java | 2 +- .../main/java/org/ethereum/util/RLPItem.java | 1 + .../main/java/org/ethereum/util/RLPList.java | 1 + .../main/java/org/ethereum/util/Utils.java | 19 +- .../main/java/org/ethereum/util/Value.java | 33 +- .../main/java/org/ethereum/vm/DataWord.java | 20 +- .../main/java/org/ethereum/vm/GasCost.java | 92 ++- .../main/java/org/ethereum/vm/LogInfo.java | 30 +- .../java/org/ethereum/vm/MessageCall.java | 38 +- .../src/main/java/org/ethereum/vm/OpCode.java | 545 +++++++++++----- .../main/java/org/ethereum/vm/Program.java | 77 +-- .../java/org/ethereum/vm/ProgramInvoke.java | 21 +- .../org/ethereum/vm/ProgramInvokeFactory.java | 7 +- .../ethereum/vm/ProgramInvokeFactoryImpl.java | 60 +- .../org/ethereum/vm/ProgramInvokeImpl.java | 57 +- .../ethereum/vm/ProgramInvokeMockImpl.java | 21 +- .../java/org/ethereum/vm/ProgramResult.java | 20 +- .../src/main/java/org/ethereum/vm/VM.java | 489 +++++++++------ .../main/java/org/ethereum/vmtrace/Op.java | 16 +- .../org/ethereum/vmtrace/ProgramTrace.java | 9 +- .../wallet/EtherSaleWalletDecoder.java | 3 +- .../test/java/test/ethereum/TestContext.java | 12 +- .../java/test/ethereum/core/BlockTest.java | 36 +- .../java/test/ethereum/core/BloomTest.java | 8 +- .../java/test/ethereum/core/ForkTest.java | 31 +- .../java/test/ethereum/core/LogInfoTest.java | 5 +- .../java/test/ethereum/core/MinerTest.java | 12 +- .../java/test/ethereum/core/StateTest.java | 2 +- .../ethereum/core/TransactionReceiptTest.java | 2 +- .../test/ethereum/core/TransactionTest.java | 42 +- .../java/test/ethereum/core/WalletTest.java | 11 +- .../java/test/ethereum/crypto/ECKeyTest.java | 20 +- .../ethereum/db/ByteArrayWrapperTest.java | 2 +- .../java/test/ethereum/db/RepositoryTest.java | 216 ++++--- .../test/ethereum/db/TrackDatabaseTest.java | 8 +- .../jsontestsuite/GitHubJSONTestSuite.java | 36 +- .../jsontestsuite/GitHubStateTest.java | 2 - .../java/test/ethereum/mine/ForkGenTest.java | 8 +- .../java/test/ethereum/mine/MineSwarm.java | 16 +- .../java/test/ethereum/mine/MinerThread.java | 50 +- .../ethereum/net/BlockHashesMessageTest.java | 6 +- .../test/ethereum/net/BlocksMessageTest.java | 4 +- .../test/ethereum/net/HelloMessageTest.java | 2 +- .../ethereum/net/NewBlockMessageTest.java | 4 +- .../test/ethereum/net/PeersMessageTest.java | 2 +- .../test/ethereum/net/StatusMessageTest.java | 2 +- .../ethereum/net/TransactionsMessageTest.java | 21 +- .../net/wire/AdaptiveMessageIdsTest.java | 67 +- .../ethereum/serpent/MachineCompileTest.java | 1 + .../ethereum/serpent/SerpentCompileTest.java | 110 ++-- .../java/test/ethereum/trie/TrieTest.java | 69 +-- .../java/test/ethereum/util/ByteUtilTest.java | 61 +- .../ethereum/util/CompactEncoderTest.java | 38 +- .../test/java/test/ethereum/util/RLPTest.java | 424 +++++++++---- .../java/test/ethereum/util/RlpTestData.java | 12 +- .../java/test/ethereum/util/UtilsTest.java | 1 + .../java/test/ethereum/util/ValueTest.java | 3 +- .../java/test/ethereum/vm/DataWordTest.java | 10 +- .../test/ethereum/vm/ProgramMemoryTest.java | 6 +- .../java/test/ethereum/vm/VMComplexTest.java | 35 +- .../java/test/ethereum/vm/VMCustomTest.java | 27 +- .../test/java/test/ethereum/vm/VMTest.java | 582 +++++++++--------- .../src/test/resources/dbdump/dbdump.json | 1 - ethereumj-studio/build-post-package.xml | 14 +- ethereumj-studio/pom.xml | 8 +- .../main/java/org/ethereum/geo/IpGeoDB.java | 1 + .../org/ethereum/gui/AccountsListWindow.java | 28 +- .../org/ethereum/gui/BlockChainTable.java | 6 +- .../ethereum/gui/ConnectionConsoleWindow.java | 2 +- .../org/ethereum/gui/ConsoleTokenMaker.java | 443 ++++++------- .../org/ethereum/gui/ContractCallDialog.java | 32 +- .../ethereum/gui/ContractSubmitDialog.java | 25 +- .../main/java/org/ethereum/gui/GUIUtils.java | 1 + .../java/org/ethereum/gui/PayOutDialog.java | 13 +- .../org/ethereum/gui/PeersTableModel.java | 23 +- .../org/ethereum/gui/PeersTableWindow.java | 6 +- .../org/ethereum/gui/ProgramPlayDialog.java | 13 +- .../java/org/ethereum/gui/SerpentEditor.java | 33 +- .../org/ethereum/gui/SerpentTokenMaker.java | 208 ++++--- .../org/ethereum/gui/StateExplorerWindow.java | 74 +-- .../main/java/org/ethereum/gui/ToolBar.java | 17 +- .../org/ethereum/gui/WalletAddressPanel.java | 5 +- .../java/org/ethereum/gui/WalletSumPanel.java | 3 +- .../java/org/ethereum/gui/WalletWindow.java | 3 +- 199 files changed, 4309 insertions(+), 3331 deletions(-) diff --git a/ethereumj-core/bintray-publish-version.xml b/ethereumj-core/bintray-publish-version.xml index 30d6b202..3960fa24 100644 --- a/ethereumj-core/bintray-publish-version.xml +++ b/ethereumj-core/bintray-publish-version.xml @@ -1,4 +1,3 @@ - - - + - - + + @@ -43,24 +41,24 @@ - - + + + else="${artifact.version}"> - + - + @@ -78,8 +76,6 @@ - - @@ -93,11 +89,11 @@ + value="${repo.location}/${artifact.group.path}/${artifact.id}/${artifact.version}/"/> + value="${artifact.group.path}/${artifact.id}/${bintray.version}/${artifact.id}-${bintray.version}"/> @@ -116,10 +112,9 @@ - - + @@ -132,11 +127,11 @@ - - - + + + - + @@ -169,6 +164,4 @@ - - diff --git a/ethereumj-core/pom.xml b/ethereumj-core/pom.xml index f8f558a7..3d577b68 100644 --- a/ethereumj-core/pom.xml +++ b/ethereumj-core/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 org.ethereum ethereumj @@ -8,14 +8,14 @@ EthereumJ http://www.ethereumj.org - + --> @@ -70,9 +70,9 @@ - com.cedarsoftware - java-util - 1.8.0 + com.cedarsoftware + java-util + 1.8.0 @@ -347,7 +347,7 @@ - - + --> org.antlr @@ -400,9 +399,8 @@ - - + diff --git a/ethereumj-core/src/main/java/org/ethereum/Start.java b/ethereumj-core/src/main/java/org/ethereum/Start.java index 7a830b73..b72d2551 100644 --- a/ethereumj-core/src/main/java/org/ethereum/Start.java +++ b/ethereumj-core/src/main/java/org/ethereum/Start.java @@ -14,7 +14,7 @@ import org.ethereum.facade.EthereumFactory; public class Start { - public static void main(String args[]){ + public static void main(String args[]) { CLIInterface.call(args); Ethereum ethereum = EthereumFactory.createEthereum(); diff --git a/ethereumj-core/src/main/java/org/ethereum/cli/CLIInterface.java b/ethereumj-core/src/main/java/org/ethereum/cli/CLIInterface.java index 687b4b01..cfb9c35b 100644 --- a/ethereumj-core/src/main/java/org/ethereum/cli/CLIInterface.java +++ b/ethereumj-core/src/main/java/org/ethereum/cli/CLIInterface.java @@ -19,35 +19,35 @@ public class CLIInterface { private static final Logger logger = LoggerFactory.getLogger("cli"); - public static void call(String[] args){ + public static void call(String[] args) { try { - for (int i = 0; i < args.length; ++i){ + for (int i = 0; i < args.length; ++i) { // override the db directory - if (args[i].equals("--help")){ + if (args[i].equals("--help")) { printHelp(); System.exit(1); } // override the db directory - if (args[i].equals("-db") && i + 1 < args.length){ - String db = args[i+1]; + if (args[i].equals("-db") && i + 1 < args.length) { + String db = args[i + 1]; logger.info("DB directory set to [{}]", db); CONFIG.setDataBaseDir(db); } // override the listen port directory - if (args[i].equals("-listen") && i + 1 < args.length){ - String port = args[i+1]; + if (args[i].equals("-listen") && i + 1 < args.length) { + String port = args[i + 1]; logger.info("Listen port set to [{}]", port); CONFIG.setListenPort(Integer.valueOf(port)); } // override the connect host:port directory - if (args[i].equals("-connect") && i + 1 < args.length){ - String connectStr = args[i+1]; + if (args[i].equals("-connect") && i + 1 < args.length) { + String connectStr = args[i + 1]; logger.info("Connect host:port set to [{}]", connectStr); String[] params = connectStr.split(":"); String host = params[0]; @@ -57,8 +57,8 @@ public class CLIInterface { } // override the listen port directory - if (args[i].equals("-reset") && i + 1 < args.length){ - Boolean resetStr = interpret( args[i+1] ); + if (args[i].equals("-reset") && i + 1 < args.length) { + Boolean resetStr = interpret(args[i + 1]); logger.info("Resetting db set to [{}]", resetStr); CONFIG.setDatabaseReset(resetStr); } @@ -70,15 +70,15 @@ public class CLIInterface { } } - private static Boolean interpret(String arg){ + private static Boolean interpret(String arg) { - if (arg.equals("on") || arg.equals("true") || arg.equals("yes")) return true; + if (arg.equals("on") || arg.equals("true") || arg.equals("yes")) return true; if (arg.equals("off") || arg.equals("false") || arg.equals("no")) return false; throw new Error("Can't interpret the answer: " + arg); } - private static void printHelp(){ + private static void printHelp() { System.out.println("--help -- this help message "); System.out.println("-reset -- reset yes/no the all database "); diff --git a/ethereumj-core/src/main/java/org/ethereum/config/SystemProperties.java b/ethereumj-core/src/main/java/org/ethereum/config/SystemProperties.java index 96552024..0554e33e 100644 --- a/ethereumj-core/src/main/java/org/ethereum/config/SystemProperties.java +++ b/ethereumj-core/src/main/java/org/ethereum/config/SystemProperties.java @@ -14,41 +14,41 @@ import org.springframework.stereotype.Component; * Utility class to retrieve property values from the system.properties files * * @author Roman Mandeleil - * Created on: 22/05/2014 19:22 + * Created on: 22/05/2014 19:22 */ public class SystemProperties { private static Logger logger = LoggerFactory.getLogger("general"); - private static int DEFAULT_TX_APPROVE_TIMEOUT = 10; - private static String DEFAULT_DISCOVERY_PEER_LIST = "poc-7.ethdev.com:30303"; - private static String DEFAULT_ACTIVE_PEER_IP = "poc-7.ethdev.com"; - private static int DEFAULT_ACTIVE_PORT = 30303; - private static String DEFAULT_SAMPLES_DIR = "samples"; - private static String DEFAULT_COINBASE_SECRET = "monkey"; - private static int DEFAULT_ACTIVE_PEER_CHANNEL_TIMEOUT = 5; - private static Boolean DEFAULT_DB_RESET = false; - private static Boolean DEFAULT_DUMP_FULL = false; - private static Boolean DEFAULT_RECORD_BLOCKS = false; - private static String DEFAULT_DUMP_DIR = "dmp"; - private static String DEFAULT_DUMP_STYLE = "standard+"; - private static Integer DEFAULT_VMTRACE_BLOCK = 0; - private static String DEFAULT_DATABASE_DIR = System.getProperty("user.dir"); - private static Boolean DEFAULT_DUMP_CLEAN_ON_RESTART = true; - private static Boolean DEFAULT_PLAY_VM = true; - private static Boolean DEFAULT_BLOCKCHAIN_ONLY = false; - private static int DEFAULT_TRACE_STARTBLOCK = -1; - private static int DEFAULT_MAX_HASHES_ASK = -1; // unlimited - private static int DEFAULT_MAX_BLOCKS_ASK = 10; - private static int DEFAULT_MAX_BLOCKS_QUEUED = 300; - private static String DEFAULT_PROJECT_VERSION = ""; - private static String DEFAULT_HELLO_PHRASE = "Dev"; - private static Boolean DEFAULT_VM_TRACE = false; - private static String DEFAULT_VM_TRACE_DIR = "dmp"; - private static int DEFAULT_PEER_LISTEN_PORT = 30303; + private static int DEFAULT_TX_APPROVE_TIMEOUT = 10; + private static String DEFAULT_DISCOVERY_PEER_LIST = "poc-7.ethdev.com:30303"; + private static String DEFAULT_ACTIVE_PEER_IP = "poc-7.ethdev.com"; + private static int DEFAULT_ACTIVE_PORT = 30303; + private static String DEFAULT_SAMPLES_DIR = "samples"; + private static String DEFAULT_COINBASE_SECRET = "monkey"; + private static int DEFAULT_ACTIVE_PEER_CHANNEL_TIMEOUT = 5; + private static Boolean DEFAULT_DB_RESET = false; + private static Boolean DEFAULT_DUMP_FULL = false; + private static Boolean DEFAULT_RECORD_BLOCKS = false; + private static String DEFAULT_DUMP_DIR = "dmp"; + private static String DEFAULT_DUMP_STYLE = "standard+"; + private static Integer DEFAULT_VMTRACE_BLOCK = 0; + private static String DEFAULT_DATABASE_DIR = System.getProperty("user.dir"); + private static Boolean DEFAULT_DUMP_CLEAN_ON_RESTART = true; + private static Boolean DEFAULT_PLAY_VM = true; + private static Boolean DEFAULT_BLOCKCHAIN_ONLY = false; + private static int DEFAULT_TRACE_STARTBLOCK = -1; + private static int DEFAULT_MAX_HASHES_ASK = -1; // unlimited + private static int DEFAULT_MAX_BLOCKS_ASK = 10; + private static int DEFAULT_MAX_BLOCKS_QUEUED = 300; + private static String DEFAULT_PROJECT_VERSION = ""; + private static String DEFAULT_HELLO_PHRASE = "Dev"; + private static Boolean DEFAULT_VM_TRACE = false; + private static String DEFAULT_VM_TRACE_DIR = "dmp"; + private static int DEFAULT_PEER_LISTEN_PORT = 30303; /* Testing */ - private static Boolean DEFAULT_VMTEST_LOAD_LOCAL = false; + private static Boolean DEFAULT_VMTEST_LOAD_LOCAL = false; private static List DEFAULT_PROTOCOL_LIST = Arrays.asList("eth", "shh"); @@ -122,7 +122,7 @@ public class SystemProperties { return Boolean.parseBoolean(prop.getProperty("database.reset")); } - public void setDatabaseReset(Boolean reset){ + public void setDatabaseReset(Boolean reset) { prop.setProperty("database.reset", reset.toString()); } @@ -131,7 +131,7 @@ public class SystemProperties { return prop.getProperty("peer.active.ip"); } - public void setActivePeerIP(String host){ + public void setActivePeerIP(String host) { prop.setProperty("peer.active.ip", host.toString()); } @@ -140,7 +140,7 @@ public class SystemProperties { return Integer.parseInt(prop.getProperty("peer.active.port")); } - public void setActivePeerPort(Integer port){ + public void setActivePeerPort(Integer port) { prop.setProperty("peer.active.port", port.toString()); } @@ -195,7 +195,7 @@ public class SystemProperties { return prop.getProperty("database.dir"); } - public void setDataBaseDir(String dataBaseDir){ + public void setDataBaseDir(String dataBaseDir) { prop.setProperty("database.dir", dataBaseDir); } @@ -247,13 +247,13 @@ public class SystemProperties { return hash; } - public List peerCapabilities(){ + public List peerCapabilities() { if (prop.isEmpty()) return DEFAULT_PROTOCOL_LIST; String capabilitiesList = prop.getProperty("peer.capabilities"); return Arrays.asList(capabilitiesList.split(",")); } - public boolean vmTrace(){ + public boolean vmTrace() { if (prop.isEmpty()) return DEFAULT_VM_TRACE; return Boolean.parseBoolean(prop.getProperty("vm.structured.trace")); } @@ -263,12 +263,12 @@ public class SystemProperties { return prop.getProperty("vm.structured.dir"); } - public int listenPort(){ + public int listenPort() { if (prop.isEmpty()) return DEFAULT_PEER_LISTEN_PORT; return Integer.parseInt(prop.getProperty("peer.listen.port")); } - public void setListenPort(Integer port){ + public void setListenPort(Integer port) { prop.setProperty("peer.listen.port", port.toString()); } diff --git a/ethereumj-core/src/main/java/org/ethereum/core/Account.java b/ethereumj-core/src/main/java/org/ethereum/core/Account.java index 8f184f29..61f5bb22 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Account.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Account.java @@ -16,7 +16,7 @@ import org.springframework.stereotype.Component; */ @Component @Scope("prototype") -public class Account { +public class Account { private ECKey ecKey; private byte[] address; @@ -30,7 +30,7 @@ public class Account { public Account() { } - public void init(){ + public void init() { this.ecKey = new ECKey(Utils.getRandom()); address = this.ecKey.getAddress(); } @@ -40,14 +40,14 @@ public class Account { address = this.ecKey.getAddress(); } - public BigInteger getNonce(){ + public BigInteger getNonce() { AccountState accountState = worldManager.getRepository().getAccountState(getAddress()); return accountState.getNonce(); } - public BigInteger getBalance(){ + public BigInteger getBalance() { AccountState accountState = worldManager.getRepository().getAccountState(this.getAddress()); @@ -57,15 +57,15 @@ public class Account { if (accountState != null) balance = accountState.getBalance(); - synchronized (getPendingTransactins()){ - if (!getPendingTransactins().isEmpty()){ + synchronized (getPendingTransactins()) { + if (!getPendingTransactins().isEmpty()) { - for (Transaction tx : getPendingTransactins()){ - if (Arrays.equals(getAddress(), tx.getSender())){ + for (Transaction tx : getPendingTransactins()) { + if (Arrays.equals(getAddress(), tx.getSender())) { balance = balance.subtract(new BigInteger(1, tx.getValue())); } - if (Arrays.equals(getAddress(), tx.getReceiveAddress())){ + if (Arrays.equals(getAddress(), tx.getReceiveAddress())) { balance = balance.add(new BigInteger(1, tx.getValue())); } } @@ -94,14 +94,14 @@ public class Account { return this.pendingTransactions; } - public void addPendingTransaction(Transaction transaction){ - synchronized (pendingTransactions){ + public void addPendingTransaction(Transaction transaction) { + synchronized (pendingTransactions) { pendingTransactions.add(transaction); } } - public void clearAllPendingTransactions(){ - synchronized (pendingTransactions){ + public void clearAllPendingTransactions() { + synchronized (pendingTransactions) { pendingTransactions.clear(); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/core/AccountState.java b/ethereumj-core/src/main/java/org/ethereum/core/AccountState.java index aa822a91..76f249d4 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/AccountState.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/AccountState.java @@ -41,7 +41,7 @@ public class AccountState { * retrieval */ private byte[] codeHash = EMPTY_DATA_HASH; - private boolean dirty = false; + private boolean dirty = false; private boolean deleted = false; @@ -57,13 +57,13 @@ public class AccountState { public AccountState(byte[] rlpData) { this.rlpEncoded = rlpData; - RLPList items = (RLPList) RLP.decode2(rlpEncoded).get(0); + RLPList items = (RLPList) RLP.decode2(rlpEncoded).get(0); this.nonce = items.get(0).getRLPData() == null ? BigInteger.ZERO : new BigInteger(1, items.get(0).getRLPData()); this.balance = items.get(1).getRLPData() == null ? BigInteger.ZERO : new BigInteger(1, items.get(1).getRLPData()); - this.stateRoot = items.get(2).getRLPData(); - this.codeHash = items.get(3).getRLPData(); + this.stateRoot = items.get(2).getRLPData(); + this.codeHash = items.get(3).getRLPData(); } public BigInteger getNonce() { @@ -117,11 +117,11 @@ public class AccountState { } public byte[] getEncoded() { - if(rlpEncoded == null) { - byte[] nonce = RLP.encodeBigInteger(this.nonce); - byte[] balance = RLP.encodeBigInteger(this.balance); - byte[] stateRoot = RLP.encodeElement(this.stateRoot); - byte[] codeHash = RLP.encodeElement(this.codeHash); + if (rlpEncoded == null) { + byte[] nonce = RLP.encodeBigInteger(this.nonce); + byte[] balance = RLP.encodeBigInteger(this.balance); + byte[] stateRoot = RLP.encodeElement(this.stateRoot); + byte[] codeHash = RLP.encodeElement(this.codeHash); this.rlpEncoded = RLP.encodeList(nonce, balance, stateRoot, codeHash); } return rlpEncoded; @@ -143,7 +143,7 @@ public class AccountState { return deleted; } - public AccountState clone(){ + public AccountState clone() { AccountState accountState = new AccountState(); accountState.addToBalance(this.getBalance()); @@ -156,10 +156,10 @@ public class AccountState { } public String toString() { - String ret = " Nonce: " + this.getNonce().toString() + "\n" + - " Balance: " + getBalance() + "\n" + - " State Root: " + Hex.toHexString(this.getStateRoot()) + "\n" + - " Code Hash: " + Hex.toHexString(this.getCodeHash()); + String ret = " Nonce: " + this.getNonce().toString() + "\n" + + " Balance: " + getBalance() + "\n" + + " State Root: " + Hex.toHexString(this.getStateRoot()) + "\n" + + " Code Hash: " + Hex.toHexString(this.getCodeHash()); return ret; } } diff --git a/ethereumj-core/src/main/java/org/ethereum/core/Block.java b/ethereumj-core/src/main/java/org/ethereum/core/Block.java index 8805a49b..92c53ae6 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Block.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Block.java @@ -23,6 +23,7 @@ import java.util.concurrent.CopyOnWriteArrayList; * (such blocks are known as uncles). * * www.ethereumJ.com + * * @author Roman Mandeleil, * Nick Savers * Created on: 20/05/2014 10:44 @@ -31,7 +32,7 @@ public class Block { private static final Logger logger = LoggerFactory.getLogger("block"); - public static BigInteger BLOCK_REWARD = BigInteger.valueOf(1500000000000000000L); + public static BigInteger BLOCK_REWARD = BigInteger.valueOf(1500000000000000000L); public static BigInteger UNCLE_REWARD = BLOCK_REWARD.multiply( BigInteger.valueOf(15)).divide(BigInteger.valueOf(16)); public static BigInteger INCLUSION_REWARD = Block.BLOCK_REWARD @@ -65,11 +66,11 @@ public class Block { long gasUsed, long timestamp, byte[] extraData, byte[] nonce, List transactionsList, List uncleList) { this.header = new BlockHeader(parentHash, unclesHash, coinbase, logsBloom, - difficulty, number, gasLimit, gasUsed, + difficulty, number, gasLimit, gasUsed, timestamp, extraData, nonce); this.transactionsList = transactionsList; - if (this.transactionsList == null){ + if (this.transactionsList == null) { this.transactionsList = new CopyOnWriteArrayList(); } @@ -105,7 +106,7 @@ public class Block { this.parsed = true; } - public BlockHeader getHeader(){ + public BlockHeader getHeader() { if (!parsed) parseRLP(); return this.header; } @@ -162,7 +163,7 @@ public class Block { return this.header.getTxTrieRoot(); } - public byte[] getLogBloom(){ + public byte[] getLogBloom() { if (!parsed) parseRLP(); return this.header.getLogsBloom(); } @@ -243,7 +244,7 @@ public class Block { toStringBuff.append(header.toString()); toStringBuff.append("\nUncles [\n"); - for (BlockHeader uncle : getUncleList()){ + for (BlockHeader uncle : getUncleList()) { toStringBuff.append(uncle.toString()); toStringBuff.append("\n"); } @@ -277,20 +278,21 @@ public class Block { for (int i = 0; i < txTransactions.size(); i++) { RLPElement transactionRaw = txTransactions.get(i); this.transactionsList.add(new Transaction(transactionRaw.getRLPData())); - this.txsState.update(RLP.encodeInt(i) , transactionRaw.getRLPData()); + this.txsState.update(RLP.encodeInt(i), transactionRaw.getRLPData()); } String calculatedRoot = Hex.toHexString(txsState.getRootHash()); - if(!calculatedRoot.equals(Hex.toHexString(expectedRoot))) + if (!calculatedRoot.equals(Hex.toHexString(expectedRoot))) logger.error("Added tx receipts don't match the given txsStateRoot"); } /** * check if param block is son of this block + * * @param block - possible a son of this * @return - true if this block is parent of param block */ - public boolean isParentOf(Block block){ + public boolean isParentOf(Block block) { return Arrays.areEqual(this.getHash(), block.getParentHash()); } @@ -298,29 +300,29 @@ public class Block { return this.header.isGenesis(); } - public boolean isEqual(Block block){ + public boolean isEqual(Block block) { return Arrays.areEqual(this.getHash(), block.getHash()); } - private byte[] getUnclesEncoded(){ + private byte[] getUnclesEncoded() { byte[][] unclesEncoded = new byte[uncleList.size()][]; int i = 0; - for( BlockHeader uncle : uncleList ){ + for (BlockHeader uncle : uncleList) { unclesEncoded[i] = uncle.getEncoded(); ++i; } return RLP.encodeList(unclesEncoded); } - public void addUncle(BlockHeader uncle){ + public void addUncle(BlockHeader uncle) { uncleList.add(uncle); - this.getHeader().setUnclesHash( SHA3Helper.sha3( getUnclesEncoded() )); + this.getHeader().setUnclesHash(SHA3Helper.sha3(getUnclesEncoded())); rlpEncoded = null; } public byte[] getEncoded() { - if(rlpEncoded == null) { + if (rlpEncoded == null) { byte[] header = this.header.getEncoded(); byte[] transactions = RLP.encodeList(); byte[] uncles = getUnclesEncoded(); @@ -335,7 +337,7 @@ public class Block { return header; } - public String getShortHash(){ + public String getShortHash() { if (!parsed) parseRLP(); return Hex.toHexString(getHash()).substring(0, 6); } diff --git a/ethereumj-core/src/main/java/org/ethereum/core/BlockHeader.java b/ethereumj-core/src/main/java/org/ethereum/core/BlockHeader.java index bed731e0..ecf78eea 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/BlockHeader.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/BlockHeader.java @@ -18,7 +18,7 @@ public class BlockHeader { /* The SHA3 256-bit hash of the parent block, in its entirety */ - private byte[] parentHash; + private byte[] parentHash; /* The SHA3 256-bit hash of the uncles list portion of this block */ private byte[] unclesHash; /* The 160-bit address to which all fees collected from the @@ -63,40 +63,40 @@ public class BlockHeader { public BlockHeader(RLPList rlpHeader) { - this.parentHash = rlpHeader.get(0).getRLPData(); - this.unclesHash = rlpHeader.get(1).getRLPData(); - this.coinbase = rlpHeader.get(2).getRLPData(); - this.stateRoot = rlpHeader.get(3).getRLPData(); + this.parentHash = rlpHeader.get(0).getRLPData(); + this.unclesHash = rlpHeader.get(1).getRLPData(); + this.coinbase = rlpHeader.get(2).getRLPData(); + this.stateRoot = rlpHeader.get(3).getRLPData(); - this.txTrieRoot = rlpHeader.get(4).getRLPData(); - if(this.txTrieRoot == null) + this.txTrieRoot = rlpHeader.get(4).getRLPData(); + if (this.txTrieRoot == null) this.txTrieRoot = EMPTY_TRIE_HASH; - this.recieptTrieRoot = rlpHeader.get(5).getRLPData(); - if(this.recieptTrieRoot == null) + this.recieptTrieRoot = rlpHeader.get(5).getRLPData(); + if (this.recieptTrieRoot == null) this.recieptTrieRoot = EMPTY_TRIE_HASH; - this.logsBloom = rlpHeader.get(6).getRLPData(); - this.difficulty = rlpHeader.get(7).getRLPData(); + this.logsBloom = rlpHeader.get(6).getRLPData(); + this.difficulty = rlpHeader.get(7).getRLPData(); - byte[] nrBytes = rlpHeader.get(8).getRLPData(); - byte[] glBytes = rlpHeader.get(9).getRLPData(); - byte[] guBytes = rlpHeader.get(10).getRLPData(); - byte[] tsBytes = rlpHeader.get(11).getRLPData(); + byte[] nrBytes = rlpHeader.get(8).getRLPData(); + byte[] glBytes = rlpHeader.get(9).getRLPData(); + byte[] guBytes = rlpHeader.get(10).getRLPData(); + byte[] tsBytes = rlpHeader.get(11).getRLPData(); - this.number = nrBytes == null ? 0 : (new BigInteger(1, nrBytes)).longValue(); + this.number = nrBytes == null ? 0 : (new BigInteger(1, nrBytes)).longValue(); - this.gasLimit = glBytes == null ? 0 : (new BigInteger(1, glBytes)).longValue(); - this.gasUsed = guBytes == null ? 0 : (new BigInteger(1, guBytes)).longValue(); - this.timestamp = tsBytes == null ? 0 : (new BigInteger(1, tsBytes)).longValue(); + this.gasLimit = glBytes == null ? 0 : (new BigInteger(1, glBytes)).longValue(); + this.gasUsed = guBytes == null ? 0 : (new BigInteger(1, guBytes)).longValue(); + this.timestamp = tsBytes == null ? 0 : (new BigInteger(1, tsBytes)).longValue(); - this.extraData = rlpHeader.get(12).getRLPData(); - this.nonce = rlpHeader.get(13).getRLPData(); + this.extraData = rlpHeader.get(12).getRLPData(); + this.nonce = rlpHeader.get(13).getRLPData(); } public BlockHeader(byte[] parentHash, byte[] unclesHash, byte[] coinbase, - byte[] logsBloom, byte[] difficulty, long number, + byte[] logsBloom, byte[] difficulty, long number, long gasLimit, long gasUsed, long timestamp, byte[] extraData, byte[] nonce) { this.parentHash = parentHash; @@ -117,6 +117,7 @@ public class BlockHeader { /** * Calculate Difficulty * See Yellow Paper: http://www.gavwood.com/Paper.pdf - page 5, 4.3.4 (24) + * * @return byte array value of the difficulty */ public byte[] calcDifficulty() { @@ -132,8 +133,6 @@ public class BlockHeader { } - - public boolean isGenesis() { return this.getNumber() == Genesis.NUMBER; } @@ -141,79 +140,107 @@ public class BlockHeader { public byte[] getParentHash() { return parentHash; } + public void setParentHash(byte[] parentHash) { this.parentHash = parentHash; } + public byte[] getUnclesHash() { return unclesHash; } + public void setUnclesHash(byte[] unclesHash) { this.unclesHash = unclesHash; } + public byte[] getCoinbase() { return coinbase; } + public void setCoinbase(byte[] coinbase) { this.coinbase = coinbase; } + public byte[] getStateRoot() { return stateRoot; } + public void setStateRoot(byte[] stateRoot) { this.stateRoot = stateRoot; } + public byte[] getTxTrieRoot() { return txTrieRoot; } + public void setTxTrieRoot(byte[] txTrieRoot) { this.txTrieRoot = txTrieRoot; } + public byte[] getRecieptTrieRoot() { return recieptTrieRoot; } - public byte[] getLogsBloom() {return logsBloom;} + + public byte[] getLogsBloom() { + return logsBloom; + } + public void setRecieptTrieRoot(byte[] recieptTrieRoot) { this.recieptTrieRoot = recieptTrieRoot; } + public byte[] getDifficulty() { return difficulty; } + public void setDifficulty(byte[] difficulty) { this.difficulty = difficulty; } + public long getTimestamp() { return timestamp; } + public void setTimestamp(long timestamp) { this.timestamp = timestamp; } + public long getNumber() { return number; } + public void setNumber(long number) { this.number = number; } + public long getGasLimit() { return gasLimit; } + public void setGasLimit(long gasLimit) { this.gasLimit = gasLimit; } + public long getGasUsed() { return gasUsed; } + public void setGasUsed(long gasUsed) { this.gasUsed = gasUsed; } + public byte[] getExtraData() { return extraData; } + public void setExtraData(byte[] extraData) { this.extraData = extraData; } + public byte[] getNonce() { return nonce; } + public void setNonce(byte[] nonce) { this.nonce = nonce; } @@ -227,31 +254,31 @@ public class BlockHeader { } public byte[] getEncoded(boolean withNonce) { - byte[] parentHash = RLP.encodeElement(this.parentHash); + byte[] parentHash = RLP.encodeElement(this.parentHash); - byte[] unclesHash = RLP.encodeElement(this.unclesHash); - byte[] coinbase = RLP.encodeElement(this.coinbase); + byte[] unclesHash = RLP.encodeElement(this.unclesHash); + byte[] coinbase = RLP.encodeElement(this.coinbase); - byte[] stateRoot = RLP.encodeElement(this.stateRoot); + byte[] stateRoot = RLP.encodeElement(this.stateRoot); if (txTrieRoot == null) this.txTrieRoot = EMPTY_TRIE_HASH; - byte[] txTrieRoot = RLP.encodeElement(this.txTrieRoot); + byte[] txTrieRoot = RLP.encodeElement(this.txTrieRoot); if (recieptTrieRoot == null) this.recieptTrieRoot = EMPTY_TRIE_HASH; - byte[] recieptTrieRoot = RLP.encodeElement(this.recieptTrieRoot); + byte[] recieptTrieRoot = RLP.encodeElement(this.recieptTrieRoot); - byte[] logsBloom = RLP.encodeElement(this.logsBloom); - byte[] difficulty = RLP.encodeElement(this.difficulty); - byte[] number = RLP.encodeBigInteger(BigInteger.valueOf(this.number)); - byte[] gasLimit = RLP.encodeBigInteger(BigInteger.valueOf(this.gasLimit)); - byte[] gasUsed = RLP.encodeBigInteger(BigInteger.valueOf(this.gasUsed)); - byte[] timestamp = RLP.encodeBigInteger(BigInteger.valueOf(this.timestamp)); - byte[] extraData = RLP.encodeElement(this.extraData); - if(withNonce) { - byte[] nonce = RLP.encodeElement(this.nonce); + byte[] logsBloom = RLP.encodeElement(this.logsBloom); + byte[] difficulty = RLP.encodeElement(this.difficulty); + byte[] number = RLP.encodeBigInteger(BigInteger.valueOf(this.number)); + byte[] gasLimit = RLP.encodeBigInteger(BigInteger.valueOf(this.gasLimit)); + byte[] gasUsed = RLP.encodeBigInteger(BigInteger.valueOf(this.gasUsed)); + byte[] timestamp = RLP.encodeBigInteger(BigInteger.valueOf(this.timestamp)); + byte[] extraData = RLP.encodeElement(this.extraData); + if (withNonce) { + byte[] nonce = RLP.encodeElement(this.nonce); return RLP.encodeList(parentHash, unclesHash, coinbase, stateRoot, txTrieRoot, recieptTrieRoot, logsBloom, difficulty, number, - gasLimit, gasUsed, timestamp, extraData, nonce); + gasLimit, gasUsed, timestamp, extraData, nonce); } else { return RLP.encodeList(parentHash, unclesHash, coinbase, stateRoot, txTrieRoot, recieptTrieRoot, logsBloom, difficulty, number, @@ -260,7 +287,6 @@ public class BlockHeader { } - private StringBuffer toStringBuff = new StringBuffer(); public String toString() { @@ -269,16 +295,16 @@ public class BlockHeader { toStringBuff.append(" parentHash=" + toHexString(parentHash)).append("\n"); toStringBuff.append(" unclesHash=" + toHexString(unclesHash)).append("\n"); toStringBuff.append(" coinbase=" + toHexString(coinbase)).append("\n"); - toStringBuff.append(" stateRoot=" + toHexString(stateRoot)).append("\n"); - toStringBuff.append(" txTrieHash=" + toHexString(txTrieRoot)).append("\n"); - toStringBuff.append(" reciptsTrieHash=" + toHexString(recieptTrieRoot)).append("\n"); - toStringBuff.append(" difficulty=" + toHexString(difficulty)).append("\n"); - toStringBuff.append(" number=" + number).append("\n"); - toStringBuff.append(" gasLimit=" + gasLimit).append("\n"); - toStringBuff.append(" gasUsed=" + gasUsed).append("\n"); - toStringBuff.append(" timestamp=" + timestamp + " (" + Utils.longToDateTime(timestamp) + ")").append("\n"); - toStringBuff.append(" extraData=" + toHexString(extraData)).append("\n"); - toStringBuff.append(" nonce=" + toHexString(nonce)).append("\n"); + toStringBuff.append(" stateRoot=" + toHexString(stateRoot)).append("\n"); + toStringBuff.append(" txTrieHash=" + toHexString(txTrieRoot)).append("\n"); + toStringBuff.append(" reciptsTrieHash=" + toHexString(recieptTrieRoot)).append("\n"); + toStringBuff.append(" difficulty=" + toHexString(difficulty)).append("\n"); + toStringBuff.append(" number=" + number).append("\n"); + toStringBuff.append(" gasLimit=" + gasLimit).append("\n"); + toStringBuff.append(" gasUsed=" + gasUsed).append("\n"); + toStringBuff.append(" timestamp=" + timestamp + " (" + Utils.longToDateTime(timestamp) + ")").append("\n"); + toStringBuff.append(" extraData=" + toHexString(extraData)).append("\n"); + toStringBuff.append(" nonce=" + toHexString(nonce)).append("\n"); return toStringBuff.toString(); } @@ -286,15 +312,15 @@ public class BlockHeader { toStringBuff.append(" parentHash=" + toHexString(parentHash)).append(""); toStringBuff.append(" unclesHash=" + toHexString(unclesHash)).append(""); toStringBuff.append(" coinbase=" + toHexString(coinbase)).append(""); - toStringBuff.append(" stateRoot=" + toHexString(stateRoot)).append(""); - toStringBuff.append(" txTrieHash=" + toHexString(txTrieRoot)).append(""); - toStringBuff.append(" difficulty=" + toHexString(difficulty)).append(""); - toStringBuff.append(" number=" + number).append(""); - toStringBuff.append(" gasLimit=" + gasLimit).append(""); - toStringBuff.append(" gasUsed=" + gasUsed).append(""); - toStringBuff.append(" timestamp=" + timestamp).append(""); - toStringBuff.append(" extraData=" + toHexString(extraData)).append(""); - toStringBuff.append(" nonce=" + toHexString(nonce)).append(""); + toStringBuff.append(" stateRoot=" + toHexString(stateRoot)).append(""); + toStringBuff.append(" txTrieHash=" + toHexString(txTrieRoot)).append(""); + toStringBuff.append(" difficulty=" + toHexString(difficulty)).append(""); + toStringBuff.append(" number=" + number).append(""); + toStringBuff.append(" gasLimit=" + gasLimit).append(""); + toStringBuff.append(" gasUsed=" + gasUsed).append(""); + toStringBuff.append(" timestamp=" + timestamp).append(""); + toStringBuff.append(" extraData=" + toHexString(extraData)).append(""); + toStringBuff.append(" nonce=" + toHexString(nonce)).append(""); return toStringBuff.toString(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java b/ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java index b7aa6149..d356773e 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java @@ -45,7 +45,7 @@ import static org.ethereum.core.Denomination.SZABO; *
  • Check that the proof of work on the block is valid.
  • *
  • Let S[0] be the STATE_ROOT of the previous block.
  • *
  • Let TX be the block's transaction list, with n transactions. - * For all in in 0...n-1, set S[i+1] = APPLY(S[i],TX[i]). + * For all in in 0...n-1, set S[i+1] = APPLY(S[i],TX[i]). * If any applications returns an error, or if the total gas consumed in the block * up until this point exceeds the GASLIMIT, return an error.
  • *
  • Let S_FINAL be S[n], but adding the block reward paid to the miner.
  • @@ -54,6 +54,7 @@ import static org.ethereum.core.Denomination.SZABO; * See Ethereum Whitepaper * * www.etherJ.com + * * @author Roman Mandeleil, * Nick Savers * Created on: 20/05/2014 10:44 @@ -119,23 +120,23 @@ public class BlockchainImpl implements Blockchain { } @Override - public TransactionReceipt getTransactionReceiptByHash(byte[] hash){ + public TransactionReceipt getTransactionReceiptByHash(byte[] hash) { - return blockStore.getTransactionReceiptByHash(hash); + return blockStore.getTransactionReceiptByHash(hash); } @Override - public Block getBlockByHash(byte[] hash){ + public Block getBlockByHash(byte[] hash) { return blockStore.getBlockByHash(hash); } @Override - public List getListOfHashesStartFrom(byte[] hash, int qty){ + public List getListOfHashesStartFrom(byte[] hash, int qty) { return blockStore.getListOfHashesStartFrom(hash, qty); } - public void tryToConnect(Block block){ + public void tryToConnect(Block block) { recordBlock(block); @@ -144,7 +145,7 @@ public class BlockchainImpl implements Blockchain { Hex.toHexString(block.getHash()).substring(0, 6), block.getNumber()); - if (blockStore.getBlockByHash(block.getHash()) != null){ + if (blockStore.getBlockByHash(block.getHash()) != null) { if (logger.isDebugEnabled()) logger.debug("Block already exist hash: {}, number: {}", @@ -157,12 +158,12 @@ public class BlockchainImpl implements Blockchain { // The simple case got the block // to connect to the main chain - if (bestBlock.isParentOf(block)){ + if (bestBlock.isParentOf(block)) { add(block); return; } - if (!hasParentOnTheChain(block) && block.getNumber() > bestBlock.getNumber()){ + if (!hasParentOnTheChain(block) && block.getNumber() > bestBlock.getNumber()) { logger.info("*** Blockchain will rollback and resynchronise now "); @@ -198,7 +199,7 @@ public class BlockchainImpl implements Blockchain { // keep chain continuity if (!Arrays.equals(getBestBlock().getHash(), - block.getParentHash())) return; + block.getParentHash())) return; if (block.getNumber() >= CONFIG.traceStartBlock() && CONFIG.traceStartBlock() != -1) { AdvancedDeviceUtils.adjustDetailedTracing(block.getNumber()); @@ -221,8 +222,8 @@ public class BlockchainImpl implements Blockchain { listener.onBlock(block); if (blockQueue.size() == 0 && - !syncDoneCalled && - channelManager.isAllSync()){ + !syncDoneCalled && + channelManager.isAllSync()) { logger.info("Sync done"); syncDoneCalled = true; @@ -231,7 +232,7 @@ public class BlockchainImpl implements Blockchain { } - public Block getParent(BlockHeader header){ + public Block getParent(BlockHeader header) { return blockStore.getBlockByHash(header.getParentHash()); } @@ -239,6 +240,7 @@ public class BlockchainImpl implements Blockchain { /** * Calculate GasLimit * See Yellow Paper: http://www.gavwood.com/Paper.pdf - page 5, 4.3.4 (25) + * * @return long value of the gasLimit */ public long calcGasLimit(BlockHeader header) { @@ -272,12 +274,12 @@ public class BlockchainImpl implements Blockchain { * likely next period. Conversely, if the period is too large, the difficulty, * and expected time to the next block, is reduced. */ - private boolean isValid(Block block){ + private boolean isValid(Block block) { boolean isValid = true; if (isValid) return (isValid); // todo get back to the real header validation - if(!block.isGenesis()) { + if (!block.isGenesis()) { isValid = isValid(block.getHeader()); for (BlockHeader uncle : block.getUncleList()) { @@ -291,7 +293,7 @@ public class BlockchainImpl implements Blockchain { isValid = generationGap > 0 && generationGap < 7; } } - if(!isValid) + if (!isValid) logger.warn("WARNING: Invalid - {}", this); return isValid; @@ -300,7 +302,7 @@ public class BlockchainImpl implements Blockchain { private void processBlock(Block block) { List receipts = new ArrayList<>(); - if(isValid(block)) { + if (isValid(block)) { if (!block.isGenesis()) { if (!CONFIG.blockChainOnly()) { wallet.addTransactions(block.getTransactionsList()); @@ -341,9 +343,9 @@ public class BlockchainImpl implements Blockchain { stateLogger.info("[{}] ", receipt.toString()); if (stateLogger.isInfoEnabled()) - stateLogger.info("tx[{}].receipt: [{}] ",i, Hex.toHexString(receipt.getEncoded())); + stateLogger.info("tx[{}].receipt: [{}] ", i, Hex.toHexString(receipt.getEncoded())); - if(block.getNumber() >= CONFIG.traceStartBlock()) + if (block.getNumber() >= CONFIG.traceStartBlock()) repository.dumpState(block, totalGasUsed, i++, tx.getHash()); reciepts.add(receipt); @@ -354,7 +356,7 @@ public class BlockchainImpl implements Blockchain { track.commit(); - if(block.getNumber() >= CONFIG.traceStartBlock()) + if (block.getNumber() >= CONFIG.traceStartBlock()) repository.dumpState(block, totalGasUsed, 0, null); return reciepts; @@ -372,7 +374,7 @@ public class BlockchainImpl implements Blockchain { BigInteger totalBlockReward = Block.BLOCK_REWARD; // Add extra rewards based on number of uncles - if(block.getUncleList().size() > 0) { + if (block.getUncleList().size() > 0) { for (BlockHeader uncle : block.getUncleList()) { track.addBalance(uncle.getCoinbase(), Block.UNCLE_REWARD); } @@ -386,10 +388,10 @@ public class BlockchainImpl implements Blockchain { public void storeBlock(Block block, List receipts) { /* Debug check to see if the state is still as expected */ - if(logger.isWarnEnabled()) { + if (logger.isWarnEnabled()) { String blockStateRootHash = Hex.toHexString(block.getStateRoot()); String worldStateRootHash = Hex.toHexString(repository.getRoot()); - if(!blockStateRootHash.equals(worldStateRootHash)){ + if (!blockStateRootHash.equals(worldStateRootHash)) { stateLogger.info("BLOCK: STATE CONFLICT! block: {} worldstate {} mismatch", block.getNumber(), worldStateRootHash); adminInfo.lostConsensus(); @@ -411,17 +413,17 @@ public class BlockchainImpl implements Blockchain { } - public boolean hasParentOnTheChain(Block block){ + public boolean hasParentOnTheChain(Block block) { return getParent(block.getHeader()) != null; } @Override - public List getAltChains(){ + public List getAltChains() { return altChains; } @Override - public List getGarbage(){ + public List getGarbage() { return garbage; } @@ -442,14 +444,14 @@ public class BlockchainImpl implements Blockchain { } @Override - public void reset(){ + public void reset() { blockStore.reset(); altChains = new ArrayList<>(); garbage = new ArrayList<>(); } @Override - public void close(){ + public void close() { blockQueue.close(); } @@ -468,12 +470,15 @@ public class BlockchainImpl implements Blockchain { this.totalDifficulty = totalDifficulty; } - private void recordBlock(Block block){ + private void recordBlock(Block block) { if (!CONFIG.recordBlocks()) return; - if (bestBlock.isGenesis()){ - try {FileUtils.deleteDirectory(CONFIG.dumpDir());} catch (IOException e) {} + if (bestBlock.isGenesis()) { + try { + FileUtils.deleteDirectory(CONFIG.dumpDir()); + } catch (IOException e) { + } } String dir = CONFIG.dumpDir() + "/"; @@ -490,7 +495,7 @@ public class BlockchainImpl implements Blockchain { fw = new FileWriter(dumpFile.getAbsoluteFile(), true); bw = new BufferedWriter(fw); - if (bestBlock.isGenesis()){ + if (bestBlock.isGenesis()) { bw.write(Hex.toHexString(bestBlock.getEncoded())); bw.write("\n"); } @@ -516,15 +521,15 @@ public class BlockchainImpl implements Blockchain { this.repository = repository; } - public void setProgramInvokeFactory(ProgramInvokeFactory factory){ + public void setProgramInvokeFactory(ProgramInvokeFactory factory) { this.programInvokeFactory = factory; } - public void startTracking(){ + public void startTracking() { track = repository.startTracking(); } - public void commitTracking(){ + public void commitTracking() { track.commit(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/core/Bloom.java b/ethereumj-core/src/main/java/org/ethereum/core/Bloom.java index 81258688..33b25ad1 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Bloom.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Bloom.java @@ -15,14 +15,14 @@ import java.util.Arrays; * http://www.herongyang.com/Java/Bit-String-Set-Bit-to-Byte-Array.html */ -public class Bloom { +public class Bloom { byte[] data = new byte[64]; public Bloom() { } - public Bloom(byte[] data){ + public Bloom(byte[] data) { this.data = data; } @@ -41,8 +41,8 @@ public class Bloom { return bloom; } - public void or(Bloom bloom){ - for (int i = 0; i < data.length; ++i){ + public void or(Bloom bloom) { + for (int i = 0; i < data.length; ++i) { data[i] |= bloom.data[i]; } } diff --git a/ethereumj-core/src/main/java/org/ethereum/core/Chain.java b/ethereumj-core/src/main/java/org/ethereum/core/Chain.java index aee0a1a5..59c56d17 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Chain.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Chain.java @@ -27,7 +27,7 @@ public class Chain { private Map index = new HashMap<>(); - public boolean tryToConnect(Block block){ + public boolean tryToConnect(Block block) { if (chain.isEmpty()) { add(block); @@ -35,14 +35,14 @@ public class Chain { } Block lastBlock = chain.get(chain.size() - 1); - if (lastBlock.isParentOf(block)){ + if (lastBlock.isParentOf(block)) { add(block); return true; } return false; } - public void add(Block block){ + public void add(Block block) { logger.info("adding block to alt chain block.hash: [{}] ", block.getShortHash()); totalDifficulty = totalDifficulty.add(block.getCumulativeDifficulty()); logger.info("total difficulty on alt chain is: [{}] ", totalDifficulty); @@ -50,15 +50,15 @@ public class Chain { index.put(new ByteArrayWrapper(block.getHash()), block); } - public Block get(int i){ + public Block get(int i) { return chain.get(i); } - public Block getLast(){ + public Block getLast() { return chain.get(chain.size() - 1); } - public BigInteger getTotalDifficulty(){ + public BigInteger getTotalDifficulty() { return totalDifficulty; } @@ -66,11 +66,11 @@ public class Chain { this.totalDifficulty = totalDifficulty; } - public boolean isParentOnTheChain(Block block){ - return (index.get(new ByteArrayWrapper( block.getParentHash() )) != null); + public boolean isParentOnTheChain(Block block) { + return (index.get(new ByteArrayWrapper(block.getParentHash())) != null); } - public long getSize(){ + public long getSize() { return chain.size(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/core/Genesis.java b/ethereumj-core/src/main/java/org/ethereum/core/Genesis.java index df505e41..a3f677b6 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Genesis.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Genesis.java @@ -30,7 +30,7 @@ public class Genesis extends Block { public final static BigInteger PREMINE_AMOUNT = BigInteger.valueOf(2).pow(200); - private static String[] premine = new String[] { + private static String[] premine = new String[]{ "51ba59315b3a95761d0863b05ccc7a7f54703d99", "e6716f9544a56c530d868e4bfbacb172315bdead", // # (J) "b9c015918bdaba24b4ff057a92a3873d6eb201be", // # (V) @@ -50,10 +50,10 @@ public class Genesis extends Block { public static byte[] COINBASE = zeroHash160; public static byte[] LOG_BLOOM = zeroHash512; public static byte[] DIFFICULTY = BigInteger.valueOf(2).pow(17).toByteArray(); - public static long NUMBER = 0; - public static long GAS_LIMIT = 1000000; - public static long GAS_USED = 0; - public static long TIMESTAMP = 0; + public static long NUMBER = 0; + public static long GAS_LIMIT = 1000000; + public static long GAS_USED = 0; + public static long TIMESTAMP = 0; public static byte[] EXTRA_DATA = new byte[0]; public static byte[] NONCE = sha3(new byte[]{42}); diff --git a/ethereumj-core/src/main/java/org/ethereum/core/Transaction.java b/ethereumj-core/src/main/java/org/ethereum/core/Transaction.java index d57cbc32..af887438 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Transaction.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Transaction.java @@ -10,6 +10,7 @@ import org.ethereum.util.RLPList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.BigIntegers; + import java.security.SignatureException; import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; @@ -86,7 +87,7 @@ public class Transaction { this.value = value; this.data = data; - if(receiveAddress == null) { + if (receiveAddress == null) { this.receiveAddress = ByteUtil.EMPTY_BYTE_ARRAY; } @@ -97,25 +98,25 @@ public class Transaction { public void rlpParse() { RLPList decodedTxList = RLP.decode2(rlpEncoded); - RLPList transaction = (RLPList) decodedTxList.get(0); + RLPList transaction = (RLPList) decodedTxList.get(0); - this.nonce = transaction.get(0).getRLPData(); - this.gasPrice = transaction.get(1).getRLPData(); - this.gasLimit = transaction.get(2).getRLPData(); + this.nonce = transaction.get(0).getRLPData(); + this.gasPrice = transaction.get(1).getRLPData(); + this.gasLimit = transaction.get(2).getRLPData(); this.receiveAddress = transaction.get(3).getRLPData(); - this.value = transaction.get(4).getRLPData(); - this.data = transaction.get(5).getRLPData(); + this.value = transaction.get(4).getRLPData(); + this.data = transaction.get(5).getRLPData(); // only parse signature in case tx is signed - if(transaction.get(6).getRLPData() != null) { - byte v = transaction.get(6).getRLPData()[0]; - byte[] r = transaction.get(7).getRLPData(); - byte[] s = transaction.get(8).getRLPData(); + if (transaction.get(6).getRLPData() != null) { + byte v = transaction.get(6).getRLPData()[0]; + byte[] r = transaction.get(7).getRLPData(); + byte[] s = transaction.get(8).getRLPData(); this.signature = ECDSASignature.fromComponents(r, s, v); } else { logger.debug("RLP encoded tx is not signed!"); } this.parsed = true; - this.hash = getHash(); + this.hash = getHash(); } public boolean isParsed() { @@ -158,7 +159,7 @@ public class Transaction { public byte[] getGasPrice() { if (!parsed) rlpParse(); - return gasPrice== null ? ZERO_BYTE_ARRAY : gasPrice; + return gasPrice == null ? ZERO_BYTE_ARRAY : gasPrice; } public byte[] getGasLimit() { @@ -166,7 +167,7 @@ public class Transaction { return gasLimit; } - public long nonZeroDataBytes(){ + public long nonZeroDataBytes() { if (data == null) return 0; int counter = 0; for (final byte aData : data) { @@ -175,7 +176,7 @@ public class Transaction { return counter; } - public long zeroDataBytes(){ + public long zeroDataBytes() { if (data == null) return 0; int counter = 0; for (final byte aData : data) { @@ -237,7 +238,7 @@ public class Transaction { @Override public String toString() { if (!parsed) rlpParse(); - return "TransactionData [" + "hash=" + ByteUtil.toHexString(hash) + + return "TransactionData [" + "hash=" + ByteUtil.toHexString(hash) + " nonce=" + ByteUtil.toHexString(nonce) + ", gasPrice=" + ByteUtil.toHexString(gasPrice) + ", gas=" + ByteUtil.toHexString(gasLimit) + @@ -251,8 +252,8 @@ public class Transaction { } /** - * For signatures you have to keep also - * RLP of the transaction without any signature data + * For signatures you have to keep also + * RLP of the transaction without any signature data */ public byte[] getEncodedRaw() { @@ -261,16 +262,16 @@ public class Transaction { // parse null as 0 for nonce byte[] nonce = null; - if ( this.nonce == null || this.nonce.length == 1 && this.nonce[0] == 0){ - nonce = RLP.encodeElement(null); + if (this.nonce == null || this.nonce.length == 1 && this.nonce[0] == 0) { + nonce = RLP.encodeElement(null); } else { - nonce = RLP.encodeElement(this.nonce); + nonce = RLP.encodeElement(this.nonce); } - byte[] gasPrice = RLP.encodeElement(this.gasPrice); - byte[] gasLimit = RLP.encodeElement(this.gasLimit); - byte[] receiveAddress = RLP.encodeElement(this.receiveAddress); - byte[] value = RLP.encodeElement(this.value); - byte[] data = RLP.encodeElement(this.data); + byte[] gasPrice = RLP.encodeElement(this.gasPrice); + byte[] gasLimit = RLP.encodeElement(this.gasLimit); + byte[] receiveAddress = RLP.encodeElement(this.receiveAddress); + byte[] value = RLP.encodeElement(this.value); + byte[] data = RLP.encodeElement(this.data); rlpRaw = RLP.encodeList(nonce, gasPrice, gasLimit, receiveAddress, value, data); @@ -279,25 +280,25 @@ public class Transaction { public byte[] getEncoded() { - if(rlpEncoded != null) return rlpEncoded; + if (rlpEncoded != null) return rlpEncoded; // parse null as 0 for nonce byte[] nonce = null; - if (this.nonce == null || this.nonce.length == 1 && this.nonce[0] == 0){ - nonce = RLP.encodeElement(null); + if (this.nonce == null || this.nonce.length == 1 && this.nonce[0] == 0) { + nonce = RLP.encodeElement(null); } else { - nonce = RLP.encodeElement(this.nonce); + nonce = RLP.encodeElement(this.nonce); } - byte[] gasPrice = RLP.encodeElement(this.gasPrice); - byte[] gasLimit = RLP.encodeElement(this.gasLimit); - byte[] receiveAddress = RLP.encodeElement(this.receiveAddress); - byte[] value = RLP.encodeElement(this.value); - byte[] data = RLP.encodeElement(this.data); + byte[] gasPrice = RLP.encodeElement(this.gasPrice); + byte[] gasLimit = RLP.encodeElement(this.gasLimit); + byte[] receiveAddress = RLP.encodeElement(this.receiveAddress); + byte[] value = RLP.encodeElement(this.value); + byte[] data = RLP.encodeElement(this.data); byte[] v, r, s; - if(signature != null) { - v = RLP.encodeByte( signature.v ); + if (signature != null) { + v = RLP.encodeByte(signature.v); r = RLP.encodeElement(BigIntegers.asUnsignedByteArray(signature.r)); s = RLP.encodeElement(BigIntegers.asUnsignedByteArray(signature.s)); } else { @@ -309,7 +310,7 @@ public class Transaction { this.rlpEncoded = RLP.encodeList(nonce, gasPrice, gasLimit, receiveAddress, value, data, v, r, s); - this.hash = this.getHash(); + this.hash = this.getHash(); return rlpEncoded; } @@ -331,7 +332,7 @@ public class Transaction { public boolean equals(Object obj) { if (!(obj instanceof Transaction)) return false; - Transaction tx = (Transaction)obj; + Transaction tx = (Transaction) obj; return tx.hashCode() == this.hashCode(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/core/TransactionExecutor.java b/ethereumj-core/src/main/java/org/ethereum/core/TransactionExecutor.java index ca77fcc7..38bc64fa 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/TransactionExecutor.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/TransactionExecutor.java @@ -38,7 +38,7 @@ public class TransactionExecutor { ProgramInvokeFactory programInvokeFactory, Block currentBlock) { this.tx = tx; - this.coinbase = coinbase; + this.coinbase = coinbase; this.track = track; this.programInvokeFactory = programInvokeFactory; this.currentBlock = currentBlock; @@ -53,7 +53,7 @@ public class TransactionExecutor { // https://github.com/ethereum/cpp-ethereum/blob/develop/libethereum/Executive.cpp#L55 - public void execute(){ + public void execute() { logger.info("applyTransaction: [{}]", Hex.toHexString(tx.getHash())); @@ -166,8 +166,8 @@ public class TransactionExecutor { try { // CREATE NEW CONTRACT ADDRESS AND ADD TX VALUE - if(isContractCreation) { - if(stateLogger.isDebugEnabled()) + if (isContractCreation) { + if (stateLogger.isDebugEnabled()) stateLogger.debug("new contract created address={}", Hex.toHexString(receiverAddress)); } @@ -199,9 +199,9 @@ public class TransactionExecutor { trackTx.commit(); } else { // REFUND GASDEBIT EXCEPT FOR FEE (500 + 5*TX_NO_ZERO_DATA) - long dataCost = tx.getData() == null ? 0: + long dataCost = tx.getData() == null ? 0 : tx.nonZeroDataBytes() * GasCost.TX_NO_ZERO_DATA + - tx.zeroDataBytes() * GasCost.TX_ZERO_DATA; + tx.zeroDataBytes() * GasCost.TX_ZERO_DATA; gasUsed = GasCost.TRANSACTION + dataCost; BigInteger refund = gasDebit.subtract(BigInteger.valueOf(gasUsed).multiply(gasPrice)); @@ -253,7 +253,7 @@ public class TransactionExecutor { repository.addBalance(coinbase, refund.negate()); } - if (result.getFutureRefund() > 0){ + if (result.getFutureRefund() > 0) { long futureRefund = Math.min(result.getFutureRefund(), result.getGasUsed() / 2); BigInteger futureRefundBI = BigInteger.valueOf(futureRefund); @@ -284,11 +284,12 @@ public class TransactionExecutor { Hex.toHexString(contractAddress), Hex.toHexString(bodyCode)); - BigInteger storageCost = gasPrice.multiply( BigInteger.valueOf( bodyCode.length * GasCost.CREATE_DATA_BYTE) ); + BigInteger storageCost = gasPrice.multiply(BigInteger.valueOf(bodyCode.length * GasCost + .CREATE_DATA_BYTE)); BigInteger balance = repository.getBalance(senderAddress); // check if can be charged for the contract data save - if (storageCost.compareTo(balance) > 1){ + if (storageCost.compareTo(balance) > 1) { bodyCode = EMPTY_BYTE_ARRAY; } else { repository.addBalance(coinbase, storageCost); @@ -301,7 +302,7 @@ public class TransactionExecutor { // delete the marked to die accounts if (result.getDeleteAccounts() == null) return; - for (DataWord address : result.getDeleteAccounts()){ + for (DataWord address : result.getDeleteAccounts()) { repository.delete(address.getNoLeadZeroesData()); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/core/TransactionReceipt.java b/ethereumj-core/src/main/java/org/ethereum/core/TransactionReceipt.java index a88f58f2..92d47f3a 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/TransactionReceipt.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/TransactionReceipt.java @@ -17,8 +17,6 @@ import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; * comprising the transaction, together with the post-transaction state, * and the cumulative gas used in the block containing the transaction receipt * as of immediately after the transaction has happened, - * - * */ public class TransactionReceipt { @@ -26,7 +24,7 @@ public class TransactionReceipt { private byte[] postTxState = EMPTY_BYTE_ARRAY; private byte[] cumulativeGas = EMPTY_BYTE_ARRAY; - private Bloom bloomFilter = new Bloom(); + private Bloom bloomFilter = new Bloom(); private List logInfoList = new ArrayList(); /* Tx Receipt in encoded form */ @@ -40,10 +38,10 @@ public class TransactionReceipt { RLPList params = RLP.decode2(rlp); RLPList receipt = (RLPList) params.get(0); - RLPItem postTxStateRLP = (RLPItem) receipt.get(0); + RLPItem postTxStateRLP = (RLPItem) receipt.get(0); RLPItem cumulativeGasRLP = (RLPItem) receipt.get(1); - RLPItem bloomRLP = (RLPItem) receipt.get(2); - RLPList logs = (RLPList) receipt.get(3); + RLPItem bloomRLP = (RLPItem) receipt.get(2); + RLPList logs = (RLPList) receipt.get(3); postTxState = postTxStateRLP.getRLPData(); cumulativeGas = cumulativeGasRLP.getRLPData(); @@ -92,11 +90,11 @@ public class TransactionReceipt { /* [postTxState, cumulativeGas, bloomFilter, logInfoList] */ public byte[] getEncoded() { - if(rlpEncoded != null) return rlpEncoded; + if (rlpEncoded != null) return rlpEncoded; - byte[] postTxStateRLP = RLP.encodeElement(this.postTxState); + byte[] postTxStateRLP = RLP.encodeElement(this.postTxState); byte[] cumulativeGasRLP = RLP.encodeElement(this.cumulativeGas); - byte[] bloomRLP = RLP.encodeElement(this.bloomFilter.data); + byte[] bloomRLP = RLP.encodeElement(this.bloomFilter.data); byte[] logInfoListRLP = null; if (logInfoList != null) { @@ -104,11 +102,11 @@ public class TransactionReceipt { int i = 0; for (LogInfo logInfo : logInfoList) { - logInfoListE[i] = logInfo.getEncoded() ; + logInfoListE[i] = logInfo.getEncoded(); ++i; } logInfoListRLP = RLP.encodeList(logInfoListE); - } else{ + } else { logInfoListRLP = RLP.encodeList(); } @@ -122,7 +120,7 @@ public class TransactionReceipt { } public void setCumulativeGas(long cumulativeGas) { - this.cumulativeGas = BigIntegers.asUnsignedByteArray( BigInteger.valueOf( cumulativeGas ) ); + this.cumulativeGas = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(cumulativeGas)); } public void setCumulativeGas(byte[] cumulativeGas) { @@ -135,16 +133,16 @@ public class TransactionReceipt { this.rlpEncoded = null; this.logInfoList = logInfoList; - for (LogInfo loginfo : logInfoList){ + for (LogInfo loginfo : logInfoList) { bloomFilter.or(loginfo.getBloom()); } } - public void setTransaction(Transaction transaction){ + public void setTransaction(Transaction transaction) { this.transaction = transaction; } - public Transaction getTransaction(){ + public Transaction getTransaction() { return transaction; } diff --git a/ethereumj-core/src/main/java/org/ethereum/core/Wallet.java b/ethereumj-core/src/main/java/org/ethereum/core/Wallet.java index 8381a8e8..5fe1c3c5 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Wallet.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Wallet.java @@ -110,7 +110,7 @@ public class Wallet { * @param transaction * @return */ - public WalletTransaction addByWalletTransaction(Transaction transaction){ + public WalletTransaction addByWalletTransaction(Transaction transaction) { String hash = Hex.toHexString(transaction.getHash()); WalletTransaction walletTransaction = new WalletTransaction(transaction); this.walletTransactions.put(hash, walletTransaction); @@ -127,9 +127,9 @@ public class Wallet { */ public WalletTransaction addTransaction(Transaction transaction) { String hash = Hex.toHexString(transaction.getHash()); - logger.info("pending transaction placed hash: {}", hash ); + logger.info("pending transaction placed hash: {}", hash); - WalletTransaction walletTransaction = this.walletTransactions.get(hash); + WalletTransaction walletTransaction = this.walletTransactions.get(hash); if (walletTransaction != null) walletTransaction.incApproved(); else { @@ -158,7 +158,7 @@ public class Wallet { public void removeTransaction(Transaction transaction) { String hash = Hex.toHexString(transaction.getHash()); - logger.info("pending transaction removed with hash: {} ", hash); + logger.info("pending transaction removed with hash: {} ", hash); walletTransactions.remove(hash); } @@ -167,7 +167,7 @@ public class Wallet { transactionMap.put(new ByteArrayWrapper(transaction.getHash()), transaction); byte[] senderAddress = transaction.getSender(); - Account sender = rows.get(Hex.toHexString(senderAddress)); + Account sender = rows.get(Hex.toHexString(senderAddress)); if (sender != null) { sender.addPendingTransaction(transaction); @@ -178,8 +178,8 @@ public class Wallet { } byte[] receiveAddress = transaction.getReceiveAddress(); - if(receiveAddress != null) { - Account receiver = rows.get(Hex.toHexString(receiveAddress)); + if (receiveAddress != null) { + Account receiver = rows.get(Hex.toHexString(receiveAddress)); if (receiver != null) { receiver.addPendingTransaction(transaction); @@ -195,7 +195,7 @@ public class Wallet { public void processBlock(Block block) { - for (Account account : getAccountCollection()){ + for (Account account : getAccountCollection()) { account.clearAllPendingTransactions(); } @@ -237,11 +237,11 @@ public class Wallet { NodeList rowNodes = walletNode.getChildNodes(); - for (int i = 0; i < rowNodes.getLength(); ++i ) { + for (int i = 0; i < rowNodes.getLength(); ++i) { - Node rowNode = rowNodes.item(i); - Node addrNode = rowNode.getChildNodes().item(0); - Node privNode = rowNode.getChildNodes().item(1); + Node rowNode = rowNodes.item(i); + Node addrNode = rowNode.getChildNodes().item(0); + Node privNode = rowNode.getChildNodes().item(1); Node valueNode = rowNode.getChildNodes().item(2); // TODO: complete load func @@ -287,11 +287,11 @@ public class Wallet { doc.appendChild(walletElement); Attr high = doc.createAttribute("high"); - high.setValue(Long.toString( this.high )); + high.setValue(Long.toString(this.high)); walletElement.setAttributeNode(high); int i = 0; - for (Account account : getAccountCollection()) { + for (Account account : getAccountCollection()) { Element raw = doc.createElement("raw"); Attr id = doc.createAttribute("id"); @@ -308,7 +308,7 @@ public class Wallet { Element privKey = doc.createElement("privkey"); privKey.setTextContent(Hex.toHexString(account.getEcKey().getPrivKeyBytes())); - Element value = doc.createElement("value"); + Element value = doc.createElement("value"); value.setTextContent(account.getBalance().toString()); raw.appendChild(addressE); @@ -334,7 +334,7 @@ public class Wallet { listener.valueChanged(); } - public interface WalletListener{ + public interface WalletListener { public void valueChanged(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/crypto/ECKey.java b/ethereumj-core/src/main/java/org/ethereum/crypto/ECKey.java index 43937be9..69474452 100644 --- a/ethereumj-core/src/main/java/org/ethereum/crypto/ECKey.java +++ b/ethereumj-core/src/main/java/org/ethereum/crypto/ECKey.java @@ -14,6 +14,7 @@ package org.ethereum.crypto; * See the License for the specific language governing permissions and * limitations under the License. */ + import static org.ethereum.util.ByteUtil.bigIntegerToBytes; import java.io.Serializable; @@ -66,12 +67,15 @@ import org.spongycastle.util.encoders.Hex; * can usually ignore the compressed/uncompressed distinction.

    * * This code is borrowed from the bitcoinj project and altered to fit Ethereum.
    - * See bitcoinj on GitHub + * See bitcoinj on GitHub */ public class ECKey implements Serializable { private static final Logger logger = LoggerFactory.getLogger(ECKey.class); - /** The parameters of the secp256k1 curve that Ethereum uses. */ + /** + * The parameters of the secp256k1 curve that Ethereum uses. + */ public static final ECDomainParameters CURVE; /** @@ -125,7 +129,7 @@ public class ECKey implements Serializable { public ECKey(@Nullable BigInteger priv, ECPoint pub) { this.priv = priv; - if(pub == null) + if (pub == null) throw new IllegalArgumentException("Public key may not be null"); this.pub = pub; } @@ -234,7 +238,9 @@ public class ECKey implements Serializable { return point.getEncoded(compressed); } - /** Gets the hash160 form of the public key (as seen in addresses). */ + /** + * Gets the hash160 form of the public key (as seen in addresses). + */ public byte[] getAddress() { if (pubKeyHash == null) { byte[] pubBytes = this.pub.getEncoded(false); @@ -251,7 +257,9 @@ public class ECKey implements Serializable { return pub.getEncoded(); } - /** Gets the public key in the form of an elliptic curve point object from Bouncy Castle. */ + /** + * Gets the public key in the form of an elliptic curve point object from Bouncy Castle. + */ public ECPoint getPubKeyPoint() { return pub; } @@ -300,7 +308,9 @@ public class ECKey implements Serializable { * components can be useful for doing further EC maths on them. */ public static class ECDSASignature { - /** The two components of the signature. */ + /** + * The two components of the signature. + */ public final BigInteger r, s; public byte v; @@ -460,9 +470,9 @@ public class ECKey implements Serializable { *

    When using native ECDSA verification, data must be 32 bytes, and no element may be * larger than 520 bytes.

    * - * @param data Hash of the data to verify. + * @param data Hash of the data to verify. * @param signature signature. - * @param pub The public key bytes to use. + * @param pub The public key bytes to use. */ public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) { ECDSASigner signer = new ECDSASigner(); @@ -481,9 +491,9 @@ public class ECKey implements Serializable { /** * Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key. * - * @param data Hash of the data to verify. + * @param data Hash of the data to verify. * @param signature signature. - * @param pub The public key bytes to use. + * @param pub The public key bytes to use. */ public static boolean verify(byte[] data, byte[] signature, byte[] pub) { return verify(data, signature, pub); @@ -492,7 +502,7 @@ public class ECKey implements Serializable { /** * Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key. * - * @param data Hash of the data to verify. + * @param data Hash of the data to verify. * @param signature signature. */ public boolean verify(byte[] data, byte[] signature) { @@ -601,11 +611,13 @@ public class ECKey implements Serializable { return ECKey.fromPublicOnly(q.getEncoded(compressed)); } - /** Decompress a compressed public key (x co-ord and low-bit of y-coord). */ + /** + * Decompress a compressed public key (x co-ord and low-bit of y-coord). + */ private static ECPoint decompressKey(BigInteger xBN, boolean yBit) { X9IntegerConverter x9 = new X9IntegerConverter(); byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE.getCurve())); - compEnc[0] = (byte)(yBit ? 0x03 : 0x02); + compEnc[0] = (byte) (yBit ? 0x03 : 0x02); return CURVE.getCurve().decodePoint(compEnc); } @@ -643,6 +655,6 @@ public class ECKey implements Serializable { } private static void check(boolean test, String message) { - if(!test) throw new IllegalArgumentException(message); + if (!test) throw new IllegalArgumentException(message); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/crypto/HashUtil.java b/ethereumj-core/src/main/java/org/ethereum/crypto/HashUtil.java index f0e6657c..f6f48ae0 100644 --- a/ethereumj-core/src/main/java/org/ethereum/crypto/HashUtil.java +++ b/ethereumj-core/src/main/java/org/ethereum/crypto/HashUtil.java @@ -41,7 +41,7 @@ public class HashUtil { public static byte[] sha3(byte[] input) { ByteArrayWrapper inputByteArray = new ByteArrayWrapper(input); byte[] result = sha3Cache.get(inputByteArray); - if(result != null) + if (result != null) return result; result = SHA3Helper.sha3(input); sha3Cache.put(inputByteArray, result); @@ -71,7 +71,7 @@ public class HashUtil { /** * The way to calculate new address inside ethereum * - * @param addr - creating addres + * @param addr - creating addres * @param nonce - nonce of creating address * @return new address */ diff --git a/ethereumj-core/src/main/java/org/ethereum/db/BlockStore.java b/ethereumj-core/src/main/java/org/ethereum/db/BlockStore.java index 15829b98..ab428faa 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/BlockStore.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/BlockStore.java @@ -20,7 +20,7 @@ import java.util.List; * Created on: 12/11/2014 17:16 */ @Repository -@Transactional(propagation= Propagation.SUPPORTS) +@Transactional(propagation = Propagation.SUPPORTS) public class BlockStore { @Autowired @@ -35,10 +35,10 @@ public class BlockStore { List result = sessionFactory.getCurrentSession(). createQuery("from BlockVO where number = :number"). - setParameter("number", blockNumber).list(); + setParameter("number", blockNumber).list(); if (result.size() == 0) return null; - BlockVO vo = (BlockVO)result.get(0); + BlockVO vo = (BlockVO) result.get(0); return new Block(vo.rlp); } @@ -51,7 +51,7 @@ public class BlockStore { setParameter("hash", hash).list(); if (result.size() == 0) return null; - BlockVO vo = (BlockVO)result.get(0); + BlockVO vo = (BlockVO) result.get(0); return new Block(vo.rlp); } @@ -72,7 +72,7 @@ public class BlockStore { setParameter("limit", block.getNumber() - qty). setMaxResults(qty).list(); - for (byte[] h : result){ + for (byte[] h : result) { hashes.add(h); } @@ -80,7 +80,7 @@ public class BlockStore { } @Transactional - public void deleteBlocksSince(long number){ + public void deleteBlocksSince(long number) { sessionFactory.getCurrentSession(). createQuery("delete from BlockVO where number > :number"). @@ -92,10 +92,10 @@ public class BlockStore { @Transactional public void saveBlock(Block block, List receipts) { - BlockVO blockVO = new BlockVO(block.getNumber(), block.getHash(), + BlockVO blockVO = new BlockVO(block.getNumber(), block.getHash(), block.getEncoded(), block.getCumulativeDifficulty()); - for (TransactionReceipt receipt : receipts){ + for (TransactionReceipt receipt : receipts) { byte[] hash = receipt.getTransaction().getHash(); byte[] rlp = receipt.getEncoded(); @@ -108,9 +108,9 @@ public class BlockStore { } @Transactional(readOnly = true) - public BigInteger getTotalDifficultySince(long number){ + public BigInteger getTotalDifficultySince(long number) { - BigInteger result = (BigInteger)sessionFactory.getCurrentSession(). + BigInteger result = (BigInteger) sessionFactory.getCurrentSession(). createQuery("select sum(cummulativeDifficulty) from BlockVO where number > :number"). setParameter("number", number). uniqueResult(); @@ -120,9 +120,9 @@ public class BlockStore { @Transactional(readOnly = true) - public BigInteger getTotalDifficulty(){ + public BigInteger getTotalDifficulty() { - BigInteger result = (BigInteger)sessionFactory.getCurrentSession(). + BigInteger result = (BigInteger) sessionFactory.getCurrentSession(). createQuery("select sum(cummulativeDifficulty) from BlockVO").uniqueResult(); return result; @@ -130,15 +130,15 @@ public class BlockStore { @Transactional(readOnly = true) - public Block getBestBlock(){ + public Block getBestBlock() { Long bestNumber = (Long) sessionFactory.getCurrentSession().createQuery("select max(number) from BlockVO").uniqueResult(); List result = sessionFactory.getCurrentSession(). - createQuery("from BlockVO where number = :number").setParameter("number", bestNumber) .list(); + createQuery("from BlockVO where number = :number").setParameter("number", bestNumber).list(); if (result.isEmpty()) return null; - BlockVO vo = (BlockVO)result.get(0); + BlockVO vo = (BlockVO) result.get(0); return new Block(vo.rlp); } @@ -151,7 +151,7 @@ public class BlockStore { createQuery("from BlockVO").list(); ArrayList blocks = new ArrayList<>(); - for (BlockVO blockVO : (List)result){ + for (BlockVO blockVO : (List) result) { blocks.add(new Block(blockVO.getRlp())); } @@ -161,7 +161,7 @@ public class BlockStore { @Transactional public void reset() { sessionFactory.getCurrentSession(). - createQuery("delete from BlockVO").executeUpdate(); + createQuery("delete from BlockVO").executeUpdate(); } public TransactionReceipt getTransactionReceiptByHash(byte[] hash) { @@ -171,7 +171,7 @@ public class BlockStore { setParameter("hash", hash).list(); if (result.size() == 0) return null; - TransactionReceiptVO vo = (TransactionReceiptVO)result.get(0); + TransactionReceiptVO vo = (TransactionReceiptVO) result.get(0); return new TransactionReceipt(vo.rlp); diff --git a/ethereumj-core/src/main/java/org/ethereum/db/BlockVO.java b/ethereumj-core/src/main/java/org/ethereum/db/BlockVO.java index 0070a4c7..3a255922 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/BlockVO.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/BlockVO.java @@ -19,7 +19,7 @@ public class BlockVO { @Id byte[] hash; - Long number; + Long number; @Lob byte[] rlp; @@ -31,8 +31,8 @@ public class BlockVO { public BlockVO(Long number, byte[] hash, byte[] rlp, BigInteger cummulativeDifficulty) { this.number = number; - this.hash = hash; - this.rlp = rlp; + this.hash = hash; + this.rlp = rlp; this.cummulativeDifficulty = cummulativeDifficulty; } diff --git a/ethereumj-core/src/main/java/org/ethereum/db/ContractDetails.java b/ethereumj-core/src/main/java/org/ethereum/db/ContractDetails.java index f0194438..c8f33f2e 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/ContractDetails.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/ContractDetails.java @@ -20,12 +20,12 @@ public class ContractDetails { private byte[] rlpEncoded; - private List storageKeys = new ArrayList<>(); + private List storageKeys = new ArrayList<>(); private List storageValues = new ArrayList<>(); private byte[] code = ByteUtil.EMPTY_BYTE_ARRAY; - private boolean dirty = false; + private boolean dirty = false; private boolean deleted = false; private Trie storageTrie = new TrieImpl(null); @@ -75,8 +75,7 @@ public class ContractDetails { if (foundIndex != -1) { DataWord value = storageValues.get(foundIndex); return value.clone(); - } - else + } else return null; } @@ -94,7 +93,7 @@ public class ContractDetails { storageTrie = new TrieImpl(null); // calc the trie for root hash - for (int i = 0; i < storageKeys.size(); ++i){ + for (int i = 0; i < storageKeys.size(); ++i) { storageTrie.update(storageKeys.get(i).getData(), RLP .encodeElement(storageValues.get(i).getNoLeadZeroesData())); } @@ -197,7 +196,7 @@ public class ContractDetails { keys.addAll(storageKeys); List values = new ArrayList<>(); - for (DataWord key : keys){ + for (DataWord key : keys) { DataWord value = storage.get(key); values.add(value); @@ -208,18 +207,17 @@ public class ContractDetails { } - - public ContractDetails clone(){ + public ContractDetails clone() { ContractDetails contractDetails = new ContractDetails(); contractDetails.setCode(this.getCode()); - contractDetails.setStorage(new ArrayList(this.storageKeys) , - new ArrayList(this.storageValues)); + contractDetails.setStorage(new ArrayList(this.storageKeys), + new ArrayList(this.storageValues)); return contractDetails; } - public String toString(){ + public String toString() { String ret = " Code: " + Hex.toHexString(code) + "\n"; ret += " Storage: " + getStorage().toString(); diff --git a/ethereumj-core/src/main/java/org/ethereum/db/DatabaseImpl.java b/ethereumj-core/src/main/java/org/ethereum/db/DatabaseImpl.java index 74663e45..5909872b 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/DatabaseImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/DatabaseImpl.java @@ -18,12 +18,12 @@ import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; /** - * Generic interface for Ethereum database + * Generic interface for Ethereum database * - * LevelDB key/value pair DB implementation will be used. - * Choice must be made between: - * Pure Java: https://github.com/dain/leveldb - * JNI binding: https://github.com/fusesource/leveldbjni + * LevelDB key/value pair DB implementation will be used. + * Choice must be made between: + * Pure Java: https://github.com/dain/leveldb + * JNI binding: https://github.com/fusesource/leveldbjni */ public class DatabaseImpl implements Database { @@ -40,10 +40,10 @@ public class DatabaseImpl implements Database { try { logger.debug("Opening database"); File dbLocation = new File(System.getProperty("user.dir") + "/" + - SystemProperties.CONFIG.databaseDir() + "/"); + SystemProperties.CONFIG.databaseDir() + "/"); File fileLocation = new File(dbLocation, name); - if(SystemProperties.CONFIG.databaseReset()) { + if (SystemProperties.CONFIG.databaseReset()) { destroyDB(fileLocation); } @@ -53,13 +53,13 @@ public class DatabaseImpl implements Database { // String stats = DATABASE.getProperty("leveldb.stats"); // logger.debug(stats); - if (logger.isTraceEnabled()){ + if (logger.isTraceEnabled()) { logger.trace("Dump for: {}", fileLocation.toString()); - DBIterator iter = db.iterator(); + DBIterator iter = db.iterator(); - while(iter.hasNext()){ - byte[] key = iter.peekNext().getKey(); + while (iter.hasNext()) { + byte[] key = iter.peekNext().getKey(); byte[] value = iter.peekNext().getValue(); logger.trace("key={}, value={}", Hex.toHexString(key), Hex.toHexString(value)); @@ -90,7 +90,7 @@ public class DatabaseImpl implements Database { @Override public void put(byte[] key, byte[] value) { - if(logger.isDebugEnabled()) + if (logger.isDebugEnabled()) logger.debug("put: key: [{}], value: [{}]", Hex.toHexString(key), Hex.toHexString(value)); @@ -99,7 +99,7 @@ public class DatabaseImpl implements Database { @Override public void delete(byte[] key) { - if(logger.isDebugEnabled()) + if (logger.isDebugEnabled()) logger.debug("delete: key: [{}]"); db.delete(key); diff --git a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryDummy.java b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryDummy.java index 51427e8e..b2eeb9d7 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryDummy.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryDummy.java @@ -41,7 +41,7 @@ public class RepositoryDummy implements Repository { private static final Logger logger = LoggerFactory.getLogger("repository"); private Map worldState = new HashMap<>(); - private Map detailsDB = new HashMap<>() ; + private Map detailsDB = new HashMap<>(); @Override @@ -53,12 +53,12 @@ public class RepositoryDummy implements Repository { @Override public void close() { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } @Override public boolean isClosed() { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } @@ -71,21 +71,21 @@ public class RepositoryDummy implements Repository { AccountState accountState = stateCache.get(hash); ContractDetails contractDetails = detailsCache.get(hash); - if (accountState.isDeleted()){ - worldState.remove( hash ) ; - detailsDB.remove( hash ); + if (accountState.isDeleted()) { + worldState.remove(hash); + detailsDB.remove(hash); logger.debug("delete: [{}]", Hex.toHexString(hash.getData())); - } else{ + } else { - if (accountState.isDirty() || contractDetails.isDirty()){ - detailsDB.put( hash, contractDetails); + if (accountState.isDirty() || contractDetails.isDirty()) { + detailsDB.put(hash, contractDetails); accountState.setStateRoot(contractDetails.getStorageHash()); accountState.setCodeHash(sha3(contractDetails.getCode())); - worldState.put( hash, accountState); - if (logger.isDebugEnabled()){ + worldState.put(hash, accountState); + if (logger.isDebugEnabled()) { logger.debug("update: [{}],nonce: [{}] balance: [{}] \n [{}]", Hex.toHexString(hash.getData()), accountState.getNonce(), @@ -106,23 +106,23 @@ public class RepositoryDummy implements Repository { @Override public void flush() { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } @Override public void rollback() { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } @Override public void commit() { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } @Override public void syncToRoot(byte[] root) { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } @Override @@ -140,7 +140,7 @@ public class RepositoryDummy implements Repository { return null; } - public Set getFullAddressSet(){ + public Set getFullAddressSet() { return worldState.keySet(); } @@ -170,7 +170,7 @@ public class RepositoryDummy implements Repository { @Override public DataWord getStorageValue(byte[] addr, DataWord key) { - ContractDetails details = getContractDetails(addr); + ContractDetails details = getContractDetails(addr); if (details == null) return null; @@ -180,11 +180,11 @@ public class RepositoryDummy implements Repository { @Override public void addStorageRow(byte[] addr, DataWord key, DataWord value) { - ContractDetails details = getContractDetails(addr); + ContractDetails details = getContractDetails(addr); - if (details == null){ + if (details == null) { createAccount(addr); - details = getContractDetails(addr); + details = getContractDetails(addr); } details.put(key, value); @@ -193,7 +193,7 @@ public class RepositoryDummy implements Repository { @Override public byte[] getCode(byte[] addr) { - ContractDetails details = getContractDetails(addr); + ContractDetails details = getContractDetails(addr); if (details == null) return null; @@ -204,15 +204,15 @@ public class RepositoryDummy implements Repository { @Override public void saveCode(byte[] addr, byte[] code) { - ContractDetails details = getContractDetails(addr); + ContractDetails details = getContractDetails(addr); - if (details == null){ + if (details == null) { createAccount(addr); - details = getContractDetails(addr); + details = getContractDetails(addr); } details.setCode(code); - detailsDB.put(wrap( addr ), details); + detailsDB.put(wrap(addr), details); } @Override @@ -295,8 +295,8 @@ public class RepositoryDummy implements Repository { @Override public void loadAccount(byte[] addr, HashMap cacheAccounts, HashMap cacheDetails) { - AccountState account = getAccountState(addr); - ContractDetails details = getContractDetails(addr); + AccountState account = getAccountState(addr); + ContractDetails details = getContractDetails(addr); if (account == null) account = new AccountState(); diff --git a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryImpl.java b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryImpl.java index 460e7691..4a0c98ee 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryImpl.java @@ -43,37 +43,37 @@ public class RepositoryImpl implements Repository { private static final Logger logger = LoggerFactory.getLogger("repository"); - private Trie worldState; + private Trie worldState; - private DatabaseImpl detailsDB = null; - private DatabaseImpl stateDB = null; + private DatabaseImpl detailsDB = null; + private DatabaseImpl stateDB = null; public RepositoryImpl() { this(DETAILS_DB, STATE_DB); } public RepositoryImpl(String detailsDbName, String stateDbName) { - detailsDB = new DatabaseImpl(detailsDbName); - stateDB = new DatabaseImpl(stateDbName); - worldState = new TrieImpl(stateDB.getDb()); + detailsDB = new DatabaseImpl(detailsDbName); + stateDB = new DatabaseImpl(stateDbName); + worldState = new TrieImpl(stateDB.getDb()); } @Override public void reset() { close(); - detailsDB = new DatabaseImpl(DETAILS_DB); - stateDB = new DatabaseImpl(STATE_DB); - worldState = new TrieImpl(stateDB.getDb()); + detailsDB = new DatabaseImpl(DETAILS_DB); + stateDB = new DatabaseImpl(STATE_DB); + worldState = new TrieImpl(stateDB.getDb()); } @Override public void close() { - if (this.detailsDB != null){ + if (this.detailsDB != null) { detailsDB.close(); detailsDB = null; } - if (this.stateDB != null){ + if (this.stateDB != null) { stateDB.close(); stateDB = null; } @@ -93,21 +93,21 @@ public class RepositoryImpl implements Repository { AccountState accountState = stateCache.get(hash); ContractDetails contractDetails = detailsCache.get(hash); - if (accountState.isDeleted()){ + if (accountState.isDeleted()) { worldState.delete(hash.getData()); detailsDB.delete(hash.getData()); logger.debug("delete: [{}]", Hex.toHexString(hash.getData())); - } else{ + } else { - if (accountState.isDirty() || contractDetails.isDirty()){ + if (accountState.isDirty() || contractDetails.isDirty()) { detailsDB.put(hash.getData(), contractDetails.getEncoded()); accountState.setStateRoot(contractDetails.getStorageHash()); accountState.setCodeHash(sha3(contractDetails.getCode())); worldState.update(hash.getData(), accountState.getEncoded()); - if (logger.isDebugEnabled()){ + if (logger.isDebugEnabled()) { logger.debug("update: [{}],nonce: [{}] balance: [{}] \n [{}]", Hex.toHexString(hash.getData()), accountState.getNonce(), @@ -126,7 +126,7 @@ public class RepositoryImpl implements Repository { } @Override - public void flush(){ + public void flush() { logger.info("flush to disk"); worldState.sync(); } @@ -134,12 +134,12 @@ public class RepositoryImpl implements Repository { @Override public void rollback() { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } @Override public void commit() { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(); } @Override @@ -164,7 +164,9 @@ public class RepositoryImpl implements Repository { if (block.getNumber() == 0 && txNumber == 0) if (CONFIG.dumpCleanOnRestart()) { try { - FileUtils.deleteDirectory(CONFIG.dumpDir());} catch (IOException e) {} + FileUtils.deleteDirectory(CONFIG.dumpDir()); + } catch (IOException e) { + } } String dir = CONFIG.dumpDir() + "/"; @@ -212,7 +214,7 @@ public class RepositoryImpl implements Repository { } } - public void dumpTrie(Block block){ + public void dumpTrie(Block block) { if (!(CONFIG.dumpFull() || CONFIG.dumpBlock() == block.getNumber())) return; @@ -239,9 +241,11 @@ public class RepositoryImpl implements Repository { logger.error(e.getMessage(), e); } finally { try { - if (bw != null)bw.close(); - if (fw != null)fw.close(); - } catch (IOException e) {e.printStackTrace();} + if (bw != null) bw.close(); + if (fw != null) fw.close(); + } catch (IOException e) { + e.printStackTrace(); + } } } @@ -279,7 +283,7 @@ public class RepositoryImpl implements Repository { @Override public DataWord getStorageValue(byte[] addr, DataWord key) { - ContractDetails details = getContractDetails(addr); + ContractDetails details = getContractDetails(addr); if (details == null) return null; @@ -290,11 +294,11 @@ public class RepositoryImpl implements Repository { @Override public void addStorageRow(byte[] addr, DataWord key, DataWord value) { - ContractDetails details = getContractDetails(addr); + ContractDetails details = getContractDetails(addr); - if (details == null){ + if (details == null) { createAccount(addr); - details = getContractDetails(addr); + details = getContractDetails(addr); } details.put(key, value); @@ -304,7 +308,7 @@ public class RepositoryImpl implements Repository { @Override public byte[] getCode(byte[] addr) { - ContractDetails details = getContractDetails(addr); + ContractDetails details = getContractDetails(addr); if (details == null) return null; @@ -314,11 +318,11 @@ public class RepositoryImpl implements Repository { @Override public void saveCode(byte[] addr, byte[] code) { - ContractDetails details = getContractDetails(addr); + ContractDetails details = getContractDetails(addr); - if (details == null){ + if (details == null) { createAccount(addr); - details = getContractDetails(addr); + details = getContractDetails(addr); } details.setCode(code); @@ -365,8 +369,6 @@ public class RepositoryImpl implements Repository { } - - @Override public void delete(byte[] addr) { worldState.delete(addr); @@ -419,8 +421,8 @@ public class RepositoryImpl implements Repository { HashMap cacheAccounts, HashMap cacheDetails) { - AccountState account = getAccountState(addr); - ContractDetails details = getContractDetails(addr); + AccountState account = getAccountState(addr); + ContractDetails details = getContractDetails(addr); if (account == null) account = new AccountState(); diff --git a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryTrack.java b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryTrack.java index 4b01d86b..c3970906 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/RepositoryTrack.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/RepositoryTrack.java @@ -27,12 +27,12 @@ public class RepositoryTrack implements Repository { private static final Logger logger = LoggerFactory.getLogger("repository"); - HashMap cacheAccounts = new HashMap<>(); - HashMap cacheDetails = new HashMap<>(); + HashMap cacheAccounts = new HashMap<>(); + HashMap cacheDetails = new HashMap<>(); Repository repository; - public RepositoryTrack(){ + public RepositoryTrack() { this.repository = new RepositoryDummy(); } @@ -43,7 +43,7 @@ public class RepositoryTrack implements Repository { @Override public AccountState createAccount(byte[] addr) { - logger.trace("createAccount: [{}]", Hex.toHexString(addr)) ; + logger.trace("createAccount: [{}]", Hex.toHexString(addr)); AccountState accountState = new AccountState(); cacheAccounts.put(wrap(addr), accountState); @@ -59,7 +59,7 @@ public class RepositoryTrack implements Repository { AccountState accountState = cacheAccounts.get(wrap(addr)); - if (accountState == null){ + if (accountState == null) { repository.loadAccount(addr, cacheAccounts, cacheDetails); accountState = cacheAccounts.get(wrap(addr)); } @@ -83,7 +83,7 @@ public class RepositoryTrack implements Repository { ContractDetails contractDetails = cacheDetails.get(wrap(addr)); - if (contractDetails == null){ + if (contractDetails == null) { repository.loadAccount(addr, cacheAccounts, cacheDetails); contractDetails = cacheDetails.get(wrap(addr)); } @@ -93,12 +93,12 @@ public class RepositoryTrack implements Repository { @Override public void loadAccount(byte[] addr, HashMap cacheAccounts, - HashMap cacheDetails){ + HashMap cacheDetails) { - AccountState accountState = this.cacheAccounts.get(wrap(addr)); + AccountState accountState = this.cacheAccounts.get(wrap(addr)); ContractDetails contractDetails = this.cacheDetails.get(wrap(addr)); - if (accountState == null){ + if (accountState == null) { repository.loadAccount(addr, cacheAccounts, cacheDetails); } else { cacheAccounts.put(wrap(addr), accountState.clone()); @@ -110,7 +110,7 @@ public class RepositoryTrack implements Repository { @Override public void delete(byte[] addr) { - logger.trace("delete account: [{}]", Hex.toHexString(addr)) ; + logger.trace("delete account: [{}]", Hex.toHexString(addr)); getAccountState(addr).setDeleted(true); getContractDetails(addr).setDeleted(true); } @@ -165,7 +165,7 @@ public class RepositoryTrack implements Repository { public BigInteger addBalance(byte[] addr, BigInteger value) { AccountState accountState = getAccountState(addr); - if (accountState == null){ + if (accountState == null) { accountState = createAccount(addr); } @@ -210,7 +210,7 @@ public class RepositoryTrack implements Repository { throw new UnsupportedOperationException(); } - public Set getFullAddressSet(){ + public Set getFullAddressSet() { return cacheAccounts.keySet(); } @@ -228,7 +228,7 @@ public class RepositoryTrack implements Repository { @Override - public void flush(){ + public void flush() { throw new UnsupportedOperationException(); } @@ -256,14 +256,14 @@ public class RepositoryTrack implements Repository { } @Override - public void updateBatch(HashMap accountStates, - HashMap contractDetailes){ + public void updateBatch(HashMap accountStates, + HashMap contractDetailes) { - for (ByteArrayWrapper hash : accountStates.keySet()){ + for (ByteArrayWrapper hash : accountStates.keySet()) { cacheAccounts.put(hash, accountStates.get(hash)); } - for (ByteArrayWrapper hash : contractDetailes.keySet()){ + for (ByteArrayWrapper hash : contractDetailes.keySet()) { cacheDetails.put(hash, contractDetailes.get(hash)); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/db/TrackDatabase.java b/ethereumj-core/src/main/java/org/ethereum/db/TrackDatabase.java index 717f51a2..013480ea 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/TrackDatabase.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/TrackDatabase.java @@ -30,10 +30,10 @@ public class TrackDatabase implements Database { } public void commitTrack() { - for(ByteArrayWrapper key : changes.keySet()) { + for (ByteArrayWrapper key : changes.keySet()) { db.put(key.getData(), changes.get(key)); } - for(ByteArrayWrapper key : deletes) { + for (ByteArrayWrapper key : deletes) { db.delete(key.getData()); } changes = null; @@ -57,7 +57,7 @@ public class TrackDatabase implements Database { } public byte[] get(byte[] key) { - if(trackingChanges) { + if (trackingChanges) { ByteArrayWrapper wKey = new ByteArrayWrapper(key); if (deletes.contains(wKey)) return null; if (changes.get(wKey) != null) return changes.get(wKey); @@ -65,7 +65,9 @@ public class TrackDatabase implements Database { return db.get(key); } - /** Delete object (key) from db **/ + /** + * Delete object (key) from db * + */ public void delete(byte[] key) { if (trackingChanges) { ByteArrayWrapper wKey = new ByteArrayWrapper(key); @@ -76,7 +78,7 @@ public class TrackDatabase implements Database { } @Override - public void close(){ + public void close() { db.close(); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/db/TransactionReceiptVO.java b/ethereumj-core/src/main/java/org/ethereum/db/TransactionReceiptVO.java index d2a65521..5dfa33a2 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/TransactionReceiptVO.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/TransactionReceiptVO.java @@ -26,8 +26,8 @@ public class TransactionReceiptVO { } public TransactionReceiptVO(byte[] hash, byte[] rlp) { - this.hash = hash; - this.rlp = rlp; + this.hash = hash; + this.rlp = rlp; } public byte[] getHash() { diff --git a/ethereumj-core/src/main/java/org/ethereum/facade/Blockchain.java b/ethereumj-core/src/main/java/org/ethereum/facade/Blockchain.java index eaa74c97..aa768598 100644 --- a/ethereumj-core/src/main/java/org/ethereum/facade/Blockchain.java +++ b/ethereumj-core/src/main/java/org/ethereum/facade/Blockchain.java @@ -11,30 +11,47 @@ import org.ethereum.db.ByteArrayWrapper; import org.ethereum.net.BlockQueue; import org.ethereum.core.Genesis; -public interface Blockchain { +public interface Blockchain { public static final byte[] GENESIS_HASH = Genesis.getInstance().getHash(); public long getSize(); + public void add(Block block); + public void tryToConnect(Block block); + public void storeBlock(Block block, List receipts); + public Block getBlockByNumber(long blockNr); + public void setBestBlock(Block block); + public Block getBestBlock(); + public BlockQueue getQueue(); + public boolean hasParentOnTheChain(Block block); + public void reset(); + public void close(); + public void updateTotalDifficulty(Block block); + public BigInteger getTotalDifficulty(); + public void setTotalDifficulty(BigInteger totalDifficulty); + public byte[] getBestBlockHash(); + public List getListOfHashesStartFrom(byte[] hash, int qty); TransactionReceipt getTransactionReceiptByHash(byte[] hash); public Block getBlockByHash(byte[] hash); + public List getAltChains(); + public List getGarbage(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/facade/Ethereum.java b/ethereumj-core/src/main/java/org/ethereum/facade/Ethereum.java index 9033421c..2e4f0d5f 100644 --- a/ethereumj-core/src/main/java/org/ethereum/facade/Ethereum.java +++ b/ethereumj-core/src/main/java/org/ethereum/facade/Ethereum.java @@ -24,10 +24,11 @@ public interface Ethereum { /** * Find a peer but not this one + * * @param excludePeer - peer to exclude * @return online peer if available otherwise null */ - public PeerInfo findOnlinePeer(PeerInfo excludePeer) ; + public PeerInfo findOnlinePeer(PeerInfo excludePeer); /** * Find an online peer but not from excluded list @@ -35,7 +36,7 @@ public interface Ethereum { * @param excludePeerSet - peers to exclude * @return online peer if available otherwise null */ - public PeerInfo findOnlinePeer(Set excludePeerSet) ; + public PeerInfo findOnlinePeer(Set excludePeerSet); /** * @return online peer if available @@ -64,9 +65,11 @@ public interface Ethereum { public Set getPeers(); public void startPeerDiscovery(); + public void stopPeerDiscovery(); public void connect(InetAddress addr, int port); + public void connect(String ip, int port); public Blockchain getBlockchain(); diff --git a/ethereumj-core/src/main/java/org/ethereum/facade/EthereumFactory.java b/ethereumj-core/src/main/java/org/ethereum/facade/EthereumFactory.java index c72b6c98..b5609465 100644 --- a/ethereumj-core/src/main/java/org/ethereum/facade/EthereumFactory.java +++ b/ethereumj-core/src/main/java/org/ethereum/facade/EthereumFactory.java @@ -61,7 +61,7 @@ public class EthereumFactory { @Bean - public DataSourceTransactionManager transactionManager(){ + public DataSourceTransactionManager transactionManager() { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(dataSource()); @@ -69,18 +69,18 @@ public class EthereumFactory { } @Bean(name = "dataSource") - public DriverManagerDataSource dataSource(){ + public DriverManagerDataSource dataSource() { logger.info("Connecting to the block store"); System.setProperty("hsqldb.reconfig_logging", "false"); String url = - String.format("jdbc:hsqldb:file:./%s/blockchain/blockchain.db;" + - "create=%s;hsqldb.default_table_type=cached", + String.format("jdbc:hsqldb:file:./%s/blockchain/blockchain.db;" + + "create=%s;hsqldb.default_table_type=cached", - SystemProperties.CONFIG.databaseDir(), - SystemProperties.CONFIG.databaseReset()); + SystemProperties.CONFIG.databaseDir(), + SystemProperties.CONFIG.databaseReset()); DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); @@ -99,12 +99,12 @@ public class EthereumFactory { private static EthereumFactory factory; - public static Ethereum createEthereum(){ + public static Ethereum createEthereum() { logger.info("capability eth version: [{}]", EthHandler.VERSION); logger.info("capability shh version: [{}]", ShhHandler.VERSION); - if (context == null){ + if (context == null) { context = new AnnotationConfigApplicationContext(EthereumFactory.class); factory = context.getBean(EthereumFactory.class); } diff --git a/ethereumj-core/src/main/java/org/ethereum/facade/EthereumImpl.java b/ethereumj-core/src/main/java/org/ethereum/facade/EthereumImpl.java index 2d38a50b..553d76be 100644 --- a/ethereumj-core/src/main/java/org/ethereum/facade/EthereumImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/facade/EthereumImpl.java @@ -60,19 +60,22 @@ public class EthereumImpl implements Ethereum { } @PostConstruct - public void init(){ + public void init() { worldManager.loadBlockchain(); - if (CONFIG.listenPort() > 0){ + if (CONFIG.listenPort() > 0) { Executors.newSingleThreadExecutor().submit( - new Runnable() { public void run() { - peerServer.start(CONFIG.listenPort()); - }} + new Runnable() { + public void run() { + peerServer.start(CONFIG.listenPort()); + } + } ); } } /** * Find a peer but not this one + * * @param peer - peer to exclude * @return online peer */ @@ -90,7 +93,7 @@ public class EthereumImpl implements Ethereum { } @Override - public PeerInfo findOnlinePeer(Set excludePeers) { + public PeerInfo findOnlinePeer(Set excludePeers) { logger.info("Looking for online peers..."); final EthereumListener listener = worldManager.getListener(); @@ -132,7 +135,7 @@ public class EthereumImpl implements Ethereum { } @Override - public void startPeerDiscovery(){ + public void startPeerDiscovery() { worldManager.startPeerDiscovery(); } @@ -179,10 +182,10 @@ public class EthereumImpl implements Ethereum { } @Override - public PeerClient getDefaultPeer(){ + public PeerClient getDefaultPeer() { PeerClient peer = worldManager.getActivePeer(); - if (peer == null){ + if (peer == null) { peer = new PeerClient(); worldManager.setActivePeer(peer); @@ -200,12 +203,12 @@ public class EthereumImpl implements Ethereum { BigInteger gasPrice, BigInteger gas, byte[] recieveAddress, - BigInteger value, byte[] data ){ + BigInteger value, byte[] data) { - byte[] nonceBytes = ByteUtil.bigIntegerToBytes(nonce); - byte[] gasPriceBytes = ByteUtil.bigIntegerToBytes(gasPrice); - byte[] gasBytes = ByteUtil.bigIntegerToBytes(gas); - byte[] valueBytes = ByteUtil.bigIntegerToBytes(value); + byte[] nonceBytes = ByteUtil.bigIntegerToBytes(nonce); + byte[] gasPriceBytes = ByteUtil.bigIntegerToBytes(gasPrice); + byte[] gasBytes = ByteUtil.bigIntegerToBytes(gas); + byte[] valueBytes = ByteUtil.bigIntegerToBytes(value); Transaction tx = new Transaction(nonceBytes, gasPriceBytes, gasBytes, recieveAddress, valueBytes, data); @@ -215,7 +218,7 @@ public class EthereumImpl implements Ethereum { @Override - public Future submitTransaction(Transaction transaction){ + public Future submitTransaction(Transaction transaction) { TransactionTask transactionTask = new TransactionTask(transaction, worldManager); Future future = TransactionExecutor.instance.submitTransaction(transactionTask); @@ -225,13 +228,13 @@ public class EthereumImpl implements Ethereum { @Override - public Wallet getWallet(){ + public Wallet getWallet() { return worldManager.getWallet(); } @Override - public Repository getRepository(){ + public Repository getRepository() { return worldManager.getRepository(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/facade/Repository.java b/ethereumj-core/src/main/java/org/ethereum/facade/Repository.java index 1ecfce92..74aaba11 100644 --- a/ethereumj-core/src/main/java/org/ethereum/facade/Repository.java +++ b/ethereumj-core/src/main/java/org/ethereum/facade/Repository.java @@ -143,7 +143,7 @@ public interface Repository { * @param gasUsed the amount of gas used in the block until that point * @param txNumber is the number of the transaction for which the dump has to be made * @param txHash is the hash of the given transaction. - * If null, the block state post coinbase reward is dumped. + * If null, the block state post coinbase reward is dumped. */ public void dumpState(Block block, long gasUsed, int txNumber, byte[] txHash); @@ -172,12 +172,14 @@ public interface Repository { /** * Return to one of the previous snapshots * by moving the root. + * * @param root - new root */ public void syncToRoot(byte[] root); /** * Check to see if the current repository has an open connection to the database + * * @return true if connection to database is open */ public boolean isClosed(); @@ -198,7 +200,7 @@ public interface Repository { public byte[] getRoot(); - void loadAccount(byte[] addr, HashMap cacheAccounts, + void loadAccount(byte[] addr, HashMap cacheAccounts, HashMap cacheDetails); } diff --git a/ethereumj-core/src/main/java/org/ethereum/json/EtherObjectMapper.java b/ethereumj-core/src/main/java/org/ethereum/json/EtherObjectMapper.java index fe778700..3b14325b 100644 --- a/ethereumj-core/src/main/java/org/ethereum/json/EtherObjectMapper.java +++ b/ethereumj-core/src/main/java/org/ethereum/json/EtherObjectMapper.java @@ -15,36 +15,34 @@ import com.fasterxml.jackson.databind.ObjectMapper; * customize ethereum state dumps. * * @author Alon Muroch - * */ public class EtherObjectMapper extends ObjectMapper { @Override public String writeValueAsString(Object value) throws JsonProcessingException { - // alas, we have to pull the recycler directly here... - SegmentedStringWriter sw = new SegmentedStringWriter(_jsonFactory._getBufferRecycler()); - try { - JsonGenerator ge = _jsonFactory.createGenerator(sw); - // set ethereum custom pretty printer - EtherPrettyPrinter pp = new EtherPrettyPrinter(); - ge.setPrettyPrinter(pp); + // alas, we have to pull the recycler directly here... + SegmentedStringWriter sw = new SegmentedStringWriter(_jsonFactory._getBufferRecycler()); + try { + JsonGenerator ge = _jsonFactory.createGenerator(sw); + // set ethereum custom pretty printer + EtherPrettyPrinter pp = new EtherPrettyPrinter(); + ge.setPrettyPrinter(pp); - _configAndWriteValue(ge, value); - } catch (JsonProcessingException e) { // to support [JACKSON-758] - throw e; - } catch (IOException e) { // shouldn't really happen, but is declared as possibility so: - throw JsonMappingException.fromUnexpectedIOE(e); - } - return sw.getAndClear(); + _configAndWriteValue(ge, value); + } catch (JsonProcessingException e) { // to support [JACKSON-758] + throw e; + } catch (IOException e) { // shouldn't really happen, but is declared as possibility so: + throw JsonMappingException.fromUnexpectedIOE(e); } + return sw.getAndClear(); + } /** * An extended {@link com.fasterxml.jackson.core.util.DefaultPrettyPrinter} class to customize * an ethereum {@link com.fasterxml.jackson.core.PrettyPrinter Pretty Printer} Generator * * @author Alon Muroch - * */ public class EtherPrettyPrinter extends DefaultPrettyPrinter { @@ -55,11 +53,11 @@ public class EtherObjectMapper extends ObjectMapper { @Override public void writeObjectFieldValueSeparator(JsonGenerator jg) throws IOException, JsonGenerationException { - /** - * Custom object separator (Default is " : ") to make it easier to compare state dumps with other - * ethereum client implementations - */ - jg.writeRaw(": "); - } + /** + * Custom object separator (Default is " : ") to make it easier to compare state dumps with other + * ethereum client implementations + */ + jg.writeRaw(": "); + } } } diff --git a/ethereumj-core/src/main/java/org/ethereum/json/JSONHelper.java b/ethereumj-core/src/main/java/org/ethereum/json/JSONHelper.java index 2973033c..074c76f2 100644 --- a/ethereumj-core/src/main/java/org/ethereum/json/JSONHelper.java +++ b/ethereumj-core/src/main/java/org/ethereum/json/JSONHelper.java @@ -17,7 +17,7 @@ import java.util.*; /** * JSON Helper class to format data into ObjectNodes - * to match PyEthereum blockstate output + * to match PyEthereum blockstate output * * Dump format: * { @@ -80,8 +80,8 @@ public class JSONHelper { ObjectNode statesNode = blockNode.objectNode(); for (ByteArrayWrapper key : keys) { byte[] keyBytes = key.getData(); - AccountState accountState = repository.getAccountState(keyBytes); - ContractDetails details = repository.getContractDetails(keyBytes); + AccountState accountState = repository.getAccountState(keyBytes); + ContractDetails details = repository.getContractDetails(keyBytes); JSONHelper.dumpState(statesNode, Hex.toHexString(keyBytes), accountState, details); } blockNode.put("state", statesNode); diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/AccountState.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/AccountState.java index e3bd5b87..4f9a1697 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/AccountState.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/AccountState.java @@ -31,29 +31,29 @@ public class AccountState { public AccountState(byte[] address, JSONObject accountState) { this.address = address; - String balance = accountState.get("balance").toString(); - String code = (String)accountState.get("code"); - String nonce = accountState.get("nonce").toString(); + String balance = accountState.get("balance").toString(); + String code = (String) accountState.get("code"); + String nonce = accountState.get("nonce").toString(); - JSONObject store = (JSONObject)accountState.get("storage"); + JSONObject store = (JSONObject) accountState.get("storage"); this.balance = new BigInteger(balance).toByteArray(); if (code != null && code.length() > 2) - this.code = Hex.decode(code.substring(2)); + this.code = Hex.decode(code.substring(2)); else this.code = ByteUtil.EMPTY_BYTE_ARRAY; - this.nonce = new BigInteger(nonce).toByteArray(); + this.nonce = new BigInteger(nonce).toByteArray(); int size = store.keySet().size(); Object[] keys = store.keySet().toArray(); for (int i = 0; i < size; ++i) { String keyS = keys[i].toString(); - String valS = store.get(keys[i]).toString(); + String valS = store.get(keys[i]).toString(); - byte[] key = Utils.parseData(keyS); + byte[] key = Utils.parseData(keyS); byte[] value = Utils.parseData(valS); storage.put(new DataWord(key), new DataWord(value)); } @@ -89,12 +89,12 @@ public class AccountState { return storage; } - public List compareToReal(org.ethereum.core.AccountState state, ContractDetails details){ + public List compareToReal(org.ethereum.core.AccountState state, ContractDetails details) { List results = new ArrayList<>(); BigInteger expectedBalance = new BigInteger(1, this.getBalance()); - if (!state.getBalance().equals(expectedBalance)){ + if (!state.getBalance().equals(expectedBalance)) { String formatedString = String.format("Account: %s: has unexpected balance, expected balance: %s found balance: %s", Hex.toHexString(this.address), expectedBalance.toString(), state.getBalance().toString()); results.add(formatedString); @@ -105,13 +105,13 @@ public class AccountState { state.getNonce(); this.getNonce(); String formatedString = String.format("Account: %s: has unexpected nonce, expected nonce: %s found nonce: %s", - Hex.toHexString(this.address), expectedNonce.toString(), state.getNonce().toString() ); + Hex.toHexString(this.address), expectedNonce.toString(), state.getNonce().toString()); results.add(formatedString); } if (!Arrays.equals(details.getCode(),this.getCode())) { String formatedString = String.format("Account: %s: has unexpected nonce, expected nonce: %s found nonce: %s", - Hex.toHexString(this.address), Hex.toHexString( this.getCode() ), Hex.toHexString(details.getCode())); + Hex.toHexString(this.address), Hex.toHexString(this.getCode()), Hex.toHexString(details.getCode())); results.add(formatedString); } @@ -121,7 +121,7 @@ public class AccountState { Set expectedKeys = this.getStorage().keySet(); Set checked = new HashSet<>(); - for (DataWord key : keys){ + for (DataWord key : keys) { DataWord value = details.getStorage().get(key); DataWord expectedValue = this.getStorage().get(key); @@ -137,7 +137,7 @@ public class AccountState { continue; } - if (!expectedValue.equals(value)){ + if (!expectedValue.equals(value)) { String formatedString = String.format("Account: %s: has unexpected value, for key: %s , expectedValue: %s real value: %s", Hex.toHexString(this.address), key.toString(), @@ -149,8 +149,8 @@ public class AccountState { checked.add(key); } - for (DataWord key : expectedKeys){ - if (!checked.contains(key)){ + for (DataWord key : expectedKeys) { + if (!checked.contains(key)) { String formatedString = String.format("Account: %s: doesn't exist expected storage key: %s", Hex.toHexString(this.address), key.toString()); results.add(formatedString); diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/CallCreate.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/CallCreate.java index 8c0c8c10..36a49aa4 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/CallCreate.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/CallCreate.java @@ -30,19 +30,19 @@ public class CallCreate { public CallCreate(JSONObject callCreateJSON) { - String data = callCreateJSON.get("data").toString(); + String data = callCreateJSON.get("data").toString(); String destination = callCreateJSON.get("destination").toString(); - String gasLimit = callCreateJSON.get("gasLimit").toString(); - String value = callCreateJSON.get("value").toString(); + String gasLimit = callCreateJSON.get("gasLimit").toString(); + String value = callCreateJSON.get("value").toString(); if (data != null && data.length() > 2) - this.data = Hex.decode(data.substring(2)); + this.data = Hex.decode(data.substring(2)); else this.data = ByteUtil.EMPTY_BYTE_ARRAY; this.destination = Hex.decode(destination); - this.gasLimit = ByteUtil.bigIntegerToBytes(new BigInteger(gasLimit)); - this.value = ByteUtil.bigIntegerToBytes(new BigInteger(value)); + this.gasLimit = ByteUtil.bigIntegerToBytes(new BigInteger(gasLimit)); + this.value = ByteUtil.bigIntegerToBytes(new BigInteger(value)); } public byte[] getData() { @@ -64,10 +64,10 @@ public class CallCreate { @Override public String toString() { return "CallCreate{" + - "data=" + Hex.toHexString(data) + + "data=" + Hex.toHexString(data) + ", destination=" + Hex.toHexString(destination) + - ", gasLimit=" + Hex.toHexString(gasLimit) + - ", value=" + Hex.toHexString(value) + + ", gasLimit=" + Hex.toHexString(gasLimit) + + ", value=" + Hex.toHexString(value) + '}'; } } diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Env.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Env.java index cd112e44..489e711d 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Env.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Env.java @@ -33,19 +33,19 @@ public class Env { */ public Env(JSONObject env) { - String coinbase = env.get("currentCoinbase").toString(); + String coinbase = env.get("currentCoinbase").toString(); String difficulty = env.get("currentDifficulty").toString(); - String timestamp = env.get("currentTimestamp").toString(); - String number = env.get("currentNumber").toString(); - String gasLimit = env.get("currentGasLimit").toString(); - String prevHash = env.get("previousHash").toString(); + String timestamp = env.get("currentTimestamp").toString(); + String number = env.get("currentNumber").toString(); + String gasLimit = env.get("currentGasLimit").toString(); + String prevHash = env.get("previousHash").toString(); - this.currentCoinbase = Hex.decode(coinbase); + this.currentCoinbase = Hex.decode(coinbase); this.currentDifficlty = new BigInteger(difficulty).toByteArray(); - this.currentGasLimit = new BigInteger(gasLimit).toByteArray(); - this.currentNumber = new BigInteger(number).toByteArray(); + this.currentGasLimit = new BigInteger(gasLimit).toByteArray(); + this.currentNumber = new BigInteger(number).toByteArray(); this.currentTimestamp = new BigInteger(timestamp).toByteArray(); - this.previousHash = Hex.decode(prevHash); + this.previousHash = Hex.decode(prevHash); } diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Exec.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Exec.java index 9a459b9c..73a28a84 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Exec.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Exec.java @@ -42,36 +42,36 @@ public class Exec { */ public Exec(JSONObject exec) { - String address = exec.get("address").toString(); - String caller = exec.get("caller").toString(); + String address = exec.get("address").toString(); + String caller = exec.get("caller").toString(); - String code = exec.get("code").toString(); - String data = exec.get("data").toString(); + String code = exec.get("code").toString(); + String data = exec.get("data").toString(); - String gas = exec.get("gas").toString(); + String gas = exec.get("gas").toString(); String gasPrice = exec.get("gasPrice").toString(); - String origin = exec.get("origin").toString(); + String origin = exec.get("origin").toString(); - String value = exec.get("value").toString(); + String value = exec.get("value").toString(); this.address = Hex.decode(address); - this.caller = Hex.decode(caller); + this.caller = Hex.decode(caller); if (code != null && code.length() > 2) - this.code = Hex.decode(code.substring(2)); + this.code = Hex.decode(code.substring(2)); else this.code = ByteUtil.EMPTY_BYTE_ARRAY; if (data != null && data.length() > 2) - this.data = Hex.decode(data.substring(2)); + this.data = Hex.decode(data.substring(2)); else this.data = ByteUtil.EMPTY_BYTE_ARRAY; - this.gas = ByteUtil.bigIntegerToBytes(new BigInteger(gas)); + this.gas = ByteUtil.bigIntegerToBytes(new BigInteger(gas)); this.gasPrice = ByteUtil.bigIntegerToBytes(new BigInteger(gasPrice)); - this.origin = Hex.decode(origin); - this.value = ByteUtil.bigIntegerToBytes(new BigInteger(value)); + this.origin = Hex.decode(origin); + this.value = ByteUtil.bigIntegerToBytes(new BigInteger(value)); } @@ -86,6 +86,7 @@ public class Exec { public byte[] getData() { return data; } + public byte[] getCode() { return code; } diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Helper.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Helper.java index 2cb75cc7..7e80b617 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Helper.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Helper.java @@ -21,7 +21,7 @@ public class Helper { private static Logger logger = LoggerFactory.getLogger("misc"); - public static byte[] parseDataArray(JSONArray valArray){ + public static byte[] parseDataArray(JSONArray valArray) { // value can be: // 1. 324234 number @@ -29,34 +29,45 @@ public class Helper { // 3. "239472398472" - big number ByteArrayOutputStream bos = new ByteArrayOutputStream(); - for (int i = 0; i < valArray.size(); ++i){ + for (int i = 0; i < valArray.size(); ++i) { Object val = valArray.get(i); - if (val instanceof String){ + if (val instanceof String) { // Hex num boolean hexVal = Pattern.matches("0[xX][0-9a-fA-F]+", val.toString()); - if (hexVal){ + if (hexVal) { String number = ((String) val).substring(2); if (number.length() % 2 == 1) number = "0" + number; byte[] data = Hex.decode(number); - try {bos.write(data);} catch (IOException e) { logger.error("should not happen", e);} - } else{ + try { + bos.write(data); + } catch (IOException e) { + logger.error("should not happen", e); + } + } else { // BigInt num boolean isNumeric = Pattern.matches("[0-9a-fA-F]+", val.toString()); if (!isNumeric) throw new Error("Wrong test case JSON format"); - else{ + else { BigInteger value = new BigInteger(val.toString()); - try {bos.write(value.toByteArray());} catch (IOException e) - { logger.error("should not happen", e);} + try { + bos.write(value.toByteArray()); + } catch (IOException e) { + logger.error("should not happen", e); + } } } } else if (val instanceof Long) { // Simple long - byte[] data = ByteUtil.bigIntegerToBytes(BigInteger.valueOf((Long)val)); - try {bos.write(data);} catch (IOException e) {logger.error("should not happen", e);} + byte[] data = ByteUtil.bigIntegerToBytes(BigInteger.valueOf((Long) val)); + try { + bos.write(data); + } catch (IOException e) { + logger.error("should not happen", e); + } } else { throw new Error("Wrong test case JSON format"); } diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/JSONReader.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/JSONReader.java index a7013592..d3cb8e6d 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/JSONReader.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/JSONReader.java @@ -16,7 +16,7 @@ public class JSONReader { public static String loadJSON(String filename) { String json = ""; - if(!SystemProperties.CONFIG.vmTestLoadLocal()) + if (!SystemProperties.CONFIG.vmTestLoadLocal()) json = getFromUrl("https://raw.githubusercontent.com/ethereum/tests/develop/" + filename); return json == "" ? json = getFromLocal(filename) : json; } @@ -24,8 +24,9 @@ public class JSONReader { public static String getFromLocal(String filename) { System.out.println("Loading local file: " + filename); try { - if(System.getProperty("ETHEREUM_TEST_PATH") == null) { - System.out.println("ETHEREUM_TEST_PATH is not passed as a VM argument, please make sure you pass it with the correct path"); + if (System.getProperty("ETHEREUM_TEST_PATH") == null) { + System.out.println("ETHEREUM_TEST_PATH is not passed as a VM argument, please make sure you pass it " + + "with the correct path"); return ""; } System.out.println("From: " + System.getProperty("ETHEREUM_TEST_PATH")); diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Logs.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Logs.java index 8e1e3d42..ecf033fe 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Logs.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Logs.java @@ -18,17 +18,17 @@ public class Logs { public Logs(JSONArray jLogs) { - for (int i = 0; i < jLogs.size(); ++i){ + for (int i = 0; i < jLogs.size(); ++i) { - JSONObject jLog = (JSONObject)jLogs.get(i); - byte[] address = Hex.decode((String)jLog.get("address")); - byte[] data = Hex.decode(((String)jLog.get("data")).substring(2)); + JSONObject jLog = (JSONObject) jLogs.get(i); + byte[] address = Hex.decode((String) jLog.get("address")); + byte[] data = Hex.decode(((String) jLog.get("data")).substring(2)); List topics = new ArrayList<>(); - JSONArray jTopics = (JSONArray)jLog.get("topics"); - for(Object t: jTopics.toArray()) { - byte[] topic = Hex.decode(((String)t)); + JSONArray jTopics = (JSONArray) jLog.get("topics"); + for (Object t : jTopics.toArray()) { + byte[] topic = Hex.decode(((String) t)); topics.add(new DataWord(topic)); } @@ -38,24 +38,24 @@ public class Logs { } - public Iterator getIterator(){ + public Iterator getIterator() { return logs.iterator(); } - public List compareToReal(List logs){ + public List compareToReal(List logs) { List results = new ArrayList<>(); int i = 0; - for (LogInfo postLog : this.logs){ + for (LogInfo postLog : this.logs) { LogInfo realLog = logs.get(i); String postAddress = Hex.toHexString(postLog.getAddress()); String realAddress = Hex.toHexString(realLog.getAddress()); - if (!postAddress.equals(realAddress)){ + if (!postAddress.equals(realAddress)) { String formatedString = String.format("Log: %s: has unexpected address, expected address: %s found address: %s", i, postAddress, realAddress); @@ -65,7 +65,7 @@ public class Logs { String postData = Hex.toHexString(postLog.getData()); String realData = Hex.toHexString(realLog.getData()); - if (!postData.equals(realData)){ + if (!postData.equals(realData)) { String formatedString = String.format("Log: %s: has unexpected data, expected data: %s found data: %s", i, postData, realData); @@ -86,11 +86,11 @@ public class Logs { List realTopics = realLog.getTopics(); int j = 0; - for (DataWord postTopic : postTopics){ + for (DataWord postTopic : postTopics) { DataWord realTopic = realTopics.get(j); - if (!postTopic.equals(realTopic)){ + if (!postTopic.equals(realTopic)) { String formatedString = String.format("Log: %s: has unexpected topic: %s, expected topic: %s found topic: %s", i, j, postTopic, realTopic); diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/StateTestCase.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/StateTestCase.java index 1be713c0..f590f8bd 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/StateTestCase.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/StateTestCase.java @@ -21,8 +21,8 @@ public class StateTestCase { private String name = ""; - private Env env; - private Logs logs; + private Env env; + private Logs logs; private byte[] out; // "pre": { ... }, @@ -39,44 +39,44 @@ public class StateTestCase { this.name = name; } - public StateTestCase(JSONObject testCaseJSONObj) throws ParseException{ + public StateTestCase(JSONObject testCaseJSONObj) throws ParseException { try { - JSONObject envJSON = (JSONObject)testCaseJSONObj.get("env"); - JSONArray logsJSON = (JSONArray)testCaseJSONObj.get("logs"); - String outStr = testCaseJSONObj.get("out").toString(); - JSONObject txJSON = (JSONObject)testCaseJSONObj.get("transaction"); + JSONObject envJSON = (JSONObject) testCaseJSONObj.get("env"); + JSONArray logsJSON = (JSONArray) testCaseJSONObj.get("logs"); + String outStr = testCaseJSONObj.get("out").toString(); + JSONObject txJSON = (JSONObject) testCaseJSONObj.get("transaction"); - JSONObject preJSON = (JSONObject)testCaseJSONObj.get("pre"); - JSONObject postJSON = (JSONObject)testCaseJSONObj.get("post"); + JSONObject preJSON = (JSONObject) testCaseJSONObj.get("pre"); + JSONObject postJSON = (JSONObject) testCaseJSONObj.get("post"); - this.env = new Env(envJSON); + this.env = new Env(envJSON); this.logs = new Logs(logsJSON); - this.out = Utils.parseData(outStr); - this.transaction = new Transaction(txJSON); + this.out = Utils.parseData(outStr); + this.transaction = new Transaction(txJSON); - for (Object key : preJSON.keySet()){ + for (Object key : preJSON.keySet()) { byte[] keyBytes = Hex.decode(key.toString()); AccountState accountState = - new AccountState(keyBytes, (JSONObject) preJSON.get(key)); + new AccountState(keyBytes, (JSONObject) preJSON.get(key)); pre.put(new ByteArrayWrapper(keyBytes), accountState); } - for (Object key : postJSON.keySet()){ + for (Object key : postJSON.keySet()) { byte[] keyBytes = Hex.decode(key.toString()); AccountState accountState = - new AccountState(keyBytes, (JSONObject) postJSON.get(key)); + new AccountState(keyBytes, (JSONObject) postJSON.get(key)); post.put(new ByteArrayWrapper(keyBytes), accountState); } } catch (Throwable e) { - throw new ParseException(0, e); + throw new ParseException(0, e); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/StateTestSuite.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/StateTestSuite.java index 186e6ec9..5a9a6165 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/StateTestSuite.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/StateTestSuite.java @@ -21,7 +21,7 @@ public class StateTestSuite { public StateTestSuite(JSONObject testCaseJSONObj) throws ParseException { - for (Object key: testCaseJSONObj.keySet()){ + for (Object key : testCaseJSONObj.keySet()) { Object testCaseJSON = testCaseJSONObj.get(key); @@ -31,19 +31,17 @@ public class StateTestSuite { } } - public StateTestCase getTestCase(String name){ + public StateTestCase getTestCase(String name) { StateTestCase testCase = testCases.get(name); if (testCase == null) throw new NullPointerException("Test cases doesn't exist: " + name); - return testCase; + return testCase; } - public Collection getAllTests(){ + public Collection getAllTests() { return testCases.values(); } - - } diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestCase.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestCase.java index 14651bb8..578f5271 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestCase.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestCase.java @@ -45,73 +45,74 @@ public class TestCase { // "callcreates": { ... } private List callCreateList = new ArrayList<>(); - public TestCase(String name, JSONObject testCaseJSONObj) throws ParseException{ + public TestCase(String name, JSONObject testCaseJSONObj) throws ParseException { this(testCaseJSONObj); this.name = name; } - public TestCase(JSONObject testCaseJSONObj) throws ParseException{ + public TestCase(JSONObject testCaseJSONObj) throws ParseException { try { - JSONObject envJSON = (JSONObject)testCaseJSONObj.get("env"); - JSONObject execJSON = (JSONObject)testCaseJSONObj.get("exec"); - JSONObject preJSON = (JSONObject)testCaseJSONObj.get("pre"); + JSONObject envJSON = (JSONObject) testCaseJSONObj.get("env"); + JSONObject execJSON = (JSONObject) testCaseJSONObj.get("exec"); + JSONObject preJSON = (JSONObject) testCaseJSONObj.get("pre"); JSONObject postJSON = new JSONObject(); - if(testCaseJSONObj.containsKey("post")) // in cases where there is no post dictionary (when testing for exceptions for example) - postJSON = (JSONObject)testCaseJSONObj.get("post"); - JSONArray callCreates = new JSONArray(); - if(testCaseJSONObj.containsKey("callcreates")) - callCreates = (JSONArray)testCaseJSONObj.get("callcreates"); + if (testCaseJSONObj.containsKey("post")) // in cases where there is no post dictionary (when testing for + // exceptions for example) + postJSON = (JSONObject) testCaseJSONObj.get("post"); + JSONArray callCreates = new JSONArray(); + if (testCaseJSONObj.containsKey("callcreates")) + callCreates = (JSONArray) testCaseJSONObj.get("callcreates"); JSONArray logsJSON = new JSONArray(); - if(testCaseJSONObj.containsKey("logs")) - logsJSON = (JSONArray)testCaseJSONObj.get("logs"); + if (testCaseJSONObj.containsKey("logs")) + logsJSON = (JSONArray) testCaseJSONObj.get("logs"); logs = new Logs(logsJSON); - String gasString = "0"; - if(testCaseJSONObj.containsKey("gas")) + String gasString = "0"; + if (testCaseJSONObj.containsKey("gas")) gasString = testCaseJSONObj.get("gas").toString(); - this.gas = ByteUtil.bigIntegerToBytes(new BigInteger(gasString)); + this.gas = ByteUtil.bigIntegerToBytes(new BigInteger(gasString)); String outString = null; - if(testCaseJSONObj.containsKey("out")) + if (testCaseJSONObj.containsKey("out")) outString = testCaseJSONObj.get("out").toString(); if (outString != null && outString.length() > 2) - this.out = Hex.decode(outString.substring(2)); + this.out = Hex.decode(outString.substring(2)); else this.out = ByteUtil.EMPTY_BYTE_ARRAY; - for (Object key : preJSON.keySet()){ + for (Object key : preJSON.keySet()) { byte[] keyBytes = Hex.decode(key.toString()); AccountState accountState = - new AccountState(keyBytes, (JSONObject) preJSON.get(key)); + new AccountState(keyBytes, (JSONObject) preJSON.get(key)); pre.put(new ByteArrayWrapper(keyBytes), accountState); } - for (Object key : postJSON.keySet()){ + for (Object key : postJSON.keySet()) { byte[] keyBytes = Hex.decode(key.toString()); AccountState accountState = - new AccountState(keyBytes, (JSONObject) postJSON.get(key)); + new AccountState(keyBytes, (JSONObject) postJSON.get(key)); post.put(new ByteArrayWrapper(keyBytes), accountState); } - for (int i = 0; i < callCreates.size(); ++i){ + for (int i = 0; i < callCreates.size(); ++i) { - CallCreate cc = new CallCreate((JSONObject)callCreates.get(i)); + CallCreate cc = new CallCreate((JSONObject) callCreates.get(i)); this.callCreateList.add(cc); } - this.env = new Env(envJSON); + this.env = new Env(envJSON); this.exec = new Exec(execJSON); } catch (Throwable e) { - throw new ParseException(0, e); + throw new ParseException(0, e); } } @@ -147,7 +148,7 @@ public class TestCase { return callCreateList; } - public String getName(){ + public String getName() { return name; } diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestProgramInvokeFactory.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestProgramInvokeFactory.java index 90b2e396..919616d7 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestProgramInvokeFactory.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestProgramInvokeFactory.java @@ -15,11 +15,11 @@ import java.math.BigInteger; * Created on: 19/12/2014 12:22 */ -public class TestProgramInvokeFactory implements ProgramInvokeFactory{ +public class TestProgramInvokeFactory implements ProgramInvokeFactory { Env env; - TestProgramInvokeFactory(Env env){ + TestProgramInvokeFactory(Env env) { this.env = env; } @@ -36,15 +36,15 @@ public class TestProgramInvokeFactory implements ProgramInvokeFactory{ } - private ProgramInvoke generalInvoke(Transaction tx, Repository repository){ + private ProgramInvoke generalInvoke(Transaction tx, Repository repository) { /*** ADDRESS op ***/ // YP: Get address of currently executing account. - byte[] address = tx.isContractCreation() ? tx.getContractAddress(): tx.getReceiveAddress(); + byte[] address = tx.isContractCreation() ? tx.getContractAddress() : tx.getReceiveAddress(); /*** ORIGIN op ***/ // YP: This is the sender of original transaction; it is never a contract. - byte[] origin = tx.getSender(); + byte[] origin = tx.getSender(); /*** CALLER op ***/ // YP: This is the address of the account that is directly responsible for this execution. @@ -80,10 +80,10 @@ public class TestProgramInvokeFactory implements ProgramInvokeFactory{ long number = ByteUtil.byteArrayToLong(env.getCurrentNumber()); /*** DIFFICULTY op ***/ - byte[] difficulty = env.getCurrentDifficlty(); + byte[] difficulty = env.getCurrentDifficlty(); /*** GASLIMIT op ***/ - long gaslimit = ByteUtil.byteArrayToLong( env.getCurrentGasLimit() ); + long gaslimit = ByteUtil.byteArrayToLong(env.getCurrentGasLimit()); return new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, data, lastHash, coinbase, diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestRunner.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestRunner.java index 2d8f493c..9e976073 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestRunner.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestRunner.java @@ -53,7 +53,7 @@ public class TestRunner { List results = null; logger.info("\n***"); - logger.info(" Running test case: [" + testCase.getName() + "]") ; + logger.info(" Running test case: [" + testCase.getName() + "]"); logger.info("***\n"); results = new ArrayList<>(); @@ -62,7 +62,7 @@ public class TestRunner { logger.info("loaded repository"); - org.ethereum.core.Transaction tx = createTransaction(testCase.getTransaction()); + org.ethereum.core.Transaction tx = createTransaction(testCase.getTransaction()); logger.info("transaction: {}", tx.toString()); byte[] secretKey = testCase.getTransaction().secretKey; @@ -91,9 +91,9 @@ public class TestRunner { List logResults = testCase.getLogs().compareToReal(logs); results.addAll(logResults); - Set fullAddressSet = repository.getFullAddressSet(); + Set fullAddressSet = repository.getFullAddressSet(); int repoSize = 0; - for (ByteArrayWrapper addrWrapped : fullAddressSet){ + for (ByteArrayWrapper addrWrapped : fullAddressSet) { byte[] addr = addrWrapped.getData(); @@ -101,11 +101,11 @@ public class TestRunner { ContractDetails contractDetails = repository.getContractDetails(addr); logger.info("{} \n{} \n{}", Hex.toHexString(addr), - accountState.toString(), contractDetails.toString() ); + accountState.toString(), contractDetails.toString()); logger.info(""); AccountState expectedAccountState = testCase.getPost().get(wrap(addr)); - if (expectedAccountState == null){ + if (expectedAccountState == null) { String formatedString = String.format("Unexpected account state: address: %s", Hex.toHexString(addr)); results.add(formatedString); continue; @@ -119,7 +119,7 @@ public class TestRunner { int postRepoSize = testCase.getPost().size(); - if (postRepoSize > repoSize){ + if (postRepoSize > repoSize) { results.add("ERROR: Post repository contains more accounts than executed repository "); } @@ -129,7 +129,7 @@ public class TestRunner { public List runTestCase(TestCase testCase) { logger.info("\n***"); - logger.info(" Running test case: [" + testCase.getName() + "]") ; + logger.info(" Running test case: [" + testCase.getName() + "]"); logger.info("***\n"); List results = new ArrayList<>(); @@ -141,29 +141,29 @@ public class TestRunner { /* 2. Create ProgramInvoke - Env/Exec */ - Env env = testCase.getEnv(); + Env env = testCase.getEnv(); Exec exec = testCase.getExec(); Logs logs = testCase.getLogs(); - byte[] address = exec.getAddress(); - byte[] origin = exec.getOrigin(); - byte[] caller = exec.getCaller(); - byte[] balance = ByteUtil.bigIntegerToBytes(repository.getBalance(exec.getAddress())); - byte[] gasPrice = exec.getGasPrice(); - byte[] gas = exec.getGas(); - byte[] callValue = exec.getValue(); - byte[] msgData = exec.getData(); - byte[] lastHash = env.getPreviousHash(); - byte[] coinbase = env.getCurrentCoinbase(); - long timestamp = new BigInteger(env.getCurrentTimestamp()).longValue(); - long number = new BigInteger(env.getCurrentNumber()).longValue(); - byte[] difficulty = env.getCurrentDifficlty(); - long gaslimit = new BigInteger(env.getCurrentGasLimit()).longValue(); + byte[] address = exec.getAddress(); + byte[] origin = exec.getOrigin(); + byte[] caller = exec.getCaller(); + byte[] balance = ByteUtil.bigIntegerToBytes(repository.getBalance(exec.getAddress())); + byte[] gasPrice = exec.getGasPrice(); + byte[] gas = exec.getGas(); + byte[] callValue = exec.getValue(); + byte[] msgData = exec.getData(); + byte[] lastHash = env.getPreviousHash(); + byte[] coinbase = env.getCurrentCoinbase(); + long timestamp = new BigInteger(env.getCurrentTimestamp()).longValue(); + long number = new BigInteger(env.getCurrentNumber()).longValue(); + byte[] difficulty = env.getCurrentDifficlty(); + long gaslimit = new BigInteger(env.getCurrentGasLimit()).longValue(); // Origin and caller need to exist in order to be able to execute - if(repository.getAccountState(origin) == null) + if (repository.getAccountState(origin) == null) repository.createAccount(origin); - if(repository.getAccountState(caller) == null) + if (repository.getAccountState(caller) == null) repository.createAccount(caller); ProgramInvoke programInvoke = new ProgramInvokeImpl(address, origin, caller, balance, @@ -177,27 +177,24 @@ public class TestRunner { boolean vmDidThrowAnEception = false; RuntimeException e = null; try { - while(!program.isStopped()) + while (!program.isStopped()) vm.step(program); - } - catch (RuntimeException ex) { + } catch (RuntimeException ex) { vmDidThrowAnEception = true; e = ex; } program.saveProgramTraceToFile(testCase.getName()); - if(testCase.getPost().size() == 0) { - if(vmDidThrowAnEception != true) { + if (testCase.getPost().size() == 0) { + if (vmDidThrowAnEception != true) { String output = String.format("VM was expected to throw an exception"); logger.info(output); results.add(output); - } - else + } else logger.info("VM did throw an exception: " + e.toString()); - } - else { - if(vmDidThrowAnEception) { + } else { + if (vmDidThrowAnEception) { String output = String.format("VM threw an unexpected exception: " + e.toString()); logger.info(output); @@ -213,9 +210,9 @@ public class TestRunner { AccountState accountState = testCase.getPost().get(key); - long expectedNonce = accountState.getNonceLong(); - BigInteger expectedBalance = accountState.getBigIntegerBalance(); - byte[] expectedCode = accountState.getCode(); + long expectedNonce = accountState.getNonceLong(); + BigInteger expectedBalance = accountState.getBigIntegerBalance(); + byte[] expectedCode = accountState.getCode(); boolean accountExist = (null != repository.getAccountState(key.getData())); if (!accountExist) { @@ -283,17 +280,17 @@ public class TestRunner { continue; } - Map testStorage = contractDetails.getStorage(); + Map testStorage = contractDetails.getStorage(); DataWord actualValue = testStorage.get(new DataWord(storageKey.getData())); if (actualValue == null || - !Arrays.equals(expectedStValue, actualValue.getNoLeadZeroesData())) { + !Arrays.equals(expectedStValue, actualValue.getNoLeadZeroesData())) { String output = String.format("Storage value different: key [ %s ], expectedValue: [ %s ], actualValue: [ %s ]", Hex.toHexString(storageKey.getData()), Hex.toHexString(expectedStValue), - actualValue == null ? "" : Hex.toHexString(actualValue.getNoLeadZeroesData())); + actualValue == null ? "" : Hex.toHexString(actualValue.getNoLeadZeroesData())); logger.info(output); results.add(output); } @@ -304,36 +301,35 @@ public class TestRunner { Iterator postLogs = logs.getIterator(); int i = 0; - while(postLogs.hasNext()) { + while (postLogs.hasNext()) { LogInfo expectedLogInfo = postLogs.next(); LogInfo foundLogInfo = null; if (logResult.size() > i) - foundLogInfo = logResult.get(i); + foundLogInfo = logResult.get(i); - if(foundLogInfo == null) { + if (foundLogInfo == null) { String output = String.format("Expected log [ %s ]", expectedLogInfo.toString()); logger.info(output); results.add(output); - } - else { - if(!Arrays.equals(expectedLogInfo.getAddress(), foundLogInfo.getAddress())) { + } else { + if (!Arrays.equals(expectedLogInfo.getAddress(), foundLogInfo.getAddress())) { String output = String.format("Expected address [ %s ], found [ %s ]", Hex.toHexString(expectedLogInfo.getAddress()), Hex.toHexString(foundLogInfo.getAddress())); logger.info(output); results.add(output); } - if(!Arrays.equals(expectedLogInfo.getData(), foundLogInfo.getData())) { + if (!Arrays.equals(expectedLogInfo.getData(), foundLogInfo.getData())) { String output = String.format("Expected data [ %s ], found [ %s ]", Hex.toHexString(expectedLogInfo.getData()), Hex.toHexString(foundLogInfo.getData())); logger.info(output); results.add(output); } - if(!expectedLogInfo.getBloom().equals(foundLogInfo.getBloom())) { + if (!expectedLogInfo.getBloom().equals(foundLogInfo.getBloom())) { String output = String.format("Expected bloom [ %s ], found [ %s ]", Hex.toHexString(expectedLogInfo.getBloom().getData()), @@ -342,18 +338,18 @@ public class TestRunner { results.add(output); } - if(expectedLogInfo.getTopics().size() != foundLogInfo.getTopics().size()) { + if (expectedLogInfo.getTopics().size() != foundLogInfo.getTopics().size()) { String output = - String.format("Expected number of topics [ %d ], found [ %d ]", expectedLogInfo.getTopics().size(), foundLogInfo.getTopics().size()); + String.format("Expected number of topics [ %d ], found [ %d ]", + expectedLogInfo.getTopics().size(), foundLogInfo.getTopics().size()); logger.info(output); results.add(output); - } - else { - int j=0; - for(DataWord topic: expectedLogInfo.getTopics()) { + } else { + int j = 0; + for (DataWord topic : expectedLogInfo.getTopics()) { byte[] foundTopic = foundLogInfo.getTopics().get(j).getData(); - if(!Arrays.equals(topic.getData(), foundTopic)) { + if (!Arrays.equals(topic.getData(), foundTopic)) { String output = String.format("Expected topic [ %s ], found [ %s ]", Hex.toHexString(topic.getData()), Hex.toHexString(foundTopic)); logger.info(output); @@ -373,7 +369,7 @@ public class TestRunner { // TODO: -> basically the deleted by suicide should be deleted // TODO: -> and no unexpected created - List resultCallCreates = + List resultCallCreates = program.getResult().getCallCreateList(); // assert call creates @@ -492,14 +488,14 @@ public class TestRunner { } } - public org.ethereum.core.Transaction createTransaction(Transaction tx){ + public org.ethereum.core.Transaction createTransaction(Transaction tx) { - byte[] nonceBytes = ByteUtil.longToBytes(tx.nonce); - byte[] gasPriceBytes = ByteUtil.longToBytes(tx.gasPrice); - byte[] gasBytes = ByteUtil.longToBytes(tx.gasLimit); - byte[] valueBytes = ByteUtil.longToBytes(tx.value); - byte[] toAddr = tx.getTo(); - byte[] data = tx.getData(); + byte[] nonceBytes = ByteUtil.longToBytes(tx.nonce); + byte[] gasPriceBytes = ByteUtil.longToBytes(tx.gasPrice); + byte[] gasBytes = ByteUtil.longToBytes(tx.gasLimit); + byte[] valueBytes = ByteUtil.longToBytes(tx.value); + byte[] toAddr = tx.getTo(); + byte[] data = tx.getData(); org.ethereum.core.Transaction transaction = new org.ethereum.core.Transaction( nonceBytes, gasPriceBytes, gasBytes, @@ -508,7 +504,7 @@ public class TestRunner { return transaction; } - public RepositoryDummy loadRepository(Map pre){ + public RepositoryDummy loadRepository(Map pre) { RepositoryDummy track = new RepositoryDummy(); @@ -524,7 +520,7 @@ public class TestRunner { track.saveCode(addr, accountState.getCode()); - for (DataWord storageKey : accountState.getStorage().keySet()){ + for (DataWord storageKey : accountState.getStorage().keySet()) { track.addStorageRow(addr, storageKey, accountState.getStorage().get(storageKey)); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestSuite.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestSuite.java index 023f8117..f89497b3 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestSuite.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestSuite.java @@ -18,7 +18,7 @@ public class TestSuite { public TestSuite(JSONObject testCaseJSONObj) throws ParseException { - for (Object key: testCaseJSONObj.keySet()){ + for (Object key : testCaseJSONObj.keySet()) { Object testCaseJSON = testCaseJSONObj.get(key); TestCase testCase = new TestCase(key.toString(), (JSONObject) testCaseJSON); @@ -26,7 +26,7 @@ public class TestSuite { } } - public Iterator iterator(){ + public Iterator iterator() { return testList.iterator(); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Transaction.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Transaction.java index d2a4c80e..16f62224 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Transaction.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Transaction.java @@ -19,12 +19,12 @@ import static org.ethereum.util.ByteUtil.toHexString; public class Transaction { byte[] data; - long gasLimit; - long gasPrice; - long nonce; + long gasLimit; + long gasPrice; + long nonce; byte[] secretKey; byte[] to; - long value; + long value; /* e.g. "transaction" : { @@ -40,22 +40,22 @@ public class Transaction { public Transaction(JSONObject callCreateJSON) { - String dataStr = callCreateJSON.get("data").toString(); - String gasLimitStr = callCreateJSON.get("gasLimit").toString(); - String gasPriceStr = callCreateJSON.get("gasPrice").toString(); - String nonceStr = callCreateJSON.get("nonce").toString(); - String secretKeyStr = callCreateJSON.get("secretKey").toString(); - String toStr = callCreateJSON.get("to").toString(); - String valueStr = callCreateJSON.get("value").toString(); + String dataStr = callCreateJSON.get("data").toString(); + String gasLimitStr = callCreateJSON.get("gasLimit").toString(); + String gasPriceStr = callCreateJSON.get("gasPrice").toString(); + String nonceStr = callCreateJSON.get("nonce").toString(); + String secretKeyStr = callCreateJSON.get("secretKey").toString(); + String toStr = callCreateJSON.get("to").toString(); + String valueStr = callCreateJSON.get("value").toString(); - this.data = Utils.parseData(dataStr); - this.gasLimit = Utils.parseLong(gasLimitStr); - this.gasPrice = Utils.parseLong(gasPriceStr); - this.nonce = Utils.parseLong(nonceStr); + this.data = Utils.parseData(dataStr); + this.gasLimit = Utils.parseLong(gasLimitStr); + this.gasPrice = Utils.parseLong(gasPriceStr); + this.nonce = Utils.parseLong(nonceStr); this.secretKey = Utils.parseData(secretKeyStr); - this.to = Utils.parseData(toStr); - this.value = Utils.parseLong(valueStr); + this.to = Utils.parseData(toStr); + this.value = Utils.parseLong(valueStr); } public byte[] getData() { diff --git a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Utils.java b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Utils.java index c264a73f..6d0d64e6 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Utils.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Utils.java @@ -14,14 +14,14 @@ import org.spongycastle.util.encoders.Hex; public class Utils { - public static byte[] parseData(String data){ + public static byte[] parseData(String data) { if (data == null) return ByteUtil.EMPTY_BYTE_ARRAY; if (data.startsWith("0x")) data = data.substring(2); return Hex.decode(data); } - public static long parseLong(String data){ - return data.equals("") ? 0 : Long.parseLong(data); + public static long parseLong(String data) { + return data.equals("") ? 0 : Long.parseLong(data); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListener.java b/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListener.java index 9858eee4..f162ee7e 100644 --- a/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListener.java +++ b/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListener.java @@ -16,11 +16,18 @@ import java.util.Set; public interface EthereumListener { public void trace(String output); + public void onBlock(Block block); + public void onRecvMessage(Message message); + public void onSendMessage(Message message); + public void onPeerDisconnect(String host, long port); + public void onPendingTransactionsReceived(Set transactions); + public void onSyncDone(); + public void onNoConnections(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListenerAdapter.java b/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListenerAdapter.java index 3791544e..945ba8f9 100644 --- a/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListenerAdapter.java +++ b/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListenerAdapter.java @@ -42,7 +42,7 @@ public class EthereumListenerAdapter implements EthereumListener { } @Override - public void onNoConnections(){ + public void onNoConnections() { } } diff --git a/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListenerWrapper.java b/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListenerWrapper.java index 75b85912..847d0478 100644 --- a/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListenerWrapper.java +++ b/ethereumj-core/src/main/java/org/ethereum/listener/EthereumListenerWrapper.java @@ -13,8 +13,8 @@ import java.util.Set; * @author: Roman Mandeleil * Created on: 12/11/2014 08:34 */ -@Component(value="EthereumListener") -public class EthereumListenerWrapper implements EthereumListener{ +@Component(value = "EthereumListener") +public class EthereumListenerWrapper implements EthereumListener { EthereumListener listener; @@ -64,12 +64,12 @@ public class EthereumListenerWrapper implements EthereumListener{ @Override - public void onNoConnections(){ + public void onNoConnections() { if (listener != null) listener.onNoConnections(); } - public void addListener(EthereumListener listener){ + public void addListener(EthereumListener listener) { if (listener != null) this.listener = listener; } diff --git a/ethereumj-core/src/main/java/org/ethereum/manager/AdminInfo.java b/ethereumj-core/src/main/java/org/ethereum/manager/AdminInfo.java index 30620ca2..acf5b98d 100644 --- a/ethereumj-core/src/main/java/org/ethereum/manager/AdminInfo.java +++ b/ethereumj-core/src/main/java/org/ethereum/manager/AdminInfo.java @@ -31,7 +31,7 @@ public class AdminInfo { return consensus; } - public void lostConsensus(){ + public void lostConsensus() { consensus = false; } } diff --git a/ethereumj-core/src/main/java/org/ethereum/manager/WorldManager.java b/ethereumj-core/src/main/java/org/ethereum/manager/WorldManager.java index 031d89dd..7d3530b3 100644 --- a/ethereumj-core/src/main/java/org/ethereum/manager/WorldManager.java +++ b/ethereumj-core/src/main/java/org/ethereum/manager/WorldManager.java @@ -75,7 +75,7 @@ public class WorldManager { public void addListener(EthereumListener listener) { logger.info("Ethereum listener added"); - ((EthereumListenerWrapper)this.listener).addListener(listener); + ((EthereumListenerWrapper) this.listener).addListener(listener); } public void startPeerDiscovery() { @@ -88,7 +88,7 @@ public class WorldManager { peerDiscovery.stop(); } - public void addPendingTransactions(Set transactions){ + public void addPendingTransactions(Set transactions) { logger.info("Pending transaction list added: size: [{}]", transactions.size()); if (listener != null) @@ -96,15 +96,15 @@ public class WorldManager { pendingTransactions.addAll(transactions); } - public void clearPendingTransactions(List recivedTransactions){ + public void clearPendingTransactions(List recivedTransactions) { - for (Transaction tx : recivedTransactions){ + for (Transaction tx : recivedTransactions) { logger.info("Clear transaction, hash: [{}]", Hex.toHexString(tx.getHash())); pendingTransactions.remove(tx); } } - public ChannelManager getChannelManager(){ + public ChannelManager getChannelManager() { return channelManager; } @@ -116,7 +116,7 @@ public class WorldManager { return listener; } - public void setWallet(Wallet wallet) { + public void setWallet(Wallet wallet) { this.wallet = wallet; } @@ -144,7 +144,7 @@ public class WorldManager { return pendingTransactions; } - public boolean isBlockchainLoading(){ + public boolean isBlockchainLoading() { return blockchain.getQueue().size() > 2; } @@ -180,14 +180,14 @@ public class WorldManager { } - if (CONFIG.rootHashStart() != null){ + if (CONFIG.rootHashStart() != null) { // update world state by dummy hash byte[] rootHash = Hex.decode(CONFIG.rootHashStart()); logger.info("Loading root hash from property file: [{}]", CONFIG.rootHashStart()); this.repository.syncToRoot(rootHash); - } else{ + } else { // Update world state to latest loaded block from db this.repository.syncToRoot(blockchain.getBestBlock().getStateRoot()); @@ -202,7 +202,7 @@ public class WorldManager { */ } - public void reset(){ + public void reset() { logger.info("Resetting blockchain "); repository.reset(); blockchain.reset(); diff --git a/ethereumj-core/src/main/java/org/ethereum/mine/Miner.java b/ethereumj-core/src/main/java/org/ethereum/mine/Miner.java index d340bdbf..97982e85 100644 --- a/ethereumj-core/src/main/java/org/ethereum/mine/Miner.java +++ b/ethereumj-core/src/main/java/org/ethereum/mine/Miner.java @@ -77,9 +77,9 @@ public class Miner { byte[] testNonce = new byte[32]; byte[] concat; - while(ByteUtil.increment(testNonce) && !stop) { + while (ByteUtil.increment(testNonce) && !stop) { - if (testNonce[31] == 0 && testNonce[30] == 0){ + if (testNonce[31] == 0 && testNonce[30] == 0) { System.out.println("mining: " + new BigInteger(1, testNonce)); } @@ -87,7 +87,7 @@ public class Miner { sleep(); concat = Arrays.concatenate(hash, testNonce); byte[] result = SHA3Helper.sha3(concat); - if(FastByteComparisons.compareTo(result, 0, 32, target, 0, 32) < 0) { + if (FastByteComparisons.compareTo(result, 0, 32, target, 0, 32) < 0) { newBlock.setNonce(testNonce); return true; } @@ -95,11 +95,11 @@ public class Miner { return false; // couldn't find a valid nonce } - public void stop(){ + public void stop() { stop = true; } - private void sleep(){ + private void sleep() { try { // Thread.sleep(1); Thread.sleep(10); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/BlockQueue.java b/ethereumj-core/src/main/java/org/ethereum/net/BlockQueue.java index b7ff4fae..19d72331 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/BlockQueue.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/BlockQueue.java @@ -27,17 +27,25 @@ public class BlockQueue { private static final Logger logger = LoggerFactory.getLogger("blockqueue"); - /** The list of hashes of the heaviest chain on the network, - * for which this client doesn't have the blocks yet */ + /** + * The list of hashes of the heaviest chain on the network, + * for which this client doesn't have the blocks yet + */ private Deque blockHashQueue = new ArrayDeque<>(); - /** Queue with blocks to be validated and added to the blockchain */ + /** + * Queue with blocks to be validated and added to the blockchain + */ private Queue blockReceivedQueue = new ConcurrentLinkedQueue<>(); - /** Highest known total difficulty, representing the heaviest chain on the network */ + /** + * Highest known total difficulty, representing the heaviest chain on the network + */ private BigInteger highestTotalDifficulty; - /** Last block in the queue to be processed */ + /** + * Last block in the queue to be processed + */ private Block lastBlock; private Timer timer = new Timer("BlockQueueTimer"); @@ -61,7 +69,7 @@ public class BlockQueue { return; logger.info("BlockQueue size: {}", blockReceivedQueue.size()); - while(!blockReceivedQueue.isEmpty()){ + while (!blockReceivedQueue.isEmpty()) { Block block = blockReceivedQueue.poll(); logger.info("Processing block index: {}", block.getNumber()); @@ -85,22 +93,23 @@ public class BlockQueue { blockReceivedQueue.addAll(blockList); lastBlock = blockList.get(blockList.size() - 1); - logger.info("Blocks waiting to be proceed: queue.size: [{}] lastBlock.number: [{}]" , + logger.info("Blocks waiting to be proceed: queue.size: [{}] lastBlock.number: [{}]", blockReceivedQueue.size(), lastBlock.getNumber()); } /** * adding single block to the queue usually - * a result of a NEW_BLOCK message announce. + * a result of a NEW_BLOCK message announce. + * * @param block - new block */ - public void addBlock(Block block){ + public void addBlock(Block block) { blockReceivedQueue.add(block); lastBlock = block; - logger.debug("Blocks waiting to be proceed: queue.size: [{}] lastBlock.number: [{}]" , + logger.debug("Blocks waiting to be proceed: queue.size: [{}] lastBlock.number: [{}]", blockReceivedQueue.size(), lastBlock.getNumber()); } @@ -143,19 +152,19 @@ public class BlockQueue { public void addHash(byte[] hash) { blockHashQueue.addLast(hash); - if (logger.isTraceEnabled()){ - logger.trace("Adding hash to a hashQueue: [{}]" , Hex.toHexString(hash)); + if (logger.isTraceEnabled()) { + logger.trace("Adding hash to a hashQueue: [{}]", Hex.toHexString(hash)); } } - public void returnHashes(List hashes){ + public void returnHashes(List hashes) { - ListIterator iterator = hashes.listIterator(hashes.size()); - while(iterator.hasPrevious()) - blockHashQueue.addLast((byte[])iterator.previous()); + ListIterator iterator = hashes.listIterator(hashes.size()); + while (iterator.hasPrevious()) + blockHashQueue.addLast((byte[]) iterator.previous()); } - public void addNewBlockHash(byte[] hash){ + public void addNewBlockHash(byte[] hash) { blockHashQueue.addFirst(hash); } @@ -168,14 +177,14 @@ public class BlockQueue { List hashes = new ArrayList<>(); while (!blockHashQueue.isEmpty() && hashes.size() < CONFIG.maxBlocksAsk()) { - hashes.add(blockHashQueue.removeLast()); + hashes.add(blockHashQueue.removeLast()); } return hashes; } // a bit ugly but really gives // good result - public void logHashQueueSize(){ + public void logHashQueueSize() { logger.info("Block hashes list size: [{}]", blockHashQueue.size()); } @@ -213,11 +222,11 @@ public class BlockQueue { return blockReceivedQueue.size(); } - public boolean isHashesEmpty(){ + public boolean isHashesEmpty() { return blockHashQueue.size() == 0; } - public void clear(){ + public void clear() { this.blockHashQueue.clear(); this.blockReceivedQueue.clear(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/MessageQueue.java b/ethereumj-core/src/main/java/org/ethereum/net/MessageQueue.java index 267858e7..19ecebf5 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/MessageQueue.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/MessageQueue.java @@ -16,16 +16,16 @@ import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; /** - * This class contains the logic for sending messages in a queue + * This class contains the logic for sending messages in a queue * - * Messages open by send and answered by receive of appropriate message + * Messages open by send and answered by receive of appropriate message * PING by PONG * GET_PEERS by PEERS * GET_TRANSACTIONS by TRANSACTIONS * GET_BLOCK_HASHES by BLOCK_HASHES * GET_BLOCKS by BLOCKS * - * The following messages will not be answered: + * The following messages will not be answered: * PONG, PEERS, HELLO, STATUS, TRANSACTIONS, BLOCKS * * @author Roman Mandeleil @@ -44,9 +44,10 @@ public class MessageQueue { WorldManager worldManager; boolean hasPing = false; - public MessageQueue(){} + public MessageQueue() { + } - public void activate(ChannelHandlerContext ctx){ + public void activate(ChannelHandlerContext ctx) { this.ctx = ctx; timer.scheduleAtFixedRate(new TimerTask() { public void run() { @@ -117,7 +118,7 @@ public class MessageQueue { } } - public void close(){ + public void close() { timer.cancel(); timer.purge(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/client/Capability.java b/ethereumj-core/src/main/java/org/ethereum/net/client/Capability.java index 63c44833..2edfc005 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/client/Capability.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/client/Capability.java @@ -30,7 +30,7 @@ public class Capability implements Comparable { if (this == obj) return true; if (!(obj instanceof Capability)) return false; - Capability other = (Capability)obj; + Capability other = (Capability) obj; if (this.name == null) return other.name == null; else diff --git a/ethereumj-core/src/main/java/org/ethereum/net/client/PeerClient.java b/ethereumj-core/src/main/java/org/ethereum/net/client/PeerClient.java index 664a7be5..e5b7ebac 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/client/PeerClient.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/client/PeerClient.java @@ -22,6 +22,7 @@ import static org.ethereum.config.SystemProperties.CONFIG; /** * This class creates the connection to an remote address using the Netty framework + * * @see http://netty.io */ @Component diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/BlockHashesMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/BlockHashesMessage.java index 719fb3da..733864c5 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/BlockHashesMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/BlockHashesMessage.java @@ -18,7 +18,9 @@ import org.ethereum.util.Utils; */ public class BlockHashesMessage extends EthMessage { - /** List of block hashes from the peer ordered from child to parent */ + /** + * List of block hashes from the peer ordered from child to parent + */ private List blockHashes; public BlockHashesMessage(byte[] payload) { @@ -69,7 +71,7 @@ public class BlockHashesMessage extends EthMessage { } @Override - public EthMessageCodes getCommand(){ + public EthMessageCodes getCommand() { return EthMessageCodes.BLOCK_HASHES; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/BlocksMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/BlocksMessage.java index 6cd1b775..4a519e68 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/BlocksMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/BlocksMessage.java @@ -23,7 +23,7 @@ public class BlocksMessage extends EthMessage { super(encoded); } - public BlocksMessage(List blocks){ + public BlocksMessage(List blocks) { this.blocks = blocks; parsed = true; } @@ -45,7 +45,7 @@ public class BlocksMessage extends EthMessage { List encodedElements = new Vector<>(); encodedElements.add(RLP.encodeByte(BLOCKS.asByte())); - for (Block block : blocks){ + for (Block block : blocks) { encodedElements.add(block.getEncoded()); } @@ -68,7 +68,7 @@ public class BlocksMessage extends EthMessage { } @Override - public EthMessageCodes getCommand(){ + public EthMessageCodes getCommand() { return EthMessageCodes.BLOCKS; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/EthHandler.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/EthHandler.java index 73c5d491..37ab2bad 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/EthHandler.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/EthHandler.java @@ -73,7 +73,7 @@ public class EthHandler extends SimpleChannelInboundHandler { private List sentHashes; private Block lastBlock = Genesis.getInstance(); - public EthHandler(){ + public EthHandler() { this.peerDiscoveryMode = false; } @@ -82,7 +82,7 @@ public class EthHandler extends SimpleChannelInboundHandler { this.msgQueue = msgQueue; } - public void activate(){ + public void activate() { logger.info("ETH protocol activated"); worldManager.getListener().trace("ETH protocol activated"); @@ -95,7 +95,7 @@ public class EthHandler extends SimpleChannelInboundHandler { } - public boolean isActive(){ + public boolean isActive() { return active; } @@ -121,7 +121,7 @@ public class EthHandler extends SimpleChannelInboundHandler { break; case TRANSACTIONS: msgQueue.receivedMessage(msg); - processTransactions((TransactionsMessage)msg); + processTransactions((TransactionsMessage) msg); // List txList = transactionsMessage.getTransactions(); // for(Transaction tx : txList) // WorldManager.getInstance().getBlockchain().applyTransaction(null, @@ -138,7 +138,7 @@ public class EthHandler extends SimpleChannelInboundHandler { break; case GET_BLOCKS: msgQueue.receivedMessage(msg); - processGetBlocks( (GetBlocksMessage) msg ); + processGetBlocks((GetBlocksMessage) msg); break; case BLOCKS: msgQueue.receivedMessage(msg); @@ -146,7 +146,7 @@ public class EthHandler extends SimpleChannelInboundHandler { break; case NEW_BLOCK: msgQueue.receivedMessage(msg); - procesNewBlock((NewBlockMessage)msg); + procesNewBlock((NewBlockMessage) msg); default: break; } @@ -157,7 +157,7 @@ public class EthHandler extends SimpleChannelInboundHandler { Set txSet = msg.getTransactions(); worldManager.addPendingTransactions(txSet); - for (Transaction tx : txSet){ + for (Transaction tx : txSet) { worldManager.getWallet().addTransaction(tx); } } @@ -210,11 +210,11 @@ public class EthHandler extends SimpleChannelInboundHandler { BigInteger peerTotalDifficulty = new BigInteger(1, msg.getTotalDifficulty()); BigInteger highestKnownTotalDifficulty = blockchain.getTotalDifficulty(); - boolean synced= - FastByteComparisons.compareTo(msg.getBestHash(), 0, 32, blockchain.getBestBlockHash(), 0, 32) == 0; + boolean synced = + FastByteComparisons.compareTo(msg.getBestHash(), 0, 32, blockchain.getBestBlockHash(), 0, 32) == 0; - if ( !synced && (highestKnownTotalDifficulty == null || - peerTotalDifficulty.compareTo(highestKnownTotalDifficulty) > 0)) { + if (!synced && (highestKnownTotalDifficulty == null || + peerTotalDifficulty.compareTo(highestKnownTotalDifficulty) > 0)) { logger.info(" Their chain is better: total difficulty : {} vs {}", peerTotalDifficulty.toString(), @@ -225,7 +225,7 @@ public class EthHandler extends SimpleChannelInboundHandler { chainQueue.setBestHash(msg.getBestHash()); syncStatus = SyncSatus.HASH_RETRIEVING; sendGetBlockHashes(); - } else{ + } else { logger.info("The peer sync process fully complete"); syncStatus = SyncSatus.SYNC_DONE; } @@ -249,10 +249,9 @@ public class EthHandler extends SimpleChannelInboundHandler { byte[] foundHash, latestHash = blockchain.getBestBlockHash(); while (hashIterator.hasNext()) { foundHash = hashIterator.next(); - if (FastByteComparisons.compareTo(foundHash, 0, 32, latestHash, 0, 32) != 0){ + if (FastByteComparisons.compareTo(foundHash, 0, 32, latestHash, 0, 32) != 0) { chainQueue.addHash(foundHash); // store unknown hashes in queue until known hash is found - } - else { + } else { logger.trace("Catch up with the hashes until: {[]}", foundHash); // if known hash is found, ignore the rest @@ -270,10 +269,10 @@ public class EthHandler extends SimpleChannelInboundHandler { List blockList = blocksMessage.getBlocks(); if (!blockList.isEmpty()) - lastBlock = blockList.get(blockList.size()-1); + lastBlock = blockList.get(blockList.size() - 1); // check if you got less blocks than you asked - if (blockList.size() < sentHashes.size()){ + if (blockList.size() < sentHashes.size()) { for (int i = 0; i < blockList.size(); ++i) sentHashes.remove(0); @@ -287,14 +286,14 @@ public class EthHandler extends SimpleChannelInboundHandler { syncStatus = SyncSatus.SYNC_DONE; blockchain.getQueue().addBlocks(blockList); blockchain.getQueue().logHashQueueSize(); - } else{ + } else { if (blockList.isEmpty()) return; blockchain.getQueue().addBlocks(blockList); blockchain.getQueue().logHashQueueSize(); sendGetBlocks(); } - for (Block block : blockList){ + for (Block block : blockList) { totalDifficulty.add(block.getCumulativeDifficulty()); } } @@ -302,9 +301,10 @@ public class EthHandler extends SimpleChannelInboundHandler { /** * Processing NEW_BLOCK announce message + * * @param newBlockMessage - new block message */ - public void procesNewBlock(NewBlockMessage newBlockMessage){ + public void procesNewBlock(NewBlockMessage newBlockMessage) { Block newBlock = newBlockMessage.getBlock(); this.lastBlock = newBlock; @@ -320,7 +320,7 @@ public class EthHandler extends SimpleChannelInboundHandler { // If the GET_BLOCKs stage started add hash to the end of the hash list // then the block will be retrieved in it's turn; - if (syncStatus == SyncSatus.BLOCK_RETRIEVING){ + if (syncStatus == SyncSatus.BLOCK_RETRIEVING) { logger.debug("Sync status BLOCK_RETREIVING add to the end of hash list: block.index: [{}]", newBlock.getNumber()); blockchain.getQueue().addNewBlockHash(newBlock.getHash()); @@ -338,7 +338,7 @@ public class EthHandler extends SimpleChannelInboundHandler { totalDifficulty = new BigInteger(1, newBlockMessage.getDifficulty()); } - private void sendStatus(){ + private void sendStatus() { byte protocolVersion = EthHandler.VERSION, networkId = EthHandler.NETWORK_ID; BigInteger totalDifficulty = blockchain.getTotalDifficulty(); byte[] bestHash = blockchain.getBestBlockHash(); @@ -357,7 +357,7 @@ public class EthHandler extends SimpleChannelInboundHandler { msgQueue.sendMessage(msg); } - public void sendNewBlock(Block block){ + public void sendNewBlock(Block block) { NewBlockMessage msg = new NewBlockMessage(block, block.getDifficulty()); msgQueue.sendMessage(msg); } @@ -375,7 +375,7 @@ public class EthHandler extends SimpleChannelInboundHandler { // Parallel download blocks based on hashQueue private void sendGetBlocks() { BlockQueue queue = blockchain.getQueue(); - if (queue.size() > CONFIG.maxBlocksQueued()){ + if (queue.size() > CONFIG.maxBlocksQueued()) { logger.info("postpone asking for blocks: queue: {}", queue.size()); getBlocksTimer.schedule(new TimerTask() { @@ -420,8 +420,8 @@ public class EthHandler extends SimpleChannelInboundHandler { List hashes = msg.getBlockHashes(); Vector blocks = new Vector<>(); - for (byte[] hash : hashes){ - Block block = blockchain.getBlockByHash(hash); + for (byte[] hash : hashes) { + Block block = blockchain.getBlockByHash(hash); blocks.add(block); } @@ -468,37 +468,37 @@ public class EthHandler extends SimpleChannelInboundHandler { stopGetTxTimer(); } - public void setSyncStatus(SyncSatus syncStatus){ + public void setSyncStatus(SyncSatus syncStatus) { this.syncStatus = syncStatus; } - public SyncSatus getSyncStatus(){ + public SyncSatus getSyncStatus() { return syncStatus; } - public void setPeerId(String peerId){ + public void setPeerId(String peerId) { this.peerId = peerId; } - public enum SyncSatus{ + public enum SyncSatus { INIT, HASH_RETRIEVING, BLOCK_RETRIEVING, SYNC_DONE; } - public void setBestHash(byte[] hash){ + public void setBestHash(byte[] hash) { blockchain.getQueue().addHash(hash); } - public void doSync(){ + public void doSync() { logger.info("Sync force activated"); syncStatus = SyncSatus.HASH_RETRIEVING; setBestHash(lastBlock.getHash()); sendGetBlockHashes(); } - public StatusMessage getHandshakeStatusMessage(){ + public StatusMessage getHandshakeStatusMessage() { return handshakeStatusMessage; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/EthMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/EthMessage.java index 9bad0f09..fc3af32a 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/EthMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/EthMessage.java @@ -5,7 +5,8 @@ import org.ethereum.net.message.Message; public abstract class EthMessage extends Message { - public EthMessage() {} + public EthMessage() { + } public EthMessage(byte[] encoded) { super(encoded); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/EthMessageCodes.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/EthMessageCodes.java index 286f5349..08bea64d 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/EthMessageCodes.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/EthMessageCodes.java @@ -15,50 +15,65 @@ public enum EthMessageCodes { /* Ethereum protocol */ - /** [0x00, [PROTOCOL_VERSION, NETWORK_ID, TD, BEST_HASH, GENESIS_HASH]
    + /** + * [0x00, [PROTOCOL_VERSION, NETWORK_ID, TD, BEST_HASH, GENESIS_HASH]
    * Inform a peer of it's current ethereum state. This message should be - * send after the initial handshake and prior to any ethereum related messages. */ + * send after the initial handshake and prior to any ethereum related messages. + */ STATUS(0x00), - /** [+0x01] Request the peer to send all transactions - * currently in the queue. */ + /** + * [+0x01] Request the peer to send all transactions + * currently in the queue. + */ GET_TRANSACTIONS(0x01), - /** [+0x02, [nonce, receiving_address, value, ...], ...]
    + /** + * [+0x02, [nonce, receiving_address, value, ...], ...]
    * Specify (a) transaction(s) that the peer should make sure is included * on its transaction queue. The items in the list (following the first item 0x12) - * are transactions in the format described in the main Ethereum specification. */ + * are transactions in the format described in the main Ethereum specification. + */ TRANSACTIONS(0x02), - /** [+0x03, [hash : B_32, maxBlocks: P]:
    + /** + * [+0x03, [hash : B_32, maxBlocks: P]:
    * Requests a BlockHashes message of at most maxBlocks entries, * of block hashes from the blockchain, starting at the parent of block hash. * Does not require the peer to give maxBlocks hashes - - * they could give somewhat fewer. */ + * they could give somewhat fewer. + */ GET_BLOCK_HASHES(0x03), - /** [+0x04, [hash_0: B_32, hash_1: B_32, ....]:
    Gives a series of hashes + /** + * [+0x04, [hash_0: B_32, hash_1: B_32, ....]:
    Gives a series of hashes * of blocks (each the child of the next). This implies that the blocks - * are ordered from youngest to oldest. */ + * are ordered from youngest to oldest. + */ BLOCK_HASHES(0x04), - /** [+0x05, [hash_0: B_32, hash_1: B_32, ....]:
    Requests a Blocks message + /** + * [+0x05, [hash_0: B_32, hash_1: B_32, ....]:
    Requests a Blocks message * detailing a number of blocks to be sent, each referred to by a hash.
    * Note: Don't expect that the peer necessarily give you all these blocks - * in a single message - you might have to re-request them. */ + * in a single message - you might have to re-request them. + */ GET_BLOCKS(0x05), - /** [+0x06, [block_header, transaction_list, uncle_list], ...]
    + /** + * [+0x06, [block_header, transaction_list, uncle_list], ...]
    * Specify (a) block(s) that the peer should know about. * The items in the list (following the first item, 0x13) - * are blocks in the format described in the main Ethereum specification. */ + * are blocks in the format described in the main Ethereum specification. + */ BLOCKS(0x06), /** * [+0x07 [blockHeader, transactionList, uncleList], totalDifficulty]
    * Specify a single block that the peer should know about. The composite item * in the list (following the message ID) is a block in the format described - * in the main Ethereum specification. */ + * in the main Ethereum specification. + */ NEW_BLOCK(0x07), /** @@ -70,6 +85,7 @@ public enum EthMessageCodes { private int cmd; private static final Map intToTypeMap = new HashMap<>(); + static { for (EthMessageCodes type : EthMessageCodes.values()) { intToTypeMap.put(type.cmd, type); @@ -85,14 +101,15 @@ public enum EthMessageCodes { return type; } - public static boolean inRange(byte code){ + public static boolean inRange(byte code) { return code >= STATUS.asByte() && code <= PACKET_COUNT.asByte(); } - public static void setOffset(byte offset){ + public static void setOffset(byte offset) { EthMessageCodes.OFFSET = offset; } + public byte asByte() { - return (byte) (cmd + OFFSET); + return (byte) (cmd + OFFSET); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/GetBlockHashesMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/GetBlockHashesMessage.java index 0c2f6b6b..3774537e 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/GetBlockHashesMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/GetBlockHashesMessage.java @@ -14,11 +14,15 @@ import org.spongycastle.util.encoders.Hex; */ public class GetBlockHashesMessage extends EthMessage { - /** The newest block hash from which to start sending older hashes */ + /** + * The newest block hash from which to start sending older hashes + */ private byte[] bestHash; - /** The maximum number of blocks to return. - * Note: the peer could return fewer. */ + /** + * The maximum number of blocks to return. + * Note: the peer could return fewer. + */ private int maxBlocks; public GetBlockHashesMessage(byte[] encoded) { @@ -51,7 +55,7 @@ public class GetBlockHashesMessage extends EthMessage { @Override public byte[] getEncoded() { - if(encoded == null) encode(); + if (encoded == null) encode(); return encoded; } @@ -72,7 +76,7 @@ public class GetBlockHashesMessage extends EthMessage { } @Override - public EthMessageCodes getCommand(){ + public EthMessageCodes getCommand() { return EthMessageCodes.GET_BLOCK_HASHES; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/GetBlocksMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/GetBlocksMessage.java index 8db2431b..10403e54 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/GetBlocksMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/GetBlocksMessage.java @@ -17,7 +17,9 @@ import static org.ethereum.net.eth.EthMessageCodes.GET_BLOCKS; */ public class GetBlocksMessage extends EthMessage { - /** List of block hashes for which to retrieve the blocks */ + /** + * List of block hashes for which to retrieve the blocks + */ private List blockHashes; public GetBlocksMessage(byte[] encoded) { @@ -67,7 +69,7 @@ public class GetBlocksMessage extends EthMessage { } @Override - public EthMessageCodes getCommand(){ + public EthMessageCodes getCommand() { return EthMessageCodes.GET_BLOCKS; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/GetTransactionsMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/GetTransactionsMessage.java index c4eff242..84f3c1bf 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/GetTransactionsMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/GetTransactionsMessage.java @@ -11,7 +11,9 @@ import org.spongycastle.util.encoders.Hex; */ public class GetTransactionsMessage extends EthMessage { - /** GetTransactions message is always a the same single command payload */ + /** + * GetTransactions message is always a the same single command payload + */ private final static byte[] FIXED_PAYLOAD = Hex.decode("C116"); public byte[] getEncoded() { @@ -24,7 +26,7 @@ public class GetTransactionsMessage extends EthMessage { } @Override - public EthMessageCodes getCommand(){ + public EthMessageCodes getCommand() { return EthMessageCodes.GET_TRANSACTIONS; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/NewBlockMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/NewBlockMessage.java index 4389b9cb..42503e0b 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/NewBlockMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/NewBlockMessage.java @@ -19,16 +19,16 @@ public class NewBlockMessage extends EthMessage { super(encoded); } - public NewBlockMessage(Block block, byte[] difficulty){ + public NewBlockMessage(Block block, byte[] difficulty) { this.block = block; this.difficulty = difficulty; encode(); } - private void encode(){ - byte[] command = RLP.encodeByte( this.getCommand().asByte()); + private void encode() { + byte[] command = RLP.encodeByte(this.getCommand().asByte()); byte[] block = this.block.getEncoded(); - byte[] diff = RLP.encodeElement(this.difficulty); + byte[] diff = RLP.encodeElement(this.difficulty); this.encoded = RLP.encodeList(command, block, diff); parsed = true; @@ -39,17 +39,17 @@ public class NewBlockMessage extends EthMessage { RLPList blockRLP = ((RLPList) paramsList.get(1)); block = new Block(blockRLP.getRLPData()); - difficulty = paramsList.get(2).getRLPData(); + difficulty = paramsList.get(2).getRLPData(); parsed = true; } - public Block getBlock(){ + public Block getBlock() { if (!parsed) parse(); return block; } - public byte[] getDifficulty(){ + public byte[] getDifficulty() { if (!parsed) parse(); return difficulty; } @@ -60,7 +60,7 @@ public class NewBlockMessage extends EthMessage { } @Override - public EthMessageCodes getCommand(){ + public EthMessageCodes getCommand() { return EthMessageCodes.NEW_BLOCK; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/PacketCountMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/PacketCountMessage.java index 585823d7..a12eb537 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/PacketCountMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/PacketCountMessage.java @@ -5,7 +5,6 @@ import org.ethereum.util.RLP; /** * Wrapper around an Ethereum Ping message on the network - * */ public class PacketCountMessage extends EthMessage { @@ -23,7 +22,7 @@ public class PacketCountMessage extends EthMessage { } private void encode() { - this.encoded = RLP.encodeList(new byte[] {EthMessageCodes.STATUS.asByte()} ); + this.encoded = RLP.encodeList(new byte[]{EthMessageCodes.STATUS.asByte()}); } @@ -33,7 +32,7 @@ public class PacketCountMessage extends EthMessage { } @Override - public EthMessageCodes getCommand(){ + public EthMessageCodes getCommand() { return EthMessageCodes.PACKET_COUNT; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/StatusMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/StatusMessage.java index ef6efc85..268ccda0 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/StatusMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/StatusMessage.java @@ -18,11 +18,17 @@ public class StatusMessage extends EthMessage { private byte protocolVersion; private byte networkId; - /** Total difficulty of the best chain as found in block header. */ + /** + * Total difficulty of the best chain as found in block header. + */ private byte[] totalDifficulty; - /** The hash of the best (i.e. highest TD) known block. */ + /** + * The hash of the best (i.e. highest TD) known block. + */ private byte[] bestHash; - /** The hash of the Genesis block */ + /** + * The hash of the Genesis block + */ private byte[] genesisHash; public StatusMessage(byte[] encoded) { @@ -30,7 +36,7 @@ public class StatusMessage extends EthMessage { } public StatusMessage(byte protocolVersion, byte networkId, - byte[] totalDifficulty, byte[] bestHash, byte[] genesisHash) { + byte[] totalDifficulty, byte[] bestHash, byte[] genesisHash) { this.protocolVersion = protocolVersion; this.networkId = networkId; this.totalDifficulty = totalDifficulty; @@ -42,23 +48,23 @@ public class StatusMessage extends EthMessage { private void parse() { RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); - this.protocolVersion = ((RLPItem) paramsList.get(1)).getRLPData()[0]; - byte[] networkIdBytes = ((RLPItem) paramsList.get(2)).getRLPData(); - this.networkId = networkIdBytes == null ? 0 : networkIdBytes[0]; - this.totalDifficulty = ((RLPItem) paramsList.get(3)).getRLPData(); - this.bestHash = ((RLPItem) paramsList.get(4)).getRLPData(); - this.genesisHash = ((RLPItem) paramsList.get(5)).getRLPData(); + this.protocolVersion = ((RLPItem) paramsList.get(1)).getRLPData()[0]; + byte[] networkIdBytes = ((RLPItem) paramsList.get(2)).getRLPData(); + this.networkId = networkIdBytes == null ? 0 : networkIdBytes[0]; + this.totalDifficulty = ((RLPItem) paramsList.get(3)).getRLPData(); + this.bestHash = ((RLPItem) paramsList.get(4)).getRLPData(); + this.genesisHash = ((RLPItem) paramsList.get(5)).getRLPData(); parsed = true; } private void encode() { - byte[] command = RLP.encodeByte(STATUS.asByte()); - byte[] protocolVersion = RLP.encodeByte(this.protocolVersion); - byte[] networkId = RLP.encodeByte(this.networkId); - byte[] totalDifficulty = RLP.encodeElement(this.totalDifficulty); - byte[] bestHash = RLP.encodeElement(this.bestHash); - byte[] genesisHash = RLP.encodeElement(this.genesisHash); + byte[] command = RLP.encodeByte(STATUS.asByte()); + byte[] protocolVersion = RLP.encodeByte(this.protocolVersion); + byte[] networkId = RLP.encodeByte(this.networkId); + byte[] totalDifficulty = RLP.encodeElement(this.totalDifficulty); + byte[] bestHash = RLP.encodeElement(this.bestHash); + byte[] genesisHash = RLP.encodeElement(this.genesisHash); this.encoded = RLP.encodeList(command, protocolVersion, networkId, totalDifficulty, bestHash, genesisHash); @@ -101,7 +107,7 @@ public class StatusMessage extends EthMessage { } @Override - public EthMessageCodes getCommand(){ + public EthMessageCodes getCommand() { return STATUS; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/eth/TransactionsMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/eth/TransactionsMessage.java index 953cec13..69020680 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/eth/TransactionsMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/eth/TransactionsMessage.java @@ -72,7 +72,7 @@ public class TransactionsMessage extends EthMessage { } @Override - public EthMessageCodes getCommand(){ + public EthMessageCodes getCommand() { return EthMessageCodes.TRANSACTIONS; } @@ -82,11 +82,11 @@ public class TransactionsMessage extends EthMessage { } public String toString() { - if(!parsed) parse(); + if (!parsed) parse(); StringBuffer sb = new StringBuffer(); for (Transaction transaction : transactions) sb.append("\n ").append(transaction); return "[" + this.getCommand().name() + " num:" - + transactions.size() + " " + sb.toString() + "]"; + + transactions.size() + " " + sb.toString() + "]"; } } \ No newline at end of file diff --git a/ethereumj-core/src/main/java/org/ethereum/net/message/Message.java b/ethereumj-core/src/main/java/org/ethereum/net/message/Message.java index 27ff07ce..697be26b 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/message/Message.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/message/Message.java @@ -9,10 +9,11 @@ package org.ethereum.net.message; public abstract class Message { protected boolean parsed; - protected byte[] encoded; + protected byte[] encoded; protected byte code; - public Message() {} + public Message() { + } public Message(byte[] encoded) { this.encoded = encoded; diff --git a/ethereumj-core/src/main/java/org/ethereum/net/message/MessageFactory.java b/ethereumj-core/src/main/java/org/ethereum/net/message/MessageFactory.java index fb6a46a8..22f43aaa 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/message/MessageFactory.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/message/MessageFactory.java @@ -13,7 +13,7 @@ public class MessageFactory { public static Message createMessage(byte[] encoded) { byte code = RLP.getCommandCode(encoded); - if (P2pMessageCodes.inRange(code)){ + if (P2pMessageCodes.inRange(code)) { P2pMessageCodes receivedCommand = P2pMessageCodes.fromByte(code); switch (receivedCommand) { diff --git a/ethereumj-core/src/main/java/org/ethereum/net/message/ReasonCode.java b/ethereumj-core/src/main/java/org/ethereum/net/message/ReasonCode.java index 05cbc32c..d38e183d 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/message/ReasonCode.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/message/ReasonCode.java @@ -9,39 +9,60 @@ import java.util.Map; */ public enum ReasonCode { - /** [0x00] Disconnect request by other peer */ + /** + * [0x00] Disconnect request by other peer + */ REQUESTED(0x00), - /** [0x01] */ + /** + * [0x01] + */ TCP_ERROR(0x01), - /** [0x02] Packets can not be parsed */ + /** + * [0x02] Packets can not be parsed + */ BAD_PROTOCOL(0x02), - /** [0x03] This peer is too slow or delivers unreliable data */ + /** + * [0x03] This peer is too slow or delivers unreliable data + */ USELESS_PEER(0x03), - /** [0x04] Already too many connections with other peers */ + /** + * [0x04] Already too many connections with other peers + */ TOO_MANY_PEERS(0x04), - /** [0x05] Already have a running connection with this peer */ + /** + * [0x05] Already have a running connection with this peer + */ ALREADY_CONNECTED(0x05), - /** [0x06] Version of the p2p protocol is not the same as ours */ + /** + * [0x06] Version of the p2p protocol is not the same as ours + */ INCOMPATIBLE_PROTOCOL(0x06), - /** [0x07] Peer identifies itself with the wrong networkId */ + /** + * [0x07] Peer identifies itself with the wrong networkId + */ INCOMPATIBLE_NETWORK(0x07), - /** [0x08] Peer quit voluntarily */ + /** + * [0x08] Peer quit voluntarily + */ PEER_QUITING(0x08), - /** [0xFF] Reason not specified */ + /** + * [0xFF] Reason not specified + */ UNKNOWN(0xFF); private int reason; private static final Map intToTypeMap = new HashMap<>(); + static { for (ReasonCode type : ReasonCode.values()) { intToTypeMap.put(type.reason, type); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/message/ShhMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/message/ShhMessage.java index 3a027ff9..8e185b1a 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/message/ShhMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/message/ShhMessage.java @@ -2,7 +2,8 @@ package org.ethereum.net.message; public abstract class ShhMessage extends Message { - public ShhMessage() {} + public ShhMessage() { + } public ShhMessage(byte[] encoded) { super(encoded); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/message/StaticMessages.java b/ethereumj-core/src/main/java/org/ethereum/net/message/StaticMessages.java index 0cffa5a2..19707394 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/message/StaticMessages.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/message/StaticMessages.java @@ -27,10 +27,10 @@ public class StaticMessages { public static final String PEER_ID = Hex.toHexString(HashUtil.randomPeerId()); - public final static PingMessage PING_MESSAGE = new PingMessage(); - public final static PongMessage PONG_MESSAGE = new PongMessage(); - public final static HelloMessage HELLO_MESSAGE = generateHelloMessage(); - public final static GetPeersMessage GET_PEERS_MESSAGE = new GetPeersMessage(); + public final static PingMessage PING_MESSAGE = new PingMessage(); + public final static PongMessage PONG_MESSAGE = new PongMessage(); + public final static HelloMessage HELLO_MESSAGE = generateHelloMessage(); + public final static GetPeersMessage GET_PEERS_MESSAGE = new GetPeersMessage(); public final static GetTransactionsMessage GET_TRANSACTIONS_MESSAGE = new GetTransactionsMessage(); public static final byte[] SYNC_TOKEN = Hex.decode("22400891"); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/p2p/DisconnectMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/p2p/DisconnectMessage.java index 01fb0334..75b38459 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/p2p/DisconnectMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/p2p/DisconnectMessage.java @@ -52,7 +52,7 @@ public class DisconnectMessage extends P2pMessage { } @Override - public P2pMessageCodes getCommand(){ + public P2pMessageCodes getCommand() { return P2pMessageCodes.DISCONNECT; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/p2p/GetPeersMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/p2p/GetPeersMessage.java index b93020b2..dcffa3bf 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/p2p/GetPeersMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/p2p/GetPeersMessage.java @@ -9,7 +9,9 @@ import org.spongycastle.util.encoders.Hex; */ public class GetPeersMessage extends P2pMessage { - /** GetPeers message is always a the same single command payload */ + /** + * GetPeers message is always a the same single command payload + */ private final static byte[] FIXED_PAYLOAD = Hex.decode("C104"); @Override @@ -18,7 +20,7 @@ public class GetPeersMessage extends P2pMessage { } @Override - public P2pMessageCodes getCommand(){ + public P2pMessageCodes getCommand() { return P2pMessageCodes.GET_PEERS; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/p2p/HelloMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/p2p/HelloMessage.java index c78e6a7b..7ca02c42 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/p2p/HelloMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/p2p/HelloMessage.java @@ -20,16 +20,26 @@ import java.util.List; */ public class HelloMessage extends P2pMessage { - /** The implemented version of the P2P protocol. */ + /** + * The implemented version of the P2P protocol. + */ private byte p2pVersion; - /** The underlying client. A user-readable string. */ + /** + * The underlying client. A user-readable string. + */ private String clientId; - /** A peer-network capability code, readable ASCII and 3 letters. - * Currently only "eth", "shh" and "bzz" are known. */ + /** + * A peer-network capability code, readable ASCII and 3 letters. + * Currently only "eth", "shh" and "bzz" are known. + */ private List capabilities; - /** The port on which the peer is listening for an incoming connection */ + /** + * The port on which the peer is listening for an incoming connection + */ private int listenPort; - /** The identity and public key of the peer */ + /** + * The identity and public key of the peer + */ private String peerId; public HelloMessage(byte[] encoded) { @@ -62,8 +72,8 @@ public class HelloMessage extends P2pMessage { this.capabilities = new ArrayList<>(); for (int i = 0; i < capabilityList.size(); i++) { - RLPElement capId = ((RLPList)capabilityList.get(i)).get(0); - RLPElement capVersion = ((RLPList)capabilityList.get(i)).get(1); + RLPElement capId = ((RLPList) capabilityList.get(i)).get(0); + RLPElement capVersion = ((RLPList) capabilityList.get(i)).get(1); String name = new String(capId.getRLPData()); byte version = capVersion.getRLPData() == null ? 0 : capVersion.getRLPData()[0]; @@ -89,7 +99,7 @@ public class HelloMessage extends P2pMessage { Capability capability = this.capabilities.get(i); capabilities[i] = RLP.encodeList( RLP.encodeElement(capability.getName().getBytes()), - RLP.encodeElement(new byte[] {capability.getVersion() })); + RLP.encodeElement(new byte[]{capability.getVersion()})); } byte[] capabilityList = RLP.encodeList(capabilities); byte[] peerPort = RLP.encodeInt(this.listenPort); @@ -131,7 +141,7 @@ public class HelloMessage extends P2pMessage { } @Override - public P2pMessageCodes getCommand(){ + public P2pMessageCodes getCommand() { return P2pMessageCodes.HELLO; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pHandler.java b/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pHandler.java index cc5c435e..e9b01629 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pHandler.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pHandler.java @@ -92,7 +92,7 @@ public class P2pHandler extends SimpleChannelInboundHandler { startTimers(); } - public void activate(){ + public void activate() { // logger.info("Incoming connection from: {}", ch.remoteAddress().toString()); @@ -100,7 +100,7 @@ public class P2pHandler extends SimpleChannelInboundHandler { worldManager.getListener().trace("P2P protocol activated"); } - public boolean isActive(){ + public boolean isActive() { return active; } @@ -112,7 +112,7 @@ public class P2pHandler extends SimpleChannelInboundHandler { if (P2pMessageCodes.inRange(msg.getCommand().asByte())) logger.info("P2PHandler invoke: [{}]", msg.getCommand()); - worldManager.getListener().trace(String.format( "P2PHandler invoke: [%s]", msg.getCommand())); + worldManager.getListener().trace(String.format("P2PHandler invoke: [%s]", msg.getCommand())); switch (msg.getCommand()) { case HELLO: @@ -139,7 +139,7 @@ public class P2pHandler extends SimpleChannelInboundHandler { processPeers(ctx, (PeersMessage) msg); if (peerDiscoveryMode && - !handshakeHelloMessage.getCapabilities().contains(Capability.ETH)){ + !handshakeHelloMessage.getCapabilities().contains(Capability.ETH)) { msgQueue.sendMessage(new DisconnectMessage(ReasonCode.REQUESTED)); killTimers(); ctx.close().sync(); @@ -172,21 +172,21 @@ public class P2pHandler extends SimpleChannelInboundHandler { worldManager.getPeerDiscovery().addPeers(peersMessage.getPeers()); } - private void sendGetPeers(){ - msgQueue.sendMessage( StaticMessages.GET_PEERS_MESSAGE ); + private void sendGetPeers() { + msgQueue.sendMessage(StaticMessages.GET_PEERS_MESSAGE); } private void sendPeers() { Set peers = worldManager.getPeerDiscovery().getPeers(); - if (lastPeersSent != null && peers.equals(lastPeersSent)){ + if (lastPeersSent != null && peers.equals(lastPeersSent)) { logger.info("No new peers discovered don't answer for GetPeers"); return; } Set peerSet = new HashSet<>(); - for (PeerInfo peer : peers){ + for (PeerInfo peer : peers) { new Peer(peer.getAddress(), peer.getPort(), peer.getPeerId()); } @@ -205,20 +205,19 @@ public class P2pHandler extends SimpleChannelInboundHandler { List capInCommon = new ArrayList<>(); for (Capability capability : msg.getCapabilities()) { if (HELLO_MESSAGE.getCapabilities().contains(capability)) { - if (capability.getName().equals(Capability.ETH)){ + if (capability.getName().equals(Capability.ETH)) { // Activate EthHandler for this peer EthHandler ethHandler = - (EthHandler)ctx.pipeline().get(Capability.ETH); + (EthHandler) ctx.pipeline().get(Capability.ETH); ethHandler.setPeerId(msg.getPeerId()); ethHandler.activate(); - } - else if (capability.getName().equals(Capability.SHH)){ + } else if (capability.getName().equals(Capability.SHH)) { // Activate ShhHandler for this peer ShhHandler shhHandler = - (ShhHandler)ctx.pipeline().get(Capability.SHH); + (ShhHandler) ctx.pipeline().get(Capability.SHH); shhHandler.activate(); } capInCommon.add(capability); @@ -239,15 +238,16 @@ public class P2pHandler extends SimpleChannelInboundHandler { /** * submit transaction to the network + * * @param tx - fresh transaction object */ - public void sendTransaction(Transaction tx ){ + public void sendTransaction(Transaction tx) { TransactionsMessage msg = new TransactionsMessage(tx); msgQueue.sendMessage(msg); } - public void sendNewBlock(Block block ){ + public void sendNewBlock(Block block) { NewBlockMessage msg = new NewBlockMessage(block, block.getDifficulty()); msgQueue.sendMessage(msg); @@ -296,7 +296,7 @@ public class P2pHandler extends SimpleChannelInboundHandler { */ } - public void killTimers(){ + public void killTimers() { timer.cancel(); timer.purge(); msgQueue.close(); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pMessage.java index a36dfb63..f03d7363 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pMessage.java @@ -5,7 +5,8 @@ import org.ethereum.net.p2p.P2pMessageCodes; public abstract class P2pMessage extends Message { - public P2pMessage() {} + public P2pMessage() { + } public P2pMessage(byte[] encoded) { super(encoded); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pMessageCodes.java b/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pMessageCodes.java index d2211096..83ee8587 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pMessageCodes.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/p2p/P2pMessageCodes.java @@ -8,6 +8,7 @@ import java.util.Map; *
    * The codes for these commands are the first byte in every packet. * ÐΞV + * * @see * https://github.com/ethereum/wiki/wiki/ÐΞVp2p-Wire-Protocol */ @@ -15,33 +16,45 @@ public enum P2pMessageCodes { /* P2P protocol */ - /** [0x00, P2P_VERSION, CLIEND_ID, CAPS, LISTEN_PORT, CLIENT_ID]
    + /** + * [0x00, P2P_VERSION, CLIEND_ID, CAPS, LISTEN_PORT, CLIENT_ID]
    * First packet sent over the connection, and sent once by both sides. - * No other messages may be sent until a Hello is received. */ + * No other messages may be sent until a Hello is received. + */ HELLO(0x00), - /** [0x01, REASON]
    Inform the peer that a disconnection is imminent; + /** + * [0x01, REASON]
    Inform the peer that a disconnection is imminent; * if received, a peer should disconnect immediately. When sending, * well-behaved hosts give their peers a fighting chance (read: wait 2 seconds) - * to disconnect to before disconnecting themselves. */ + * to disconnect to before disconnecting themselves. + */ DISCONNECT(0x01), - /** [0x02]
    Requests an immediate reply of Pong from the peer. */ + /** + * [0x02]
    Requests an immediate reply of Pong from the peer. + */ PING(0x02), - /** [0x03]
    Reply to peer's Ping packet. */ + /** + * [0x03]
    Reply to peer's Ping packet. + */ PONG(0x03), - /** [0x04]
    Request the peer to enumerate some known peers - * for us to connect to. This should include the peer itself. */ + /** + * [0x04]
    Request the peer to enumerate some known peers + * for us to connect to. This should include the peer itself. + */ GET_PEERS(0x04), - /** [0x05, [IP1, Port1, Id1], [IP2, Port2, Id2], ... ]
    + /** + * [0x05, [IP1, Port1, Id1], [IP2, Port2, Id2], ... ]
    * Specifies a number of known peers. IP is a 4-byte array 'ABCD' * that should be interpreted as the IP address A.B.C.D. * Port is a 2-byte array that should be interpreted as a * 16-bit big-endian integer. Id is the 512-bit hash that acts - * as the unique identifier of the node. */ + * as the unique identifier of the node. + */ PEERS(0x05), @@ -54,6 +67,7 @@ public enum P2pMessageCodes { private int cmd; private static final Map intToTypeMap = new HashMap<>(); + static { for (P2pMessageCodes type : P2pMessageCodes.values()) { intToTypeMap.put(type.cmd, type); @@ -69,7 +83,7 @@ public enum P2pMessageCodes { return type; } - public static boolean inRange(byte code){ + public static boolean inRange(byte code) { if (code >= HELLO.asByte() && code <= USER.asByte()) return true; diff --git a/ethereumj-core/src/main/java/org/ethereum/net/p2p/Peer.java b/ethereumj-core/src/main/java/org/ethereum/net/p2p/Peer.java index 45c15daa..31481ea0 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/p2p/Peer.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/p2p/Peer.java @@ -47,7 +47,7 @@ public class Peer { byte[] port = RLP.encodeInt(this.port); byte[] peerId = RLP.encodeElement(Hex.decode(this.peerId)); byte[][] encodedCaps = new byte[this.capabilities.size()][]; - for (int i = 0; i < this.capabilities.size()*2; i++) { + for (int i = 0; i < this.capabilities.size() * 2; i++) { encodedCaps[i] = RLP.encodeString(this.capabilities.get(i).getName()); encodedCaps[i] = RLP.encodeByte(this.capabilities.get(i).getVersion()); } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/p2p/PeersMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/p2p/PeersMessage.java index eacc6b84..9601d5e1 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/p2p/PeersMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/p2p/PeersMessage.java @@ -48,7 +48,7 @@ public class PeersMessage extends P2pMessage { int peerPort = ByteUtil.byteArrayToInt(portBytes); InetAddress address = InetAddress.getByAddress(ipBytes); - String peerId = peerIdRaw == null ? "" : Hex.toHexString(peerIdRaw); + String peerId = peerIdRaw == null ? "" : Hex.toHexString(peerIdRaw); Peer peer = new Peer(address, peerPort, peerId); peers.add(peer); } catch (UnknownHostException e) { @@ -80,7 +80,7 @@ public class PeersMessage extends P2pMessage { } @Override - public P2pMessageCodes getCommand(){ + public P2pMessageCodes getCommand() { return P2pMessageCodes.PEERS; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/p2p/PingMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/p2p/PingMessage.java index 3252a1d3..f9180b42 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/p2p/PingMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/p2p/PingMessage.java @@ -9,7 +9,9 @@ import org.spongycastle.util.encoders.Hex; */ public class PingMessage extends P2pMessage { - /** Ping message is always a the same single command payload */ + /** + * Ping message is always a the same single command payload + */ private static byte[] FIXED_PAYLOAD = Hex.decode("C102"); public byte[] getEncoded() { @@ -22,7 +24,7 @@ public class PingMessage extends P2pMessage { } @Override - public P2pMessageCodes getCommand(){ + public P2pMessageCodes getCommand() { return P2pMessageCodes.PING; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/p2p/PongMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/p2p/PongMessage.java index 5b50ea8d..dfcf93fc 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/p2p/PongMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/p2p/PongMessage.java @@ -10,7 +10,9 @@ import org.spongycastle.util.encoders.Hex; */ public class PongMessage extends P2pMessage { - /** Pong message is always a the same single command payload */ + /** + * Pong message is always a the same single command payload + */ private static byte[] FIXED_PAYLOAD = Hex.decode("C103"); @Override @@ -24,7 +26,7 @@ public class PongMessage extends P2pMessage { } @Override - public P2pMessageCodes getCommand(){ + public P2pMessageCodes getCommand() { return P2pMessageCodes.PONG; } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/DiscoveryChannel.java b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/DiscoveryChannel.java index 03aaec99..81ed5037 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/DiscoveryChannel.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/DiscoveryChannel.java @@ -30,6 +30,7 @@ import static org.ethereum.config.SystemProperties.CONFIG; /** * This class creates the connection to an remote address using the Netty framework + * * @see http://netty.io */ @Component @@ -93,7 +94,7 @@ public class DiscoveryChannel { b.handler( - new ChannelInitializer(){ + new ChannelInitializer() { @Override protected void initChannel(NioSocketChannel ch) throws Exception { @@ -128,7 +129,7 @@ public class DiscoveryChannel { } finally { workerGroup.shutdownGracefully(); - if (!peerDiscoveryMode){ + if (!peerDiscoveryMode) { // EthereumListener listener = WorldManager.getInstance().getListener(); // listener.onPeerDisconnect(host, port); } @@ -136,12 +137,11 @@ public class DiscoveryChannel { } } - public HelloMessage getHelloHandshake(){ + public HelloMessage getHelloHandshake() { return p2pHandler.getHandshakeHelloMessage(); } - public StatusMessage getStatusHandshake() - { + public StatusMessage getStatusHandshake() { return ethHandler.getHandshakeStatusMessage(); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/PeerDiscovery.java b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/PeerDiscovery.java index 0b07ab52..cd004185 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/PeerDiscovery.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/PeerDiscovery.java @@ -93,7 +93,7 @@ public class PeerDiscovery { for (final Peer newPeer : newPeers) { PeerInfo peerInfo = new PeerInfo(newPeer.getAddress(), newPeer.getPort(), newPeer.getPeerId()); - if (started.get() && !peers.contains(peerInfo )){ + if (started.get() && !peers.contains(peerInfo)) { startWorker(peerInfo); } peers.add(peerInfo); @@ -103,8 +103,8 @@ public class PeerDiscovery { public void addPeers(Collection newPeers) { synchronized (peers) { - peers.addAll(newPeers); - } + peers.addAll(newPeers); + } } private void startWorker(PeerInfo peerInfo) { @@ -115,12 +115,12 @@ public class PeerDiscovery { executorPool.execute(workerThread); } - public List parsePeerDiscoveryIpList(final String peerDiscoveryIpList){ + public List parsePeerDiscoveryIpList(final String peerDiscoveryIpList) { - final List ipList = Arrays.asList( peerDiscoveryIpList.split(",") ); + final List ipList = Arrays.asList(peerDiscoveryIpList.split(",")); final List peers = new ArrayList<>(); - for (String ip : ipList){ + for (String ip : ipList) { String[] addr = ip.trim().split(":"); String ip_trim = addr[0]; String port_trim = addr[1]; diff --git a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/PeerInfo.java b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/PeerInfo.java index ec04cbd2..d53a1306 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/PeerInfo.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/PeerInfo.java @@ -20,7 +20,7 @@ public class PeerInfo { private String peerId; private List capabilities; - private HelloMessage handshakeHelloMessage; + private HelloMessage handshakeHelloMessage; private StatusMessage statusMessage; private transient boolean isOnline = false; @@ -77,7 +77,7 @@ public class PeerInfo { .append(" port=").append(getPort()) .append(" peerId=").append(getPeerId()).append("] \n") .append(this.handshakeHelloMessage == null ? "" : handshakeHelloMessage + "\n") - .append(this.statusMessage == null ? "" : statusMessage + "\n"); + .append(this.statusMessage == null ? "" : statusMessage + "\n"); return sb.toString(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/WorkerThread.java b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/WorkerThread.java index 7a59cf8f..2b23e421 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/WorkerThread.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/WorkerThread.java @@ -30,7 +30,7 @@ public class WorkerThread implements Runnable { public WorkerThread() { } - public void init(PeerInfo peer, ThreadPoolExecutor poolExecutor){ + public void init(PeerInfo peer, ThreadPoolExecutor poolExecutor) { this.peerInfo = peer; this.poolExecutor = poolExecutor; } @@ -54,7 +54,7 @@ public class WorkerThread implements Runnable { peerInfo.setOnline(true); peerInfo.setHandshakeHelloMessage(discoveryChannel.getHelloHandshake()); - peerInfo.setStatusMessage( discoveryChannel.getStatusHandshake() ); + peerInfo.setStatusMessage(discoveryChannel.getStatusHandshake()); logger.info("Peer is online: [{}] ", peerInfo); @@ -72,7 +72,7 @@ public class WorkerThread implements Runnable { } } - private void sleep(long milliseconds){ + private void sleep(long milliseconds) { try { Thread.sleep(milliseconds); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/server/Channel.java b/ethereumj-core/src/main/java/org/ethereum/net/server/Channel.java index adee1c27..6af9efdf 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/server/Channel.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/server/Channel.java @@ -52,7 +52,7 @@ public class Channel { public Channel() { } - public void init(){ + public void init() { p2pHandler.setMsgQueue(msgQueue); ethHandler.setMsgQueue(msgQueue); shhHandler.setMsgQueue(msgQueue); @@ -80,27 +80,27 @@ public class Channel { return messageEncoder; } - public void sendTransaction(Transaction tx){ + public void sendTransaction(Transaction tx) { ethHandler.sendTransaction(tx); } - public void sendNewBlock(Block block){ + public void sendNewBlock(Block block) { // 1. check by best block send or not to send ethHandler.sendNewBlock(block); } - public boolean isSync(){ + public boolean isSync() { return ethHandler.getSyncStatus() == EthHandler.SyncSatus.SYNC_DONE; } - public BigInteger getTotalDifficulty(){ + public BigInteger getTotalDifficulty() { return ethHandler.getTotalDifficulty(); } - public void ethSync(){ + public void ethSync() { ethHandler.doSync(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/server/ChannelManager.java b/ethereumj-core/src/main/java/org/ethereum/net/server/ChannelManager.java index 56adc75c..9f15b441 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/server/ChannelManager.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/server/ChannelManager.java @@ -36,63 +36,63 @@ public class ChannelManager { @PostConstruct - public void init(){ + public void init() { scheduleChannelCollector(); } - public void recvTransaction(){ + public void recvTransaction() { // ??? } - public void recvBlock(){ // todo: + public void recvBlock() { // todo: // 1. Check in the cache if the hash exist // 2. Exist: go and send it to the queue } - public void sendTransaction(Transaction tx){ - for (Channel channel : channels){ + public void sendTransaction(Transaction tx) { + for (Channel channel : channels) { channel.sendTransaction(tx); } } - public void sendNewBlock(Block block){ + public void sendNewBlock(Block block) { // 1. Go over all channels and send the block - for (Channel channel : channels){ + for (Channel channel : channels) { channel.sendNewBlock(block); } } - public void addChannel(Channel channel){ - synchronized (channels){ + public void addChannel(Channel channel) { + synchronized (channels) { channels.add(channel); } } - public boolean isAllSync(){ + public boolean isAllSync() { boolean result = true; - for (Channel channel : channels){ + for (Channel channel : channels) { result &= channel.isSync(); } return result; } - public void scheduleChannelCollector(){ + public void scheduleChannelCollector() { inactivesCollector.scheduleAtFixedRate(new TimerTask() { public void run() { Iterator iter = channels.iterator(); - while(iter.hasNext()){ + while (iter.hasNext()) { Channel channel = iter.next(); - if(!channel.p2pHandler.isActive()){ + if (!channel.p2pHandler.isActive()) { iter.remove(); logger.info("Channel removed: {}", channel.p2pHandler.getHandshakeHelloMessage()); } } - if (channels.size() == 0){ + if (channels.size() == 0) { worldManager.getListener().onNoConnections(); } } @@ -102,10 +102,10 @@ public class ChannelManager { public void ethSync() { Channel bestChannel = channels.get(0); - for (Channel channel : channels){ + for (Channel channel : channels) { if (bestChannel.getTotalDifficulty(). - compareTo(channel.getTotalDifficulty()) < 0 ){ + compareTo(channel.getTotalDifficulty()) < 0) { bestChannel = channel; } } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhHandler.java b/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhHandler.java index 7ee6925f..64a41f58 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhHandler.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhHandler.java @@ -14,8 +14,6 @@ import org.springframework.stereotype.Component; * Process the messages between peers with 'shh' capability on the network. * * Peers with 'shh' capability can send/receive: - * - * */ @Component @Scope("prototype") @@ -31,7 +29,7 @@ public class ShhHandler extends SimpleChannelInboundHandler { @Autowired WorldManager worldManager; - public ShhHandler(){ + public ShhHandler() { } public ShhHandler(MessageQueue msgQueue) { @@ -46,7 +44,7 @@ public class ShhHandler extends SimpleChannelInboundHandler { if (ShhMessageCodes.inRange(msg.getCommand().asByte())) logger.info("ShhHandler invoke: [{}]", msg.getCommand()); - worldManager.getListener().trace(String.format( "ShhHandler invoke: [%s]", msg.getCommand())); + worldManager.getListener().trace(String.format("ShhHandler invoke: [%s]", msg.getCommand())); switch (msg.getCommand()) { case STATUS: @@ -77,7 +75,7 @@ public class ShhHandler extends SimpleChannelInboundHandler { logger.debug("handlerRemoved: ... "); } - public void activate(){ + public void activate() { logger.info("SHH protocol activated"); worldManager.getListener().trace("SHH protocol activated"); this.active = true; diff --git a/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhMessage.java b/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhMessage.java index 53617bc6..b5c34fd7 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhMessage.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhMessage.java @@ -4,7 +4,8 @@ import org.ethereum.net.message.Message; public abstract class ShhMessage extends Message { - public ShhMessage() {} + public ShhMessage() { + } public ShhMessage(byte[] encoded) { super(encoded); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhMessageCodes.java b/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhMessageCodes.java index 817bb1e0..d6bdf8e2 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhMessageCodes.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/shh/ShhMessageCodes.java @@ -15,25 +15,36 @@ public enum ShhMessageCodes { /* Whisper Protocol */ - /** [+0x00] */ + /** + * [+0x00] + */ STATUS(0x00), - /** [+0x01] */ + /** + * [+0x01] + */ MESSAGE(0x01), - /** [+0x02] */ + /** + * [+0x02] + */ ADD_FILTER(0x02), - /** [+0x03] */ + /** + * [+0x03] + */ REMOVE_FILTER(0x03), - /** [+0x04] */ + /** + * [+0x04] + */ PACKET_COUNT(0x04); static byte OFFSET = 0; private int cmd; private static final Map intToTypeMap = new HashMap<>(); + static { for (ShhMessageCodes type : ShhMessageCodes.values()) { intToTypeMap.put(type.cmd, type); @@ -49,11 +60,11 @@ public enum ShhMessageCodes { return type; } - public static void setOffset(byte offset){ + public static void setOffset(byte offset) { ShhMessageCodes.OFFSET = offset; } - public static boolean inRange(byte code){ + public static boolean inRange(byte code) { if (code >= STATUS.asByte() && code <= PACKET_COUNT.asByte()) return true; @@ -62,6 +73,6 @@ public enum ShhMessageCodes { } public byte asByte() { - return (byte) (cmd + OFFSET); + return (byte) (cmd + OFFSET); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/net/submit/TransactionExecutor.java b/ethereumj-core/src/main/java/org/ethereum/net/submit/TransactionExecutor.java index d601fb5d..d829d823 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/submit/TransactionExecutor.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/submit/TransactionExecutor.java @@ -15,6 +15,7 @@ public class TransactionExecutor { static { instance = new TransactionExecutor(); } + public static TransactionExecutor instance; private ExecutorService executor = Executors.newFixedThreadPool(1); diff --git a/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageDecoder.java b/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageDecoder.java index 510e84d1..c3592b84 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageDecoder.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageDecoder.java @@ -62,10 +62,10 @@ public class MessageDecoder extends ByteToMessageDecoder { long syncToken = in.readUnsignedInt(); - if (!((syncToken >> 24 & 0xFF) == 0x22 && - (syncToken >> 16 & 0xFF) == 0x40 && - (syncToken >> 8 & 0xFF) == 0x08 && - (syncToken & 0xFF) == 0x91 )) { + if (!((syncToken >> 24 & 0xFF) == 0x22 && + (syncToken >> 16 & 0xFF) == 0x40 && + (syncToken >> 8 & 0xFF) == 0x08 && + (syncToken & 0xFF) == 0x91)) { // TODO: Drop frame and continue. // A collision can happen (although rare) diff --git a/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageEncoder.java b/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageEncoder.java index 8cb3fa28..03a02997 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageEncoder.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/wire/MessageEncoder.java @@ -24,7 +24,7 @@ import org.springframework.stereotype.Component; public class MessageEncoder extends MessageToByteEncoder { private static final Logger loggerWire = LoggerFactory.getLogger("wire"); - private static final Logger loggerNet = LoggerFactory.getLogger("net"); + private static final Logger loggerNet = LoggerFactory.getLogger("net"); @Autowired WorldManager worldManager; diff --git a/ethereumj-core/src/main/java/org/ethereum/serpent/ParserGenerator.java b/ethereumj-core/src/main/java/org/ethereum/serpent/ParserGenerator.java index 27a70eba..231fb71f 100644 --- a/ethereumj-core/src/main/java/org/ethereum/serpent/ParserGenerator.java +++ b/ethereumj-core/src/main/java/org/ethereum/serpent/ParserGenerator.java @@ -6,6 +6,7 @@ import org.apache.maven.plugin.MojoFailureException; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 25/04/14 17:06 */ @@ -17,7 +18,7 @@ public class ParserGenerator { String grammarName = userDir + "\\src\\main\\antlr4\\org\\ethereum\\serpent\\Serpent.g4"; - String options[] = {grammarName, "-visitor", "-package", "org.ethereum.serpent"}; + String options[] = {grammarName, "-visitor", "-package", "org.ethereum.serpent"}; Tool tool = new Tool(options); tool.outputDirectory = userDir + "\\src\\main\\java\\org\\ethereum\\serpent\\"; tool.processGrammarsOnCommandLine(); diff --git a/ethereumj-core/src/main/java/org/ethereum/serpent/ParserUtils.java b/ethereumj-core/src/main/java/org/ethereum/serpent/ParserUtils.java index 50f5556f..a7cdd44c 100644 --- a/ethereumj-core/src/main/java/org/ethereum/serpent/ParserUtils.java +++ b/ethereumj-core/src/main/java/org/ethereum/serpent/ParserUtils.java @@ -5,51 +5,53 @@ import org.antlr.v4.runtime.atn.PredictionMode; import org.antlr.v4.runtime.misc.Nullable; public class ParserUtils { - private ParserUtils() {} - - public static L getLexer(Class lexerClass, String source) { - CharStream input = new ANTLRInputStream(source); - L lexer; - try { - lexer = lexerClass.getConstructor(CharStream.class).newInstance(input); - } catch (Exception e) { - throw new IllegalArgumentException("couldn't invoke lexer constructor", e); + private ParserUtils() { } - lexer.addErrorListener(new AntlrFailureListener()); - return lexer; - } - public static

    P getParser(Class lexerClass, Class

    parserClass, String source) { - Lexer lexer = getLexer(lexerClass, source); - TokenStream tokens = new CommonTokenStream(lexer); - - P parser; - try { - parser = parserClass.getConstructor(TokenStream.class).newInstance(tokens); - } catch (Exception e) { - throw new IllegalArgumentException("couldn't invoke parser constructor", e); + public static L getLexer(Class lexerClass, String source) { + CharStream input = new ANTLRInputStream(source); + L lexer; + try { + lexer = lexerClass.getConstructor(CharStream.class).newInstance(input); + } catch (Exception e) { + throw new IllegalArgumentException("couldn't invoke lexer constructor", e); + } + lexer.addErrorListener(new AntlrFailureListener()); + return lexer; } - parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION); - parser.removeErrorListeners(); // don't spit to stderr - parser.addErrorListener(new DiagnosticErrorListener()); - parser.addErrorListener(new AntlrFailureListener()); - return parser; - } + public static

    P getParser(Class lexerClass, Class

    parserClass, String + source) { + Lexer lexer = getLexer(lexerClass, source); + TokenStream tokens = new CommonTokenStream(lexer); - private static class AntlrFailureListener extends BaseErrorListener { - @Override - public void syntaxError(Recognizer recognizer, @Nullable Object offendingSymbol, int line, - int charPositionInLine, String msg, @Nullable RecognitionException e) { - throw new AntlrParseException(line, charPositionInLine, msg, e); + P parser; + try { + parser = parserClass.getConstructor(TokenStream.class).newInstance(tokens); + } catch (Exception e) { + throw new IllegalArgumentException("couldn't invoke parser constructor", e); + } + parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION); + parser.removeErrorListeners(); // don't spit to stderr + parser.addErrorListener(new DiagnosticErrorListener()); + parser.addErrorListener(new AntlrFailureListener()); + + return parser; } - } - public static class AntlrParseException extends RuntimeException { - public AntlrParseException(int line, int posInLine, String msg, Throwable cause) { - // posInLine comes in 0-indexed, but we want to 1-index it so it lines up with what editors say (they - // tend to 1-index) - super(String.format("at line %d column %d: %s", line, posInLine+1, msg), cause); + private static class AntlrFailureListener extends BaseErrorListener { + @Override + public void syntaxError(Recognizer recognizer, @Nullable Object offendingSymbol, int line, + int charPositionInLine, String msg, @Nullable RecognitionException e) { + throw new AntlrParseException(line, charPositionInLine, msg, e); + } + } + + public static class AntlrParseException extends RuntimeException { + public AntlrParseException(int line, int posInLine, String msg, Throwable cause) { + // posInLine comes in 0-indexed, but we want to 1-index it so it lines up with what editors say (they + // tend to 1-index) + super(String.format("at line %d column %d: %s", line, posInLine + 1, msg), cause); + } } - } } diff --git a/ethereumj-core/src/main/java/org/ethereum/serpent/SerpentCompiler.java b/ethereumj-core/src/main/java/org/ethereum/serpent/SerpentCompiler.java index 1f2ff17a..50c26e60 100644 --- a/ethereumj-core/src/main/java/org/ethereum/serpent/SerpentCompiler.java +++ b/ethereumj-core/src/main/java/org/ethereum/serpent/SerpentCompiler.java @@ -18,6 +18,7 @@ import java.util.regex.Pattern; /** * www.ethereumJ.com + * * @author Roman Mandeleil * Created on: 13/05/14 19:37 */ @@ -85,7 +86,7 @@ public class SerpentCompiler { boolean skiping = false; for (int i = 0; i < lexaList.size(); ++i) { - String lexa = lexaList.get(i); + String lexa = lexaList.get(i); { // skiping the [asm asm] block if (lexa.equals("asm]")) { @@ -105,8 +106,8 @@ public class SerpentCompiler { } if (OpCode.contains(lexa) || - lexa.contains("REF_") || - lexa.contains("LABEL_")) continue; + lexa.contains("REF_") || + lexa.contains("LABEL_")) continue; int bytesNum = ByteUtil.numBytes(lexa); @@ -125,7 +126,7 @@ public class SerpentCompiler { // encode ref for 5 bytes for (int i = 0; i < lexaList.size(); ++i) { - String lexa = lexaList.get(i); + String lexa = lexaList.get(i); if (!lexa.contains("REF_")) continue; lexaList.add(i + 1, lexa); lexaList.add(i + 2, lexa); @@ -139,7 +140,7 @@ public class SerpentCompiler { for (int i = 0; i < lexaList.size(); ++i) { - String lexa = lexaList.get(i); + String lexa = lexaList.get(i); if (!lexa.contains("LABEL_")) continue; String label = lexaList.remove(i); @@ -154,7 +155,7 @@ public class SerpentCompiler { // encode all ref occurrence for (int i = 0; i < lexaList.size(); ++i) { - String lexa = lexaList.get(i); + String lexa = lexaList.get(i); if (!lexa.contains("REF_")) continue; String ref = lexaList.remove(i); @@ -169,7 +170,7 @@ public class SerpentCompiler { lexaList.add(i, pos.toString()); - for (int j = 0; j < (4 - bytesNum) ; ++j) + for (int j = 0; j < (4 - bytesNum); ++j) lexaList.add(i, "0"); lexaList.add(i, "PUSH4"); @@ -194,7 +195,6 @@ public class SerpentCompiler { } /** - * * @param code * @param init * @return encoded bytes @@ -212,12 +212,12 @@ public class SerpentCompiler { } // calc real code start position (after the init header) - int pos = 10 + numBytes * 2; - if (init != null) pos+=init.length; + int pos = 10 + numBytes * 2; + if (init != null) pos += init.length; // @push_len @len PUSH1 @src_start PUSH1 0 CODECOPY @push_len @len 0 PUSH1 0 RETURN - String header = String.format("[asm %s %s PUSH1 %d PUSH1 0 CODECOPY %s %s PUSH1 0 RETURN asm]", - "PUSH" + numBytes, sb.toString(), pos , "PUSH" + numBytes, sb.toString()); + String header = String.format("[asm %s %s PUSH1 %d PUSH1 0 CODECOPY %s %s PUSH1 0 RETURN asm]", + "PUSH" + numBytes, sb.toString(), pos, "PUSH" + numBytes, sb.toString()); byte[] headerMachine = compileAssemblyToMachine(header); diff --git a/ethereumj-core/src/main/java/org/ethereum/serpent/SerpentToAssemblyCompiler.java b/ethereumj-core/src/main/java/org/ethereum/serpent/SerpentToAssemblyCompiler.java index 0722a260..ad9009b2 100644 --- a/ethereumj-core/src/main/java/org/ethereum/serpent/SerpentToAssemblyCompiler.java +++ b/ethereumj-core/src/main/java/org/ethereum/serpent/SerpentToAssemblyCompiler.java @@ -14,13 +14,14 @@ import java.util.regex.Pattern; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 05/05/14 13:41 */ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { private int labelIndex = 0; - private List vars = new ArrayList<>(); + private List vars = new ArrayList<>(); private Map arraysSize = new HashMap<>(); private List arraysIndex = new ArrayList<>(); @@ -29,51 +30,51 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { public String visitParse(@NotNull SerpentParser.ParseContext ctx) { String codeBlock = visit(ctx.block()); - int memSize = vars.size() * 32 - ( vars.size() > 0 ? 1 : 0); + int memSize = vars.size() * 32 - (vars.size() > 0 ? 1 : 0); String initMemCodeBlock = ""; - if ( ! arraysSize.isEmpty() && vars.size() > 0) + if (!arraysSize.isEmpty() && vars.size() > 0) initMemCodeBlock = String.format(" 0 %d MSTORE8 ", memSize); if (memSize == 0) - codeBlock= codeBlock.replace("@vars_table@", "0"); + codeBlock = codeBlock.replace("@vars_table@", "0"); else - codeBlock= codeBlock.replace("@vars_table@", memSize + 1 + ""); + codeBlock = codeBlock.replace("@vars_table@", memSize + 1 + ""); - return initMemCodeBlock + codeBlock; + return initMemCodeBlock + codeBlock; } @Override public String visitParse_init_code_block(@NotNull SerpentParser.Parse_init_code_blockContext ctx) { String initBlock = visit(ctx.block(0)); - int memSize = vars.size() * 32 - ( vars.size() > 0 ? 1 : 0); + int memSize = vars.size() * 32 - (vars.size() > 0 ? 1 : 0); String initMemInitBlock = ""; - if ( ! arraysSize.isEmpty() && vars.size() > 0) + if (!arraysSize.isEmpty() && vars.size() > 0) initMemInitBlock = String.format(" 0 %d MSTORE8 ", memSize); if (memSize == 0) - initBlock= initBlock.replace("@vars_table@", "0"); + initBlock = initBlock.replace("@vars_table@", "0"); else - initBlock= initBlock.replace("@vars_table@", memSize + 1 + ""); + initBlock = initBlock.replace("@vars_table@", memSize + 1 + ""); vars.clear(); String codeBlock = visit(ctx.block(1)); - memSize = vars.size() * 32 - ( vars.size() > 0 ? 1 : 0); + memSize = vars.size() * 32 - (vars.size() > 0 ? 1 : 0); if (memSize == 0) - codeBlock= codeBlock.replace("@vars_table@", "0"); + codeBlock = codeBlock.replace("@vars_table@", "0"); else - codeBlock= codeBlock.replace("@vars_table@", memSize + 1 + ""); + codeBlock = codeBlock.replace("@vars_table@", memSize + 1 + ""); String initMemCodeBlock = ""; - if ( ! arraysSize.isEmpty() && vars.size() > 0) + if (!arraysSize.isEmpty() && vars.size() > 0) initMemCodeBlock = String.format(" 0 %d MSTORE8 ", memSize); return String.format(" [init %s %s init] [code %s %s code] ", initMemInitBlock, initBlock, - initMemCodeBlock, codeBlock); + initMemCodeBlock, codeBlock); } @Override @@ -81,7 +82,7 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { StringBuffer retCode = new StringBuffer(); - int endOfStmtLabel = labelIndex++ ; + int endOfStmtLabel = labelIndex++; // if body SerpentParser.BlockContext ifBlock = (SerpentParser.BlockContext) ctx.getChild(4); @@ -155,7 +156,8 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String retCode = String.format(" LABEL_%d %s NOT REF_%d JUMPI %s REF_%d JUMP LABEL_%d ", - whileStartRef, visitCondition(whileCondition), whileEndRef, visitBlock(whileBlock), whileStartRef, whileEndRef); + whileStartRef, visitCondition(whileCondition), whileEndRef, visitBlock(whileBlock), + whileStartRef, whileEndRef); return retCode; } @@ -180,9 +182,9 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { addr = vars.indexOf(varName); if (addr == -1) { - throw new UnassignVarException(varName); + throw new UnassignVarException(varName); } - return String.format(" %d MLOAD ", addr * 32); + return String.format(" %d MLOAD ", addr * 32); } @Override @@ -281,20 +283,20 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { i += 32; } - return String.format(" MSIZE 32 ADD MSIZE %s %d SWAP MSTORE ", arrayInit, arraySize); + return String.format(" MSIZE 32 ADD MSIZE %s %d SWAP MSTORE ", arrayInit, arraySize); } @Override public String visitArray_assign(@NotNull SerpentParser.Array_assignContext ctx) { - int order = this.arraysIndex.indexOf( ctx.VAR().toString()); + int order = this.arraysIndex.indexOf(ctx.VAR().toString()); if (order == -1) { throw new Error("array with that name was not defined"); } //calcAllocatedBefore(); int allocSize = 0; - for (int i = 0; i < order; ++i ) { + for (int i = 0; i < order; ++i) { String var = arraysIndex.get(i); allocSize += arraysSize.get(var); } @@ -308,20 +310,20 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { @Override public String visitArray_retreive(@NotNull SerpentParser.Array_retreiveContext ctx) { - int order = this.arraysIndex.indexOf( ctx.VAR().toString()); + int order = this.arraysIndex.indexOf(ctx.VAR().toString()); if (order == -1) { throw new Error("array with that name was not defined"); } int allocSize = 32; - for (int i = 0; i < order; ++i ) { + for (int i = 0; i < order; ++i) { String var = arraysIndex.get(i); allocSize += arraysSize.get(var); } String index = visit(ctx.int_val()); - return String.format(" 32 %s MUL %d ADD @vars_table@ ADD MLOAD ", index, allocSize ); + return String.format(" 32 %s MUL %d ADD @vars_table@ ADD MLOAD ", index, allocSize); } @Override @@ -332,13 +334,20 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand1 = visit(ctx.mul_expr()); switch (ctx.OP_MUL().getText().toLowerCase()) { - case "*": return operand0 + " " + operand1 + " MUL"; - case "/": return operand0 + " " + operand1 + " DIV"; - case "^": return operand0 + " " + operand1 + " EXP"; - case "%": return operand0 + " " + operand1 + " MOD"; - case "#/": return operand0 + " " + operand1 + " SDIV"; - case "#%": return operand0 + " " + operand1 + " SMOD"; - default: throw new UnknownOperandException(ctx.OP_MUL().getText()); + case "*": + return operand0 + " " + operand1 + " MUL"; + case "/": + return operand0 + " " + operand1 + " DIV"; + case "^": + return operand0 + " " + operand1 + " EXP"; + case "%": + return operand0 + " " + operand1 + " MOD"; + case "#/": + return operand0 + " " + operand1 + " SDIV"; + case "#%": + return operand0 + " " + operand1 + " SMOD"; + default: + throw new UnknownOperandException(ctx.OP_MUL().getText()); } } @@ -351,9 +360,12 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand1 = visit(ctx.add_expr()); switch (ctx.OP_ADD().getText().toLowerCase()) { - case "+": return operand0 + " " + operand1 + " ADD"; - case "-": return operand0 + " " + operand1 + " SUB"; - default: throw new UnknownOperandException(ctx.OP_ADD().getText()); + case "+": + return operand0 + " " + operand1 + " ADD"; + case "-": + return operand0 + " " + operand1 + " SUB"; + default: + throw new UnknownOperandException(ctx.OP_ADD().getText()); } } @@ -366,11 +378,16 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand1 = visit(ctx.add_expr()); switch (ctx.OP_REL().getText().toLowerCase()) { - case "<": return operand1 + " " + operand0 + " LT"; - case ">": return operand1 + " " + operand0 + " GT"; - case ">=": return operand1 + " " + operand0 + " LT NOT"; - case "<=": return operand1 + " " + operand0 + " GT NOT"; - default: throw new UnknownOperandException(ctx.OP_REL().getText()); + case "<": + return operand1 + " " + operand0 + " LT"; + case ">": + return operand1 + " " + operand0 + " GT"; + case ">=": + return operand1 + " " + operand0 + " LT NOT"; + case "<=": + return operand1 + " " + operand0 + " GT NOT"; + default: + throw new UnknownOperandException(ctx.OP_REL().getText()); } } @@ -383,9 +400,12 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand1 = visit(ctx.eq_exp()); switch (ctx.OP_EQ().getText().toLowerCase()) { - case "==": return operand0 + " " + operand1 + " EQ"; - case "!=": return operand0 + " " + operand1 + " EQ NOT"; - default: throw new UnknownOperandException(ctx.OP_EQ().getText()); + case "==": + return operand0 + " " + operand1 + " EQ"; + case "!=": + return operand0 + " " + operand1 + " EQ NOT"; + default: + throw new UnknownOperandException(ctx.OP_EQ().getText()); } } @@ -398,8 +418,10 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand1 = visit(ctx.and_exp()); switch (ctx.OP_AND().getText().toLowerCase()) { - case "&": return operand0 + " " + operand1 + " AND"; - default: throw new UnknownOperandException(ctx.OP_AND().getText()); + case "&": + return operand0 + " " + operand1 + " AND"; + default: + throw new UnknownOperandException(ctx.OP_AND().getText()); } } @@ -412,8 +434,10 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand1 = visit(ctx.ex_or_exp()); switch (ctx.OP_EX_OR().getText().toLowerCase()) { - case "xor": return operand0 + " " + operand1 + " XOR"; - default: throw new UnknownOperandException(ctx.OP_EX_OR().getText()); + case "xor": + return operand0 + " " + operand1 + " XOR"; + default: + throw new UnknownOperandException(ctx.OP_EX_OR().getText()); } } @@ -426,8 +450,10 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand1 = visit(ctx.in_or_exp()); switch (ctx.OP_IN_OR().getText().toLowerCase()) { - case "|": return operand0 + " " + operand1 + " OR"; - default: throw new UnknownOperandException(ctx.OP_IN_OR().getText()); + case "|": + return operand0 + " " + operand1 + " OR"; + default: + throw new UnknownOperandException(ctx.OP_IN_OR().getText()); } } @@ -440,9 +466,12 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand1 = visit(ctx.log_and_exp()); switch (ctx.OP_LOG_AND().getText().toLowerCase()) { - case "and": return operand0 + " " + operand1 + " NOT NOT MUL"; - case "&&": return operand0 + " " + operand1 + " NOT NOT MUL"; - default: throw new UnknownOperandException(ctx.OP_LOG_AND().getText()); + case "and": + return operand0 + " " + operand1 + " NOT NOT MUL"; + case "&&": + return operand0 + " " + operand1 + " NOT NOT MUL"; + default: + throw new UnknownOperandException(ctx.OP_LOG_AND().getText()); } } @@ -455,9 +484,12 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand1 = visit(ctx.log_or_exp()); switch (ctx.OP_LOG_OR().getText().toLowerCase()) { - case "||": return operand0 + " " + operand1 + " DUP 4 PC ADD JUMPI POP SWAP POP"; - case "or": return operand0 + " " + operand1 + " DUP 4 PC ADD JUMPI POP SWAP POP"; - default: throw new UnknownOperandException(ctx.OP_LOG_OR().getText()); + case "||": + return operand0 + " " + operand1 + " DUP 4 PC ADD JUMPI POP SWAP POP"; + case "or": + return operand0 + " " + operand1 + " DUP 4 PC ADD JUMPI POP SWAP POP"; + default: + throw new UnknownOperandException(ctx.OP_LOG_OR().getText()); } } @@ -536,7 +568,7 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand0 = visit(ctx.expression()); - return String.format(" %s MSIZE SWAP MSIZE MSTORE 32 SWAP RETURN ", operand0); + return String.format(" %s MSIZE SWAP MSIZE MSTORE 32 SWAP RETURN ", operand0); } @Override @@ -566,7 +598,7 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand0 = visit(ctx.expression()); - return String.format("%s 32 MUL CALLDATALOAD ", operand0); + return String.format("%s 32 MUL CALLDATALOAD ", operand0); } public String visitMsg_func(@NotNull SerpentParser.Msg_funcContext ctx, String varName) { @@ -574,22 +606,22 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { // msg_func: 'msg' '(' int_val ',' int_val ',' int_val ',' arr_def ',' int_val ',' int_val')' ; // msg_func: 'msg' '(' [gas] ',' [to] ',' [value] ',' arr_def ',' [in_len] ',' [out_len]')' ; - String operand0 = visit(ctx.int_val(0)); - String operand1 = visit(ctx.int_val(1)); - String operand2 = visit(ctx.int_val(2)); + String operand0 = visit(ctx.int_val(0)); + String operand1 = visit(ctx.int_val(1)); + String operand2 = visit(ctx.int_val(2)); String loadInData = visit(ctx.arr_def()); - String inSizeCallParam = visit(ctx.int_val(3)); - String outSizeCallParam = visit(ctx.int_val(4)); + String inSizeCallParam = visit(ctx.int_val(3)); + String outSizeCallParam = visit(ctx.int_val(4)); // TODO: 1. allocate out_memory and push ptr // TODO: 2. push ptr for in_memory allocated String randomArrayName = new String(HashUtil.randomPeerId()); - int inSize = Integer.parseInt( inSizeCallParam ); - int outSize = Integer.parseInt( outSizeCallParam ); + int inSize = Integer.parseInt(inSizeCallParam); + int outSize = Integer.parseInt(outSizeCallParam); arraysSize.put(randomArrayName, inSize * 32 + 32); arraysIndex.add(randomArrayName); @@ -604,10 +636,10 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { // this code allocates the memory block for the out data, // and saves the size in typical array format [size, element_1, element_2, ...] - String outArrSet = String.format( " %d MSIZE MSTORE 0 %d MSIZE ADD MSTORE8 ", outSizeVal, outSizeVal - 32 ); + String outArrSet = String.format(" %d MSIZE MSTORE 0 %d MSIZE ADD MSTORE8 ", outSizeVal, outSizeVal - 32); - return String.format("%d MSIZE %s %d %s %s %s %s CALL ", - outSizeVal, outArrSet ,inSize * 32, loadInData, operand2, operand1, operand0); + return String.format("%d MSIZE %s %d %s %s %s %s CALL ", + outSizeVal, outArrSet, inSize * 32, loadInData, operand2, operand1, operand0); } @Override @@ -618,7 +650,7 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand2 = visit(ctx.int_val(2)); // OUTDATASIZE OUTDATASTART INDATASIZE INDATASTART VALUE TO GAS CALL - return String.format("0 0 0 0 %s %s %s CALL ", operand2, operand1, operand0); + return String.format("0 0 0 0 %s %s %s CALL ", operand2, operand1, operand0); } @Override @@ -628,7 +660,7 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { String operand2 = visit(ctx.int_val(2)); // MEM_SIZE MEM_START GAS CREATE - return String.format(" %s %s %s CREATE ", operand2, operand1, operand0); + return String.format(" %s %s %s CREATE ", operand2, operand1, operand0); } @Override @@ -637,7 +669,7 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { int size = ctx.asm_symbol().getChildCount(); StringBuffer sb = new StringBuffer(); - for (int i = 0; i < size ; ++i) { + for (int i = 0; i < size; ++i) { String symbol = ctx.asm_symbol().children.get(i).toString(); symbol = symbol.trim(); @@ -649,14 +681,16 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { if (match) { int byteVal = Integer.parseInt(symbol); - if (byteVal > 255 || byteVal < 0) throw new Error("In the [asm asm] block should be placed only byte range numbers"); + if (byteVal > 255 || byteVal < 0) + throw new Error("In the [asm asm] block should be placed only byte range numbers"); } match = Pattern.matches("0[xX][0-9a-fA-F]+", symbol); if (match) { int byteVal = Integer.parseInt(symbol.substring(2), 16); - if (byteVal > 255 || byteVal < 0) throw new Error("In the [asm asm] block should be placed only byte range numbers"); + if (byteVal > 255 || byteVal < 0) + throw new Error("In the [asm asm] block should be placed only byte range numbers"); symbol = byteVal + ""; } @@ -725,12 +759,12 @@ public class SerpentToAssemblyCompiler extends SerpentBaseVisitor { return Integer.parseInt(result); } - private String cleanMsgString (String code) { + private String cleanMsgString(String code) { String result = ""; Pattern pattern = Pattern.compile("<(.*?)>"); - result= code.replaceAll("<(.*?)>", ""); + result = code.replaceAll("<(.*?)>", ""); return result; } diff --git a/ethereumj-core/src/main/java/org/ethereum/trie/Cache.java b/ethereumj-core/src/main/java/org/ethereum/trie/Cache.java index a8409552..8da19a3f 100644 --- a/ethereumj-core/src/main/java/org/ethereum/trie/Cache.java +++ b/ethereumj-core/src/main/java/org/ethereum/trie/Cache.java @@ -11,6 +11,7 @@ import org.iq80.leveldb.WriteBatch; /** * www.ethereumJ.com + * * @author: Nick Savers * Created on: 20/05/2014 10:44 */ @@ -92,7 +93,7 @@ public class Cache { public void undo() { Iterator> iter = this.nodes.entrySet().iterator(); while (iter.hasNext()) { - if(iter.next().getValue().isDirty()) { + if (iter.next().getValue().isDirty()) { iter.remove(); } } @@ -115,11 +116,11 @@ public class Cache { return db; } - public String cacheDump(){ + public String cacheDump() { StringBuffer cacheDump = new StringBuffer(); - for (ByteArrayWrapper key : nodes.keySet()){ + for (ByteArrayWrapper key : nodes.keySet()) { Node node = nodes.get(key); diff --git a/ethereumj-core/src/main/java/org/ethereum/trie/CollectFullSetOfNodes.java b/ethereumj-core/src/main/java/org/ethereum/trie/CollectFullSetOfNodes.java index 1bf0b028..60711b5c 100644 --- a/ethereumj-core/src/main/java/org/ethereum/trie/CollectFullSetOfNodes.java +++ b/ethereumj-core/src/main/java/org/ethereum/trie/CollectFullSetOfNodes.java @@ -20,7 +20,7 @@ public class CollectFullSetOfNodes implements TrieImpl.ScanAction { nodes.add(hash); } - public Set getCollectedHashes(){ + public Set getCollectedHashes() { return nodes; } } diff --git a/ethereumj-core/src/main/java/org/ethereum/trie/CountAllNodes.java b/ethereumj-core/src/main/java/org/ethereum/trie/CountAllNodes.java index 793ac3e7..633f4a39 100644 --- a/ethereumj-core/src/main/java/org/ethereum/trie/CountAllNodes.java +++ b/ethereumj-core/src/main/java/org/ethereum/trie/CountAllNodes.java @@ -18,5 +18,7 @@ public class CountAllNodes implements TrieImpl.ScanAction { ++counted; } - public int getCounted(){return counted;} + public int getCounted() { + return counted; + } } diff --git a/ethereumj-core/src/main/java/org/ethereum/trie/Node.java b/ethereumj-core/src/main/java/org/ethereum/trie/Node.java index 670a6458..51b6bb82 100644 --- a/ethereumj-core/src/main/java/org/ethereum/trie/Node.java +++ b/ethereumj-core/src/main/java/org/ethereum/trie/Node.java @@ -6,9 +6,9 @@ import org.ethereum.util.Value; /** * A Node in a Merkle Patricia Tree is one of the following: * - * - NULL (represented as the empty string) - * - A two-item array [ key, value ] (1 key for 2-item array) - * - A 17-item array [ v0 ... v15, vt ] (16 keys for 17-item array) + * - NULL (represented as the empty string) + * - A two-item array [ key, value ] (1 key for 2-item array) + * - A 17-item array [ v0 ... v15, vt ] (16 keys for 17-item array) * * The idea is that in the event that there is a long path of nodes * each with only one element, we shortcut the descent by setting up @@ -40,6 +40,7 @@ import org.ethereum.util.Value; * when length < 32 for the obvious reason that the function f(x) = x is reversible. * * www.ethereumJ.com + * * @author Nick Savers * Created on: 20/05/2014 10:44 */ diff --git a/ethereumj-core/src/main/java/org/ethereum/trie/TrieImpl.java b/ethereumj-core/src/main/java/org/ethereum/trie/TrieImpl.java index 8aed929d..27dbd83e 100644 --- a/ethereumj-core/src/main/java/org/ethereum/trie/TrieImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/trie/TrieImpl.java @@ -36,6 +36,7 @@ import org.spongycastle.util.encoders.Hex; * Note: the data isn't persisted unless `sync` is explicitly called. * * www.ethereumJ.com + * * @author: Nick Savers * Created on: 20/05/2014 10:44 */ @@ -48,7 +49,7 @@ public class TrieImpl implements Trie { private Object prevRoot; private Object root; - private Cache cache; + private Cache cache; public TrieImpl(DB db) { this(db, ""); @@ -106,7 +107,7 @@ public class TrieImpl implements Trie { byte[] k = binToNibbles(key); Value c = new Value(this.get(this.root, k)); - return (c == null)? null : c.asBytes(); + return (c == null) ? null : c.asBytes(); } /** @@ -126,7 +127,7 @@ public class TrieImpl implements Trie { byte[] k = binToNibbles(key); this.root = this.insertOrDelete(this.root, k, value); - if(logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { logger.debug("Added key {} and value {}", Hex.toHexString(key), Hex.toHexString(value)); logger.debug("New root-hash: {}", Hex.toHexString(this.getRootHash())); } @@ -144,7 +145,7 @@ public class TrieImpl implements Trie { @Override public void delete(byte[] key) { delete(new String(key)); - if(logger.isDebugEnabled()) { + if (logger.isDebugEnabled()) { logger.debug("Deleted value for key {}", Hex.toHexString(key)); logger.debug("New root-hash: {}", Hex.toHexString(this.getRootHash())); } @@ -213,7 +214,7 @@ public class TrieImpl implements Trie { } if (isEmptyNode(node)) { - Object[] newNode = new Object[] { packNibbles(key), value }; + Object[] newNode = new Object[]{packNibbles(key), value}; return this.putToCache(newNode); } @@ -227,7 +228,7 @@ public class TrieImpl implements Trie { // Matching key pair (ie. there's already an object with this key) if (Arrays.equals(k, key)) { - Object[] newNode = new Object[] {packNibbles(key), value}; + Object[] newNode = new Object[]{packNibbles(key), value}; return this.putToCache(newNode); } @@ -242,8 +243,8 @@ public class TrieImpl implements Trie { // Expand the 2 length slice to a 17 length slice // Create two nodes to putToCache into the new 17 length node - Object oldNode = this.insert("", copyOfRange(k, matchingLength+1, k.length), v); - Object newNode = this.insert("", copyOfRange(key, matchingLength+1, key.length), value); + Object oldNode = this.insert("", copyOfRange(k, matchingLength + 1, k.length), v); + Object newNode = this.insert("", copyOfRange(key, matchingLength + 1, key.length), value); // Create an expanded slice Object[] scaledSlice = emptyStringSlice(17); @@ -258,7 +259,7 @@ public class TrieImpl implements Trie { // End of the chain, return return newHash; } else { - Object[] newNode = new Object[] { packNibbles(copyOfRange(key, 0, matchingLength)), newHash}; + Object[] newNode = new Object[]{packNibbles(copyOfRange(key, 0, matchingLength)), newHash}; return this.putToCache(newNode); } } else { @@ -296,9 +297,9 @@ public class TrieImpl implements Trie { Object newNode; if (child.length() == PAIR_SIZE) { byte[] newKey = concatenate(k, unpackToNibbles(child.get(0).asBytes())); - newNode = new Object[] {packNibbles(newKey), child.get(1).asObj()}; + newNode = new Object[]{packNibbles(newKey), child.get(1).asObj()}; } else { - newNode = new Object[] {currentNode.get(0).asString(), hash}; + newNode = new Object[]{currentNode.get(0).asString(), hash}; } return this.putToCache(newNode); } else { @@ -324,14 +325,14 @@ public class TrieImpl implements Trie { Object[] newNode = null; if (amount == 16) { - newNode = new Object[] { packNibbles(new byte[] {16} ), itemList[amount]}; + newNode = new Object[]{packNibbles(new byte[]{16}), itemList[amount]}; } else if (amount >= 0) { Value child = this.getNode(itemList[amount]); if (child.length() == PAIR_SIZE) { key = concatenate(new byte[]{amount}, unpackToNibbles(child.get(0).asBytes())); - newNode = new Object[] {packNibbles(key), child.get(1).asObj()}; + newNode = new Object[]{packNibbles(key), child.get(1).asObj()}; } else if (child.length() == LIST_SIZE) { - newNode = new Object[] { packNibbles(new byte[]{amount}), itemList[amount]}; + newNode = new Object[]{packNibbles(new byte[]{amount}), itemList[amount]}; } } else { newNode = itemList; @@ -445,7 +446,7 @@ public class TrieImpl implements Trie { this.scanTree(this.getRootHash(), collectAction); Set hashSet = collectAction.getCollectedHashes(); - Map nodes = this.getCache().getNodes(); + Map nodes = this.getCache().getNodes(); Set toRemoveSet = new HashSet<>(); for (ByteArrayWrapper key : nodes.keySet()) { @@ -466,7 +467,7 @@ public class TrieImpl implements Trie { logger.info("Garbage collection time: [{}ms]", System.currentTimeMillis() - startTime); } - public void printFootPrint(){ + public void printFootPrint() { this.getCache().getNodes(); } @@ -477,7 +478,7 @@ public class TrieImpl implements Trie { if (node == null) return; if (node.isList()) { - List siblings = node.asList(); + List siblings = node.asList(); if (siblings.size() == PAIR_SIZE) { Value val = new Value(siblings.get(1)); if (val.isHashCode()) @@ -500,7 +501,7 @@ public class TrieImpl implements Trie { this.scanTree(this.getRootHash(), traceAction); if (this.getRoot() instanceof Value) { - root = "root: " + Hex.toHexString(getRootHash()) + " => " + this.getRoot() + "\n"; + root = "root: " + Hex.toHexString(getRootHash()) + " => " + this.getRoot() + "\n"; } else { root = "root: " + Hex.toHexString(getRootHash()) + "\n"; } @@ -511,7 +512,7 @@ public class TrieImpl implements Trie { public void doOnNode(byte[] hash, Value node); } - public boolean validate(){ + public boolean validate() { if (cache.get(getRootHash()) != null) return true; diff --git a/ethereumj-core/src/main/java/org/ethereum/trie/TrieIterator.java b/ethereumj-core/src/main/java/org/ethereum/trie/TrieIterator.java index fc9c51b1..161ee91f 100644 --- a/ethereumj-core/src/main/java/org/ethereum/trie/TrieIterator.java +++ b/ethereumj-core/src/main/java/org/ethereum/trie/TrieIterator.java @@ -3,6 +3,7 @@ package org.ethereum.trie; import java.util.List; import org.ethereum.util.Value; + import static org.ethereum.util.CompactEncoder.unpackToNibbles; /* @@ -32,7 +33,7 @@ public class TrieIterator { if (currentNode.get(1).asString() == "") { this.workNode(currentNode.get(1)); } else { - if (k[k.length-1] == 16) { + if (k[k.length - 1] == 16) { this.values.add(currentNode.get(1).asString()); } else { this.shas.add(currentNode.get(1).asBytes()); diff --git a/ethereumj-core/src/main/java/org/ethereum/util/ByteUtil.java b/ethereumj-core/src/main/java/org/ethereum/util/ByteUtil.java index 42852511..230b3f94 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/ByteUtil.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/ByteUtil.java @@ -68,7 +68,7 @@ public class ByteUtil { /** * Returns the amount of nibbles that match each other from 0 ... - * amount will never be larger than smallest input + * amount will never be larger than smallest input * * @param a - first input * @param b - second input @@ -112,16 +112,17 @@ public class ByteUtil { /** * Calculate packet length + * * @param msg byte[] * @return byte-array with 4 elements */ public static byte[] calcPacketLength(byte[] msg) { int msgLen = msg.length; byte[] len = { - (byte)((msgLen >> 24) & 0xFF), - (byte)((msgLen >> 16) & 0xFF), - (byte)((msgLen >> 8) & 0xFF), - (byte)((msgLen ) & 0xFF)}; + (byte) ((msgLen >> 24) & 0xFF), + (byte) ((msgLen >> 16) & 0xFF), + (byte) ((msgLen >> 8) & 0xFF), + (byte) ((msgLen) & 0xFF)}; return len; } @@ -157,13 +158,13 @@ public class ByteUtil { /** * Turn nibbles to a pretty looking output string * - * Example. [ 1, 2, 3, 4, 5 ] becomes '\x11\x23\x45' + * Example. [ 1, 2, 3, 4, 5 ] becomes '\x11\x23\x45' * * @param nibbles - getting byte of data [ 04 ] and turning * it to a '\x04' representation * @return pretty string of nibbles */ - public static String nibblesToPrettyString(byte[] nibbles){ + public static String nibblesToPrettyString(byte[] nibbles) { StringBuffer buffer = new StringBuffer(); for (byte nibble : nibbles) { String nibleString = oneByteToHexString(nibble); @@ -190,7 +191,7 @@ public class ByteUtil { BigInteger bInt = new BigInteger(val); int bytes = 0; - while(!bInt.equals(BigInteger.ZERO)) { + while (!bInt.equals(BigInteger.ZERO)) { bInt = bInt.shiftRight(8); ++bytes; } @@ -231,6 +232,7 @@ public class ByteUtil { /** * encode the values and concatenate together + * * @param args Object * @return byte[] */ @@ -247,7 +249,7 @@ public class ByteUtil { return baos.toByteArray(); } - public static int firstNonZeroByte(byte[] data){ + public static int firstNonZeroByte(byte[] data) { int firstNonZero = -1; int i = 0; for (; i < data.length; ++i) { @@ -287,13 +289,12 @@ public class ByteUtil { * increment byte array as a number until max is reached * * @param bytes byte[] - * * @return boolean */ public static boolean increment(byte[] bytes) { final int startIndex = 0; int i; - for (i = bytes.length-1; i >= startIndex; i--) { + for (i = bytes.length - 1; i >= startIndex; i--) { bytes[i]++; if (bytes[i] != 0) break; @@ -318,24 +319,24 @@ public class ByteUtil { } - public static ByteArrayWrapper wrap(byte[] data){ + public static ByteArrayWrapper wrap(byte[] data) { return new ByteArrayWrapper(data); } public static byte[] setBit(byte[] data, int pos, int val) { - if ( (data.length * 8) - 1 < pos ) + if ((data.length * 8) - 1 < pos) throw new Error("outside byte array limit, pos: " + pos); - int posByte = data.length - 1 - (pos) / 8; - int posBit = (pos) % 8; - byte setter = (byte)(1 << (posBit)); + int posByte = data.length - 1 - (pos) / 8; + int posBit = (pos) % 8; + byte setter = (byte) (1 << (posBit)); byte toBeSet = data[posByte]; byte result; - if(val == 1) - result = (byte)(toBeSet | setter); + if (val == 1) + result = (byte) (toBeSet | setter); else - result = (byte)(toBeSet & ~setter); + result = (byte) (toBeSet & ~setter); data[posByte] = result; return data; @@ -343,11 +344,11 @@ public class ByteUtil { public static int getBit(byte[] data, int pos) { - if ((data.length * 8) - 1 < pos ) + if ((data.length * 8) - 1 < pos) throw new Error("outside byte array limit, pos: " + pos); - int posByte = data.length - 1 - pos / 8; - int posBit = pos % 8; + int posByte = data.length - 1 - pos / 8; + int posBit = pos % 8; byte dataByte = data[posByte]; return Math.min(1, (dataByte & (1 << (posBit)))); } diff --git a/ethereumj-core/src/main/java/org/ethereum/util/CompactEncoder.java b/ethereumj-core/src/main/java/org/ethereum/util/CompactEncoder.java index 5db93a90..d6bc3c0b 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/CompactEncoder.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/CompactEncoder.java @@ -44,29 +44,29 @@ import java.util.Map; * '\x20\x0f\x1c\xb8' * > [ 15, 1, 12, 11, 8, T ] * '\x3f\x1c\xb8' - * */ public class CompactEncoder { private final static byte TERMINATOR = 16; private final static Map hexMap = new HashMap<>(); + static { - hexMap.put('0', (byte)0x0); - hexMap.put('1', (byte)0x1); - hexMap.put('2', (byte)0x2); - hexMap.put('3', (byte)0x3); - hexMap.put('4', (byte)0x4); - hexMap.put('5', (byte)0x5); - hexMap.put('6', (byte)0x6); - hexMap.put('7', (byte)0x7); - hexMap.put('8', (byte)0x8); - hexMap.put('9', (byte)0x9); - hexMap.put('a', (byte)0xa); - hexMap.put('b', (byte)0xb); - hexMap.put('c', (byte)0xc); - hexMap.put('d', (byte)0xd); - hexMap.put('e', (byte)0xe); - hexMap.put('f', (byte)0xf); + hexMap.put('0', (byte) 0x0); + hexMap.put('1', (byte) 0x1); + hexMap.put('2', (byte) 0x2); + hexMap.put('3', (byte) 0x3); + hexMap.put('4', (byte) 0x4); + hexMap.put('5', (byte) 0x5); + hexMap.put('6', (byte) 0x6); + hexMap.put('7', (byte) 0x7); + hexMap.put('8', (byte) 0x8); + hexMap.put('9', (byte) 0x9); + hexMap.put('a', (byte) 0xa); + hexMap.put('b', (byte) 0xb); + hexMap.put('c', (byte) 0xc); + hexMap.put('d', (byte) 0xd); + hexMap.put('e', (byte) 0xe); + hexMap.put('f', (byte) 0xf); } /** @@ -78,22 +78,22 @@ public class CompactEncoder { public static byte[] packNibbles(byte[] nibbles) { int terminator = 0; - if (nibbles[nibbles.length-1] == TERMINATOR) { + if (nibbles[nibbles.length - 1] == TERMINATOR) { terminator = 1; - nibbles = copyOf(nibbles, nibbles.length-1); + nibbles = copyOf(nibbles, nibbles.length - 1); } int oddlen = nibbles.length % 2; - int flag = 2*terminator + oddlen; + int flag = 2 * terminator + oddlen; if (oddlen != 0) { - byte[] flags = new byte[] { (byte) flag}; + byte[] flags = new byte[]{(byte) flag}; nibbles = concatenate(flags, nibbles); } else { - byte[] flags = new byte[] { (byte) flag, 0}; + byte[] flags = new byte[]{(byte) flag, 0}; nibbles = concatenate(flags, nibbles); } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (int i = 0; i < nibbles.length; i += 2) { - buffer.write(16*nibbles[i] + nibbles[i+1]); + buffer.write(16 * nibbles[i] + nibbles[i + 1]); } return buffer.toByteArray(); } @@ -128,7 +128,7 @@ public class CompactEncoder { byte[] hexEncoded = encode(str); ByteBuffer slice = ByteBuffer.allocate(hexEncoded.length + 1); for (byte b : hexEncoded) { - slice.put(hexMap.get((char)b)); + slice.put(hexMap.get((char) b)); } slice.put(TERMINATOR); return slice.array(); @@ -138,7 +138,7 @@ public class CompactEncoder { byte[] hexEncoded = encode(str); ByteBuffer slice = ByteBuffer.allocate(hexEncoded.length); for (byte b : hexEncoded) { - slice.put(hexMap.get((char)b)); + slice.put(hexMap.get((char) b)); } return slice.array(); } diff --git a/ethereumj-core/src/main/java/org/ethereum/util/DecodeResult.java b/ethereumj-core/src/main/java/org/ethereum/util/DecodeResult.java index 7bfc4170..046ee9ca 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/DecodeResult.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/DecodeResult.java @@ -18,6 +18,7 @@ public class DecodeResult implements Serializable { public int getPos() { return pos; } + public Object getDecoded() { return decoded; } @@ -27,7 +28,7 @@ public class DecodeResult implements Serializable { } private String asString(Object decoded) { - if(decoded instanceof String) { + if (decoded instanceof String) { return (String) decoded; } else if (decoded instanceof byte[]) { return Hex.toHexString((byte[]) decoded); diff --git a/ethereumj-core/src/main/java/org/ethereum/util/FastByteComparisons.java b/ethereumj-core/src/main/java/org/ethereum/util/FastByteComparisons.java index f52c43d3..86c3d4d0 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/FastByteComparisons.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/FastByteComparisons.java @@ -35,210 +35,212 @@ import com.google.common.primitives.UnsignedBytes; @SuppressWarnings("restriction") public abstract class FastByteComparisons { - /** - * Lexicographically compare two byte arrays. - * - * @param b1 buffer1 - * @param s1 offset1 - * @param l1 length1 - * @param b2 buffer2 - * @param s2 offset2 - * @param l2 length2 - * - * @return int - */ - public static int compareTo(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { - return LexicographicalComparerHolder.BEST_COMPARER.compareTo( - b1, s1, l1, b2, s2, l2); - } - - private interface Comparer { - abstract public int compareTo(T buffer1, int offset1, int length1, - T buffer2, int offset2, int length2); - } - - private static Comparer lexicographicalComparerJavaImpl() { - return LexicographicalComparerHolder.PureJavaComparer.INSTANCE; - } - - - /** - * Provides a lexicographical comparer implementation; either a Java - * implementation or a faster implementation based on {@link Unsafe}. - * - *

    Uses reflection to gracefully fall back to the Java implementation if - * {@code Unsafe} isn't available. - */ - private static class LexicographicalComparerHolder { - static final String UNSAFE_COMPARER_NAME = - LexicographicalComparerHolder.class.getName() + "$UnsafeComparer"; - - static final Comparer BEST_COMPARER = getBestComparer(); /** - * Returns the Unsafe-using Comparer, or falls back to the pure-Java - * implementation if unable to do so. + * Lexicographically compare two byte arrays. + * + * @param b1 buffer1 + * @param s1 offset1 + * @param l1 length1 + * @param b2 buffer2 + * @param s2 offset2 + * @param l2 length2 + * @return int */ - static Comparer getBestComparer() { - try { - Class theClass = Class.forName(UNSAFE_COMPARER_NAME); - - // yes, UnsafeComparer does implement Comparer - @SuppressWarnings("unchecked") - Comparer comparer = - (Comparer) theClass.getEnumConstants()[0]; - return comparer; - } catch (Throwable t) { // ensure we really catch *everything* - return lexicographicalComparerJavaImpl(); - } + public static int compareTo(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { + return LexicographicalComparerHolder.BEST_COMPARER.compareTo( + b1, s1, l1, b2, s2, l2); } - private enum PureJavaComparer implements Comparer { - INSTANCE; - - @Override - public int compareTo(byte[] buffer1, int offset1, int length1, - byte[] buffer2, int offset2, int length2) { - // Short circuit equal case - if (buffer1 == buffer2 && - offset1 == offset2 && - length1 == length2) { - return 0; - } - int end1 = offset1 + length1; - int end2 = offset2 + length2; - for (int i = offset1, j = offset2; i < end1 && j < end2; i++, j++) { - int a = (buffer1[i] & 0xff); - int b = (buffer2[j] & 0xff); - if (a != b) { - return a - b; - } - } - return length1 - length2; - } + private interface Comparer { + abstract public int compareTo(T buffer1, int offset1, int length1, + T buffer2, int offset2, int length2); } - @SuppressWarnings("unused") // used via reflection - private enum UnsafeComparer implements Comparer { - INSTANCE; + private static Comparer lexicographicalComparerJavaImpl() { + return LexicographicalComparerHolder.PureJavaComparer.INSTANCE; + } - static final Unsafe theUnsafe; - /** The offset to the first element in a byte array. */ - static final int BYTE_ARRAY_BASE_OFFSET; + /** + * Provides a lexicographical comparer implementation; either a Java + * implementation or a faster implementation based on {@link Unsafe}. + * + *

    Uses reflection to gracefully fall back to the Java implementation if + * {@code Unsafe} isn't available. + */ + private static class LexicographicalComparerHolder { + static final String UNSAFE_COMPARER_NAME = + LexicographicalComparerHolder.class.getName() + "$UnsafeComparer"; - static { - theUnsafe = (Unsafe) AccessController.doPrivileged( - new PrivilegedAction() { - @Override - public Object run() { - try { - Field f = Unsafe.class.getDeclaredField("theUnsafe"); - f.setAccessible(true); - return f.get(null); - } catch (NoSuchFieldException e) { - // It doesn't matter what we throw; - // it's swallowed in getBestComparer(). - throw new Error(); - } catch (IllegalAccessException e) { - throw new Error(); + static final Comparer BEST_COMPARER = getBestComparer(); + + /** + * Returns the Unsafe-using Comparer, or falls back to the pure-Java + * implementation if unable to do so. + */ + static Comparer getBestComparer() { + try { + Class theClass = Class.forName(UNSAFE_COMPARER_NAME); + + // yes, UnsafeComparer does implement Comparer + @SuppressWarnings("unchecked") + Comparer comparer = + (Comparer) theClass.getEnumConstants()[0]; + return comparer; + } catch (Throwable t) { // ensure we really catch *everything* + return lexicographicalComparerJavaImpl(); + } + } + + private enum PureJavaComparer implements Comparer { + INSTANCE; + + @Override + public int compareTo(byte[] buffer1, int offset1, int length1, + byte[] buffer2, int offset2, int length2) { + // Short circuit equal case + if (buffer1 == buffer2 && + offset1 == offset2 && + length1 == length2) { + return 0; } - } - }); - - BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class); - - // sanity check - this should never fail - if (theUnsafe.arrayIndexScale(byte[].class) != 1) { - throw new AssertionError(); + int end1 = offset1 + length1; + int end2 = offset2 + length2; + for (int i = offset1, j = offset2; i < end1 && j < end2; i++, j++) { + int a = (buffer1[i] & 0xff); + int b = (buffer2[j] & 0xff); + if (a != b) { + return a - b; + } + } + return length1 - length2; + } } - } - static final boolean littleEndian = - ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN); + @SuppressWarnings("unused") // used via reflection + private enum UnsafeComparer implements Comparer { + INSTANCE; - /** - * Returns true if x1 is less than x2, when both values are treated as - * unsigned. - */ - static boolean lessThanUnsigned(long x1, long x2) { - return (x1 + Long.MIN_VALUE) < (x2 + Long.MIN_VALUE); - } + static final Unsafe theUnsafe; - /** - * Lexicographically compare two arrays. - * - * @param buffer1 left operand - * @param buffer2 right operand - * @param offset1 Where to start comparing in the left buffer - * @param offset2 Where to start comparing in the right buffer - * @param length1 How much to compare from the left buffer - * @param length2 How much to compare from the right buffer - * @return 0 if equal, < 0 if left is less than right, etc. - */ - @Override - public int compareTo(byte[] buffer1, int offset1, int length1, - byte[] buffer2, int offset2, int length2) { - // Short circuit equal case - if (buffer1 == buffer2 && - offset1 == offset2 && - length1 == length2) { - return 0; - } - int minLength = Math.min(length1, length2); - int minWords = minLength / Longs.BYTES; - int offset1Adj = offset1 + BYTE_ARRAY_BASE_OFFSET; - int offset2Adj = offset2 + BYTE_ARRAY_BASE_OFFSET; + /** + * The offset to the first element in a byte array. + */ + static final int BYTE_ARRAY_BASE_OFFSET; + + static { + theUnsafe = (Unsafe) AccessController.doPrivileged( + new PrivilegedAction() { + @Override + public Object run() { + try { + Field f = Unsafe.class.getDeclaredField("theUnsafe"); + f.setAccessible(true); + return f.get(null); + } catch (NoSuchFieldException e) { + // It doesn't matter what we throw; + // it's swallowed in getBestComparer(). + throw new Error(); + } catch (IllegalAccessException e) { + throw new Error(); + } + } + }); + + BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class); + + // sanity check - this should never fail + if (theUnsafe.arrayIndexScale(byte[].class) != 1) { + throw new AssertionError(); + } + } + + static final boolean littleEndian = + ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN); + + /** + * Returns true if x1 is less than x2, when both values are treated as + * unsigned. + */ + static boolean lessThanUnsigned(long x1, long x2) { + return (x1 + Long.MIN_VALUE) < (x2 + Long.MIN_VALUE); + } + + /** + * Lexicographically compare two arrays. + * + * @param buffer1 left operand + * @param buffer2 right operand + * @param offset1 Where to start comparing in the left buffer + * @param offset2 Where to start comparing in the right buffer + * @param length1 How much to compare from the left buffer + * @param length2 How much to compare from the right buffer + * @return 0 if equal, < 0 if left is less than right, etc. + */ + @Override + public int compareTo(byte[] buffer1, int offset1, int length1, + byte[] buffer2, int offset2, int length2) { + // Short circuit equal case + if (buffer1 == buffer2 && + offset1 == offset2 && + length1 == length2) { + return 0; + } + int minLength = Math.min(length1, length2); + int minWords = minLength / Longs.BYTES; + int offset1Adj = offset1 + BYTE_ARRAY_BASE_OFFSET; + int offset2Adj = offset2 + BYTE_ARRAY_BASE_OFFSET; /* * Compare 8 bytes at a time. Benchmarking shows comparing 8 bytes at a * time is no slower than comparing 4 bytes at a time even on 32-bit. * On the other hand, it is substantially faster on 64-bit. */ - for (int i = 0; i < minWords * Longs.BYTES; i += Longs.BYTES) { - long lw = theUnsafe.getLong(buffer1, offset1Adj + (long) i); - long rw = theUnsafe.getLong(buffer2, offset2Adj + (long) i); - long diff = lw ^ rw; + for (int i = 0; i < minWords * Longs.BYTES; i += Longs.BYTES) { + long lw = theUnsafe.getLong(buffer1, offset1Adj + (long) i); + long rw = theUnsafe.getLong(buffer2, offset2Adj + (long) i); + long diff = lw ^ rw; - if (diff != 0) { - if (!littleEndian) { - return lessThanUnsigned(lw, rw) ? -1 : 1; - } + if (diff != 0) { + if (!littleEndian) { + return lessThanUnsigned(lw, rw) ? -1 : 1; + } - // Use binary search - int n = 0; - int y; - int x = (int) diff; - if (x == 0) { - x = (int) (diff >>> 32); - n = 32; - } + // Use binary search + int n = 0; + int y; + int x = (int) diff; + if (x == 0) { + x = (int) (diff >>> 32); + n = 32; + } - y = x << 16; - if (y == 0) { - n += 16; - } else { - x = y; - } + y = x << 16; + if (y == 0) { + n += 16; + } else { + x = y; + } - y = x << 8; - if (y == 0) { - n += 8; + y = x << 8; + if (y == 0) { + n += 8; + } + return (int) (((lw >>> n) & 0xFFL) - ((rw >>> n) & 0xFFL)); + } + } + + // The epilogue to cover the last (minLength % 8) elements. + for (int i = minWords * Longs.BYTES; i < minLength; i++) { + int result = UnsignedBytes.compare( + buffer1[offset1 + i], + buffer2[offset2 + i]); + if (result != 0) { + return result; + } + } + return length1 - length2; } - return (int) (((lw >>> n) & 0xFFL) - ((rw >>> n) & 0xFFL)); - } } - - // The epilogue to cover the last (minLength % 8) elements. - for (int i = minWords * Longs.BYTES; i < minLength; i++) { - int result = UnsignedBytes.compare( - buffer1[offset1 + i], - buffer2[offset2 + i]); - if (result != 0) { - return result; - } - } - return length1 - length2; - } } - } } diff --git a/ethereumj-core/src/main/java/org/ethereum/util/LRUMap.java b/ethereumj-core/src/main/java/org/ethereum/util/LRUMap.java index 54b1f91f..df9aca9f 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/LRUMap.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/LRUMap.java @@ -5,7 +5,7 @@ import java.util.concurrent.ConcurrentHashMap; /** * Simple LRU map used for reusing lookup values. */ -public class LRUMap extends ConcurrentHashMap { +public class LRUMap extends ConcurrentHashMap { private static final long serialVersionUID = 1L; diff --git a/ethereumj-core/src/main/java/org/ethereum/util/RLP.java b/ethereumj-core/src/main/java/org/ethereum/util/RLP.java index d09a91eb..672d6326 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/RLP.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/RLP.java @@ -45,24 +45,26 @@ import org.spongycastle.util.encoders.Hex; * See: https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP * * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 01/04/2014 10:45 - * */ public class RLP { - /** Allow for content up to size of 2^64 bytes **/ + /** + * Allow for content up to size of 2^64 bytes * + */ private static double MAX_ITEM_LENGTH = Math.pow(256, 8); /** * Reason for threshold according to Vitalik Buterin: - * - 56 bytes maximizes the benefit of both options - * - if we went with 60 then we would have only had 4 slots for long strings + * - 56 bytes maximizes the benefit of both options + * - if we went with 60 then we would have only had 4 slots for long strings * so RLP would not have been able to store objects above 4gb - * - if we went with 48 then RLP would be fine for 2^128 space, but that's way too much - * - so 56 and 2^64 space seems like the right place to put the cutoff - * - also, that's where Bitcoin's varint does the cutof - **/ + * - if we went with 48 then RLP would be fine for 2^128 space, but that's way too much + * - so 56 and 2^64 space seems like the right place to put the cutoff + * - also, that's where Bitcoin's varint does the cutof + */ private static int SIZE_THRESHOLD = 56; /** RLP encoding rules are defined as follows: */ @@ -347,7 +349,7 @@ public class RLP { byte dByte = decodeOneByteItem(data, index + offset); // return IP address - return new byte[] { aByte, bByte, cByte, dByte }; + return new byte[]{aByte, bByte, cByte, dByte}; } public static int getFirstListElement(byte[] payload, int pos) { @@ -659,7 +661,7 @@ public class RLP { // single byte item if ((msgData[pos] & 0xFF) < OFFSET_SHORT_ITEM) { - byte[] item = { (byte) (msgData[pos] & 0xFF) }; + byte[] item = {(byte) (msgData[pos] & 0xFF)}; RLPItem rlpItem = new RLPItem(item); rlpList.add(rlpItem); @@ -685,23 +687,25 @@ public class RLP { } int prefix = data[pos] & 0xFF; if (prefix == OFFSET_SHORT_ITEM) { - return new DecodeResult(pos+1, ""); // means no length or 0 + return new DecodeResult(pos + 1, ""); // means no length or 0 } else if (prefix < OFFSET_SHORT_ITEM) { - return new DecodeResult(pos+1, new byte[] { data[pos] }); // byte is its own RLP encoding + return new DecodeResult(pos + 1, new byte[]{data[pos]}); // byte is its own RLP encoding } else if (prefix < OFFSET_LONG_ITEM) { int len = prefix - OFFSET_SHORT_ITEM; // length of the encoded bytes - return new DecodeResult(pos+1+len, copyOfRange(data, pos+1, pos+1+len)); + return new DecodeResult(pos + 1 + len, copyOfRange(data, pos + 1, pos + 1 + len)); } else if (prefix < OFFSET_SHORT_LIST) { int lenlen = prefix - OFFSET_LONG_ITEM; // length of length the encoded bytes - int lenbytes = byteArrayToInt(copyOfRange(data, pos+1, pos+1+lenlen)); // length of encoded bytes - return new DecodeResult(pos+1+lenlen+lenbytes, copyOfRange(data, pos+1+lenlen, pos+1+lenlen+lenbytes)); + int lenbytes = byteArrayToInt(copyOfRange(data, pos + 1, pos + 1 + lenlen)); // length of encoded bytes + return new DecodeResult(pos + 1 + lenlen + lenbytes, copyOfRange(data, pos + 1 + lenlen, pos + 1 + lenlen + + lenbytes)); } else if (prefix <= OFFSET_LONG_LIST) { int len = prefix - OFFSET_SHORT_LIST; // length of the encoded list - int prevPos = pos; pos++; + int prevPos = pos; + pos++; return decodeList(data, pos, prevPos, len); } else if (prefix < 0xFF) { int lenlen = prefix - OFFSET_LONG_LIST; // length of length the encoded list - int lenlist = byteArrayToInt(copyOfRange(data, pos+1, pos+1+lenlen)); // length of encoded bytes + int lenlist = byteArrayToInt(copyOfRange(data, pos + 1, pos + 1 + lenlen)); // length of encoded bytes pos = pos + lenlen + 1; // start at position of first element in list int prevPos = lenlist; return decodeList(data, pos, prevPos, lenlist); @@ -712,7 +716,7 @@ public class RLP { private static DecodeResult decodeList(byte[] data, int pos, int prevPos, int len) { List slice = new ArrayList<>(); - for (int i = 0; i < len;) { + for (int i = 0; i < len; ) { // Get the next item in the data list and append it DecodeResult result = decode(data, pos); slice.add(result.getDecoded()); @@ -759,19 +763,21 @@ public class RLP { } } - /** Integer limitation goes up to 2^31-1 so length can never be bigger than MAX_ITEM_LENGTH */ + /** + * Integer limitation goes up to 2^31-1 so length can never be bigger than MAX_ITEM_LENGTH + */ public static byte[] encodeLength(int length, int offset) { if (length < SIZE_THRESHOLD) { byte firstByte = (byte) (length + offset); - return new byte[] { firstByte }; + return new byte[]{firstByte}; } else if (length < MAX_ITEM_LENGTH) { byte[] binaryLength; if (length > 0xFF) binaryLength = BigInteger.valueOf(length).toByteArray(); else - binaryLength = new byte[] { (byte) length }; + binaryLength = new byte[]{(byte) length}; byte firstByte = (byte) (binaryLength.length + offset + SIZE_THRESHOLD - 1); - return concatenate(new byte[] { firstByte }, binaryLength); + return concatenate(new byte[]{firstByte}, binaryLength); } else { throw new RuntimeException("Input too long"); } @@ -779,11 +785,11 @@ public class RLP { public static byte[] encodeByte(byte singleByte) { if ((singleByte & 0xFF) == 0) { - return new byte[] { (byte) OFFSET_SHORT_ITEM }; + return new byte[]{(byte) OFFSET_SHORT_ITEM}; } else if ((singleByte & 0xFF) < 0x7F) { - return new byte[] { singleByte }; + return new byte[]{singleByte}; } else { - return new byte[] { (byte) (OFFSET_SHORT_ITEM + 1), singleByte }; + return new byte[]{(byte) (OFFSET_SHORT_ITEM + 1), singleByte}; } } @@ -791,9 +797,9 @@ public class RLP { if (singleShort <= 0xFF) return encodeByte((byte) singleShort); else { - return new byte[] { (byte) (OFFSET_SHORT_ITEM + 2), + return new byte[]{(byte) (OFFSET_SHORT_ITEM + 2), (byte) (singleShort >> 8 & 0xFF), - (byte) (singleShort >> 0 & 0xFF) }; + (byte) (singleShort >> 0 & 0xFF)}; } } @@ -803,12 +809,12 @@ public class RLP { else if (singleInt <= 0xFFFF) return encodeShort((short) singleInt); else if (singleInt <= 0xFFFFFF) - return new byte[] { (byte) (OFFSET_SHORT_ITEM + 3), - (byte) (singleInt >>> 16), - (byte) (singleInt >>> 8), - (byte) singleInt}; + return new byte[]{(byte) (OFFSET_SHORT_ITEM + 3), + (byte) (singleInt >>> 16), + (byte) (singleInt >>> 8), + (byte) singleInt}; else { - return new byte[] { (byte) (OFFSET_SHORT_ITEM + 4), + return new byte[]{(byte) (OFFSET_SHORT_ITEM + 4), (byte) (singleInt >>> 24), (byte) (singleInt >>> 16), (byte) (singleInt >>> 8), @@ -821,8 +827,8 @@ public class RLP { } public static byte[] encodeBigInteger(BigInteger srcBigInteger) { - if(srcBigInteger == BigInteger.ZERO) - return encodeByte((byte)0); + if (srcBigInteger == BigInteger.ZERO) + return encodeByte((byte) 0); else return encodeElement(asUnsignedByteArray(srcBigInteger)); } @@ -866,14 +872,14 @@ public class RLP { public static byte[] encodeList(byte[]... elements) { - if (elements == null){ - return new byte[] {(byte)OFFSET_SHORT_LIST }; + if (elements == null) { + return new byte[]{(byte) OFFSET_SHORT_LIST}; } int totalLength = 0; for (int i = 0; elements != null && i < elements.length; ++i) { - totalLength += elements[i].length; + totalLength += elements[i].length; } byte[] data; @@ -920,13 +926,13 @@ public class RLP { } else if (input instanceof String) { String inputString = (String) input; return inputString.getBytes(); - } else if(input instanceof Long) { + } else if (input instanceof Long) { Long inputLong = (Long) input; return (inputLong == 0) ? ByteUtil.EMPTY_BYTE_ARRAY : asUnsignedByteArray(BigInteger.valueOf(inputLong)); - } else if(input instanceof Integer) { + } else if (input instanceof Integer) { Integer inputInt = (Integer) input; return (inputInt == 0) ? ByteUtil.EMPTY_BYTE_ARRAY : asUnsignedByteArray(BigInteger.valueOf(inputInt.intValue())); - } else if(input instanceof BigInteger) { + } else if (input instanceof BigInteger) { BigInteger inputBigInt = (BigInteger) input; return (inputBigInt == BigInteger.ZERO) ? ByteUtil.EMPTY_BYTE_ARRAY : asUnsignedByteArray(inputBigInt); } else if (input instanceof Value) { diff --git a/ethereumj-core/src/main/java/org/ethereum/util/RLPElement.java b/ethereumj-core/src/main/java/org/ethereum/util/RLPElement.java index f0d8fceb..d74be0ae 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/RLPElement.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/RLPElement.java @@ -6,9 +6,9 @@ import java.io.Serializable; * Wrapper class for decoded elements from an RLP encoded byte array. * * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 01/04/2014 10:45 - * */ public interface RLPElement extends Serializable { diff --git a/ethereumj-core/src/main/java/org/ethereum/util/RLPItem.java b/ethereumj-core/src/main/java/org/ethereum/util/RLPItem.java index e0305afd..6ece7042 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/RLPItem.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/RLPItem.java @@ -3,6 +3,7 @@ package org.ethereum.util; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 21/04/14 16:26 */ diff --git a/ethereumj-core/src/main/java/org/ethereum/util/RLPList.java b/ethereumj-core/src/main/java/org/ethereum/util/RLPList.java index 6a5cd4d5..30836923 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/RLPList.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/RLPList.java @@ -4,6 +4,7 @@ import java.util.ArrayList; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 21/04/14 16:26 */ diff --git a/ethereumj-core/src/main/java/org/ethereum/util/Utils.java b/ethereumj-core/src/main/java/org/ethereum/util/Utils.java index 657dbd11..8b736042 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/Utils.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/Utils.java @@ -50,6 +50,7 @@ public class Utils { } static BigInteger _1000_ = new BigInteger("1000"); + public static String getValueShortString(BigInteger number) { BigInteger result = number; int pow = 0; @@ -68,10 +69,13 @@ public class Utils { */ public static byte[] addressStringToBytes(String hex) { byte[] addr = null; - try { addr = Hex.decode(hex); } - catch(DecoderException addressIsNotValid) { return null; } + try { + addr = Hex.decode(hex); + } catch (DecoderException addressIsNotValid) { + return null; + } - if(isValidAddress(addr)) + if (isValidAddress(addr)) return addr; return null; } @@ -102,6 +106,7 @@ public class Utils { } public static double JAVA_VERSION = getJavaVersion(); + static double getJavaVersion() { String version = System.getProperty("java.version"); @@ -109,10 +114,10 @@ public class Utils { if (version.equals("0")) return 0; int pos = 0, count = 0; - for ( ; pos blockHashes) { @@ -122,7 +127,7 @@ public class Utils { if (blockHashes.isEmpty()) return sb.append("[]"); String firstHash = Hex.toHexString(blockHashes.get(0)); - String lastHash = Hex.toHexString(blockHashes.get(blockHashes.size()-1)); + String lastHash = Hex.toHexString(blockHashes.get(blockHashes.size() - 1)); return sb.append(" ").append(firstHash).append("...").append(lastHash); } diff --git a/ethereumj-core/src/main/java/org/ethereum/util/Value.java b/ethereumj-core/src/main/java/org/ethereum/util/Value.java index 04653f5c..f39344ed 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/Value.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/Value.java @@ -17,7 +17,8 @@ public class Value { public static Value fromRlpEncoded(byte[] data) { if (data != null && data.length != 0) { return new Value(RLP.decode(data, 0).getDecoded()); - } return null; + } + return null; } public Value(Object obj) { @@ -76,9 +77,9 @@ public class Value { } public byte[] asBytes() { - if(isBytes()) { + if (isBytes()) { return (byte[]) value; - } else if(isString()) { + } else if (isString()) { return asString().getBytes(); } return ByteUtil.EMPTY_BYTE_ARRAY; @@ -89,7 +90,7 @@ public class Value { } public Value get(int index) { - if(isList()) { + if (isList()) { // Guard for OutOfBounds if (asList().size() <= index) { return new Value(null); @@ -144,30 +145,30 @@ public class Value { } // it's only if the isBytes() = true; - public boolean isReadbleString(){ + public boolean isReadbleString() { int readableChars = 0; - byte[] data = (byte[])value; + byte[] data = (byte[]) value; - if (data.length == 1 && data[0] > 31 && data[0] < 126){ + if (data.length == 1 && data[0] > 31 && data[0] < 126) { return true; } - for (int i = 0; i < data.length; ++i){ + for (int i = 0; i < data.length; ++i) { if (data[i] > 32 && data[i] < 126) ++readableChars; } - if ((double)readableChars / (double)data.length > 0.55) + if ((double) readableChars / (double) data.length > 0.55) return true; else return false; } // it's only if the isBytes() = true; - public boolean isHexString(){ + public boolean isHexString() { int hexChars = 0; - byte[] data = (byte[])value; + byte[] data = (byte[]) value; for (int i = 0; i < data.length; ++i) { @@ -182,7 +183,7 @@ public class Value { return false; } - public boolean isHashCode(){ + public boolean isHashCode() { return this.asBytes().length == 32; } @@ -239,9 +240,9 @@ public class Value { } buffer.append(" ["); - for (int i = 0; i < list.length; ++i){ + for (int i = 0; i < list.length; ++i) { Value val = new Value(list[i]); - if (val.isString() || val.isEmpty()){ + if (val.isString() || val.isEmpty()) { buffer.append("'").append(val.toString()).append("'"); } else { buffer.append(val.toString()); @@ -265,14 +266,14 @@ public class Value { if (oneByte < 16) { output.append("\\x").append(ByteUtil.oneByteToHexString(oneByte)); } else { - output.append(Character.valueOf((char)oneByte)); + output.append(Character.valueOf((char) oneByte)); } } output.append("'"); return output.toString(); } return Hex.toHexString(this.asBytes()); - } else if (isString()){ + } else if (isString()) { return asString(); } return "Unexpected type"; diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/DataWord.java b/ethereumj-core/src/main/java/org/ethereum/vm/DataWord.java index 3ae3eb09..4b30dc54 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/DataWord.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/DataWord.java @@ -14,16 +14,17 @@ import java.nio.ByteBuffer; * Calculations can be done on this word with other DataWords * * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 01/06/2014 10:45 */ public class DataWord implements Comparable { /* Maximum value of the DataWord */ - public static final BigInteger _2_256 = BigInteger.valueOf(2).pow(256); - public static final BigInteger MAX_VALUE = _2_256.subtract(BigInteger.ONE); - public static final DataWord ZERO = new DataWord(new byte[32]); // don't push it in to the stack - public static final DataWord ZERO_EMPTY_ARRAY = new DataWord(new byte[0]); // don't push it in to the stack + public static final BigInteger _2_256 = BigInteger.valueOf(2).pow(256); + public static final BigInteger MAX_VALUE = _2_256.subtract(BigInteger.ONE); + public static final DataWord ZERO = new DataWord(new byte[32]); // don't push it in to the stack + public static final DataWord ZERO_EMPTY_ARRAY = new DataWord(new byte[0]); // don't push it in to the stack private byte[] data = new byte[32]; @@ -60,6 +61,7 @@ public class DataWord implements Comparable { public byte[] getNoLeadZeroesData() { return ByteUtil.stripLeadingZeroes(data); } + public byte[] getLast20Bytes() { return Arrays.copyOfRange(data, 12, data.length); } @@ -78,7 +80,7 @@ public class DataWord implements Comparable { */ public int intValue() { BigDecimal tmpValue = new BigDecimal(this.value()); - if(this.bytesOccupied() > 4) + if (this.bytesOccupied() > 4) return Integer.MAX_VALUE; return tmpValue.intValueExact(); } @@ -148,8 +150,8 @@ public class DataWord implements Comparable { this.data[i] = (byte) ~this.data[i]; } - for (int i = this.data.length - 1; i >= 0 ; --i) { - this.data[i] = (byte) (1 + this.data[i] & 0xFF); + for (int i = this.data.length - 1; i >= 0; --i) { + this.data[i] = (byte) (1 + this.data[i] & 0xFF); if (this.data[i] != 0) break; } } @@ -186,7 +188,7 @@ public class DataWord implements Comparable { } // TODO: improve with no BigInteger - public void div(DataWord word) { + public void div(DataWord word) { if (word.isZero()) { this.and(ZERO); @@ -305,7 +307,7 @@ public class DataWord implements Comparable { } } - public int bytesOccupied(){ + public int bytesOccupied() { int firstNonZero = ByteUtil.firstNonZeroByte(data); if (firstNonZero == -1) return 0; return 31 - firstNonZero + 1; diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/GasCost.java b/ethereumj-core/src/main/java/org/ethereum/vm/GasCost.java index 36115d3b..ca37a168 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/GasCost.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/GasCost.java @@ -8,51 +8,97 @@ package org.ethereum.vm; */ public class GasCost { - /** Cost 1 gas */ + /** + * Cost 1 gas + */ public static int STEP = 1; - /** Cost 20 gas */ + /** + * Cost 20 gas + */ public static int BALANCE = 20; - /** Cost 10 gas */ + /** + * Cost 10 gas + */ public static int SHA3 = 10; - /** Cost 10 gas */ + /** + * Cost 10 gas + */ public static int SHA3_WORD = 10; - /** Cost 20 gas */ + /** + * Cost 20 gas + */ public static int SLOAD = 20; - /** Cost 0 gas */ + /** + * Cost 0 gas + */ public static int STOP = 0; - /** Cost 0 gas */ + /** + * Cost 0 gas + */ public static int SUICIDE = 0; - /** Cost 300 gas */ + /** + * Cost 300 gas + */ public static int SSTORE = 300; - /** Cost 100 gas */ + /** + * Cost 100 gas + */ public static int RESET_SSTORE = 100; - /** Cost 100 gas */ + /** + * Cost 100 gas + */ public static int REFUND_SSTORE = 100; - /** Cost 100 gas */ + /** + * Cost 100 gas + */ public static int CREATE = 100; - /** Cost 1 gas */ + /** + * Cost 1 gas + */ public static int CREATE_DATA_BYTE = 5; - /** Cost 20 gas */ + /** + * Cost 20 gas + */ public static int CALL = 20; - /** Cost 1 gas */ + /** + * Cost 1 gas + */ public static int MEMORY = 1; - /** Cost 5 gas */ + /** + * Cost 5 gas + */ public static int TX_NO_ZERO_DATA = 5; - /** Cost 1 gas */ + /** + * Cost 1 gas + */ public static int TX_ZERO_DATA = 1; - /** Cost 500 gas */ + /** + * Cost 500 gas + */ public static int TRANSACTION = 500; - /** Cost 32 gas */ + /** + * Cost 32 gas + */ public static int LOG_GAS = 32; - /** Cost 1 gas */ + /** + * Cost 1 gas + */ public static int LOG_DATA_GAS = 1; - /** Cost 32 gas */ + /** + * Cost 32 gas + */ public static int LOG_TOPIC_GAS = 32; - /** Cost 1 gas */ + /** + * Cost 1 gas + */ public static int COPY_GAS = 1; - /** Cost 1 gas */ + /** + * Cost 1 gas + */ public static int EXP_GAS = 1; - /** Cost 1 gas */ + /** + * Cost 1 gas + */ public static int EXP_BYTE_GAS = 1; diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/LogInfo.java b/ethereumj-core/src/main/java/org/ethereum/vm/LogInfo.java index ae5f8cda..13a12ecd 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/LogInfo.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/LogInfo.java @@ -30,19 +30,19 @@ public class LogInfo { /* Log info in encoded form */ private byte[] rlpEncoded; - public LogInfo(byte[] rlp){ + public LogInfo(byte[] rlp) { - RLPList params = RLP.decode2(rlp); + RLPList params = RLP.decode2(rlp); RLPList logInfo = (RLPList) params.get(0); - RLPItem address = (RLPItem)logInfo.get(0); - RLPList topics = (RLPList)logInfo.get(1); - RLPItem data = (RLPItem)logInfo.get(2); + RLPItem address = (RLPItem) logInfo.get(0); + RLPList topics = (RLPList) logInfo.get(1); + RLPItem data = (RLPItem) logInfo.get(2); this.address = address.getRLPData() != null ? address.getRLPData() : new byte[]{}; - this.data = data.getRLPData() != null ? data.getRLPData() : new byte[]{}; + this.data = data.getRLPData() != null ? data.getRLPData() : new byte[]{}; - for (int i = 0; i < topics.size(); ++i){ + for (int i = 0; i < topics.size(); ++i) { byte[] topic = topics.get(i).getRLPData(); this.topics.add(new DataWord(topic)); @@ -52,9 +52,9 @@ public class LogInfo { } public LogInfo(byte[] address, List topics, byte[] data) { - this.address = (address != null) ? address : new byte[]{} ; - this.topics = (topics != null) ? topics : new ArrayList(); - this.data = (data != null) ? data : new byte[]{} ; + this.address = (address != null) ? address : new byte[]{}; + this.topics = (topics != null) ? topics : new ArrayList(); + this.data = (data != null) ? data : new byte[]{}; } public byte[] getAddress() { @@ -72,13 +72,13 @@ public class LogInfo { /* [address, [topic, topic ...] data] */ public byte[] getEncoded() { - byte[] addressEncoded = RLP.encodeElement(this.address); + byte[] addressEncoded = RLP.encodeElement(this.address); byte[][] topicsEncoded = null; - if (topics != null){ + if (topics != null) { topicsEncoded = new byte[topics.size()][]; int i = 0; - for( DataWord topic : topics ){ + for (DataWord topic : topics) { byte[] topicData = topic.getData(); topicsEncoded[i] = RLP.encodeElement(topicData); ++i; @@ -91,7 +91,7 @@ public class LogInfo { public Bloom getBloom() { Bloom ret = Bloom.create(HashUtil.sha3(address)); - for(DataWord topic:topics) { + for (DataWord topic : topics) { byte[] topicData = topic.getData(); ret.or(Bloom.create(HashUtil.sha3(topicData))); } @@ -104,7 +104,7 @@ public class LogInfo { StringBuffer topicsStr = new StringBuffer(); topicsStr.append("["); - for (DataWord topic: topics){ + for (DataWord topic : topics) { String topicStr = Hex.toHexString(topic.getData()); topicsStr.append(topicStr).append(" "); } diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/MessageCall.java b/ethereumj-core/src/main/java/org/ethereum/vm/MessageCall.java index f8075831..3fc047e7 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/MessageCall.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/MessageCall.java @@ -12,26 +12,42 @@ public class MessageCall { POST; } - /** Type of internal call. Either CALL, STATELESS or POST */ + /** + * Type of internal call. Either CALL, STATELESS or POST + */ private MsgType type; - /** gas to pay for the call, remaining gas will be refunded to the caller */ + /** + * gas to pay for the call, remaining gas will be refunded to the caller + */ private DataWord gas; - /** address of account which code to call */ + /** + * address of account which code to call + */ private DataWord codeAddress; - /** the value that can be transfer along with the code execution */ + /** + * the value that can be transfer along with the code execution + */ private DataWord endowment; - /** start of memory to be input data to the call */ + /** + * start of memory to be input data to the call + */ private DataWord inDataOffs; - /** size of memory to be input data to the call */ + /** + * size of memory to be input data to the call + */ private DataWord inDataSize; - /** start of memory to be output of the call */ + /** + * start of memory to be output of the call + */ private DataWord outDataOffs; - /** size of memory to be output data to the call */ + /** + * size of memory to be output data to the call + */ private DataWord outDataSize; public MessageCall(MsgType type, DataWord gas, DataWord codeAddress, - DataWord endowment, DataWord inDataOffs, DataWord inDataSize) { + DataWord endowment, DataWord inDataOffs, DataWord inDataSize) { this.type = type; this.gas = gas; this.codeAddress = codeAddress; @@ -41,8 +57,8 @@ public class MessageCall { } public MessageCall(MsgType type, DataWord gas, DataWord codeAddress, - DataWord endowment, DataWord inDataOffs, DataWord inDataSize, - DataWord outDataOffs, DataWord outDataSize) { + DataWord endowment, DataWord inDataOffs, DataWord inDataSize, + DataWord outDataOffs, DataWord outDataSize) { this(type, gas, codeAddress, endowment, inDataOffs, inDataSize); this.outDataOffs = outDataOffs; this.outDataSize = outDataSize; diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/OpCode.java b/ethereumj-core/src/main/java/org/ethereum/vm/OpCode.java index 2d74c398..ff4946eb 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/OpCode.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/OpCode.java @@ -10,289 +10,529 @@ import java.util.Map; */ public enum OpCode { - /** Halts execution (0x00) */ - STOP(0x00, 0), + /** + * Halts execution (0x00) + */ + STOP(0x00, 0), /* Arithmetic Operations */ - /** (0x01) Addition operation */ + /** + * (0x01) Addition operation + */ ADD(0x01, 2), - /** (0x02) Multiplication operation */ + /** + * (0x02) Multiplication operation + */ MUL(0x02, 2), - /** (0x03) Subtraction operations */ + /** + * (0x03) Subtraction operations + */ SUB(0x03, 2), - /** (0x04) Integer division operation */ + /** + * (0x04) Integer division operation + */ DIV(0x04, 2), - /** (0x05) Signed integer division operation*/ + /** + * (0x05) Signed integer division operation + */ SDIV(0x05, 2), - /** (0x06) Modulo remainder operation */ + /** + * (0x06) Modulo remainder operation + */ MOD(0x06, 2), - /** (0x07) Signed modulo remainder operation*/ + /** + * (0x07) Signed modulo remainder operation + */ SMOD(0x07, 2), - /** (0x08) Addition combined with modulo - * remainder operation */ + /** + * (0x08) Addition combined with modulo + * remainder operation + */ ADDMOD(0x08, 3), - /** (0x09) Multiplication combined with modulo - * remainder operation */ + /** + * (0x09) Multiplication combined with modulo + * remainder operation + */ MULMOD(0x09, 3), - /** (0x0a) Exponential operation */ + /** + * (0x0a) Exponential operation + */ EXP(0x0a, 2), - /** (0x0b) Extend length of signed integer */ + /** + * (0x0b) Extend length of signed integer + */ SIGNEXTEND(0x0b, 2), /* Bitwise Logic & Comparison Operations */ - /** (0x10) Less-than comparison */ + /** + * (0x10) Less-than comparison + */ LT(0X10, 2), - /** (0x11) Greater-than comparison */ + /** + * (0x11) Greater-than comparison + */ GT(0X11, 2), - /** (0x12) Signed less-than comparison */ + /** + * (0x12) Signed less-than comparison + */ SLT(0X12, 2), - /** (0x13) Signed greater-than comparison */ + /** + * (0x13) Signed greater-than comparison + */ SGT(0X13, 2), - /** (0x14) Equality comparison */ + /** + * (0x14) Equality comparison + */ EQ(0X14, 2), - /** (0x15) Negation operation */ + /** + * (0x15) Negation operation + */ ISZERO(0x15, 1), - /** (0x16) Bitwise AND operation */ + /** + * (0x16) Bitwise AND operation + */ AND(0x16, 2), - /** (0x17) Bitwise OR operation */ + /** + * (0x17) Bitwise OR operation + */ OR(0x17, 2), - /** (0x18) Bitwise XOR operation */ + /** + * (0x18) Bitwise XOR operation + */ XOR(0x18, 2), - /** (0x19) Bitwise NOT operationr */ + /** + * (0x19) Bitwise NOT operationr + */ NOT(0x19, 1), - /** (0x1a) Retrieve single byte from word */ + /** + * (0x1a) Retrieve single byte from word + */ BYTE(0x1a, 2), /* Cryptographic Operations */ - /** (0x20) Compute SHA3-256 hash */ - SHA3(0x20, 2), + /** + * (0x20) Compute SHA3-256 hash + */ + SHA3(0x20, 2), /* Environmental Information */ - /** (0x30) Get address of currently - * executing account */ + /** + * (0x30) Get address of currently + * executing account + */ ADDRESS(0x30, 0), - /** (0x31) Get balance of the given account */ + /** + * (0x31) Get balance of the given account + */ BALANCE(0x31, 1), - /** (0x32) Get execution origination address*/ + /** + * (0x32) Get execution origination address + */ ORIGIN(0x32, 0), - /** (0x33) Get caller address */ + /** + * (0x33) Get caller address + */ CALLER(0x33, 0), - /** (0x34) Get deposited value by the + /** + * (0x34) Get deposited value by the * instruction/transaction responsible - * for this execution */ + * for this execution + */ CALLVALUE(0x34, 0), - /** (0x35) Get input data of current - * environment */ + /** + * (0x35) Get input data of current + * environment + */ CALLDATALOAD(0x35, 1), - /** (0x36) Get size of input data in current - * environment */ + /** + * (0x36) Get size of input data in current + * environment + */ CALLDATASIZE(0x36, 0), - /** (0x37) Copy input data in current - * environment to memory */ + /** + * (0x37) Copy input data in current + * environment to memory + */ CALLDATACOPY(0x37, 3), - /** (0x38) Get size of code running in - * current environment */ + /** + * (0x38) Get size of code running in + * current environment + */ CODESIZE(0x38, 0), - /** (0x39) Copy code running in current - * environment to memory */ + /** + * (0x39) Copy code running in current + * environment to memory + */ CODECOPY(0x39, 3), // [len code_start mem_start CODECOPY] - /** (0x3a) Get price of gas in current - * environment */ + /** + * (0x3a) Get price of gas in current + * environment + */ GASPRICE(0x3a, 0), - /** (0x3b) Get size of code running in - * current environment with given offset */ + /** + * (0x3b) Get size of code running in + * current environment with given offset + */ EXTCODESIZE(0x3b, 1), - /** (0x3c) Copy code running in current - * environment to memory with given offset */ + /** + * (0x3c) Copy code running in current + * environment to memory with given offset + */ EXTCODECOPY(0x3c, 4), /* Block Information */ - /** (0x40) Get hash of most recent - * complete block */ + /** + * (0x40) Get hash of most recent + * complete block + */ PREVHASH(0x40, 0), - /** (0x41) Get the block’s coinbase address */ + /** + * (0x41) Get the block’s coinbase address + */ COINBASE(0x41, 0), - /** (x042) Get the block’s timestamp */ + /** + * (x042) Get the block’s timestamp + */ TIMESTAMP(0x42, 0), - /** (0x43) Get the block’s number */ + /** + * (0x43) Get the block’s number + */ NUMBER(0x43, 0), - /** (0x44) Get the block’s difficulty */ + /** + * (0x44) Get the block’s difficulty + */ DIFFICULTY(0x44, 0), - /** (0x45) Get the block’s gas limit */ + /** + * (0x45) Get the block’s gas limit + */ GASLIMIT(0x45, 0), /* Memory, Storage and Flow Operations */ - /** (0x50) Remove item from stack */ - POP(0x50, 1), - /** (0x51) Load word from memory */ + /** + * (0x50) Remove item from stack + */ + POP(0x50, 1), + /** + * (0x51) Load word from memory + */ MLOAD(0x51, 1), - /** (0x52) Save word to memory */ + /** + * (0x52) Save word to memory + */ MSTORE(0x52, 2), - /** (0x53) Save byte to memory */ + /** + * (0x53) Save byte to memory + */ MSTORE8(0x53, 2), - /** (0x54) Load word from storage */ + /** + * (0x54) Load word from storage + */ SLOAD(0x54, 1), - /** (0x55) Save word to storage */ + /** + * (0x55) Save word to storage + */ SSTORE(0x55, 2), - /** (0x56) Alter the program counter */ + /** + * (0x56) Alter the program counter + */ JUMP(0x56, 1), - /** (0x57) Conditionally alter the program - * counter */ + /** + * (0x57) Conditionally alter the program + * counter + */ JUMPI(0x57, 2), - /** (0x58) Get the program counter */ + /** + * (0x58) Get the program counter + */ PC(0x58, 0), - /** (0x59) Get the size of active memory */ + /** + * (0x59) Get the size of active memory + */ MSIZE(0x59, 0), - /** (0x5a) Get the amount of available gas */ + /** + * (0x5a) Get the amount of available gas + */ GAS(0x5a, 0), - /** (0x5b) */ + /** + * (0x5b) + */ JUMPDEST(0x5b, 0), /* Push Operations */ - /** (0x60) Place 1-byte item on stack */ + /** + * (0x60) Place 1-byte item on stack + */ PUSH1(0x60, 0), - /** (0x61) Place 2-byte item on stack */ + /** + * (0x61) Place 2-byte item on stack + */ PUSH2(0x61, 0), - /** (0x62) Place 3-byte item on stack */ + /** + * (0x62) Place 3-byte item on stack + */ PUSH3(0x62, 0), - /** (0x63) Place 4-byte item on stack */ + /** + * (0x63) Place 4-byte item on stack + */ PUSH4(0x63, 0), - /** (0x64) Place 5-byte item on stack */ + /** + * (0x64) Place 5-byte item on stack + */ PUSH5(0x64, 0), - /** (0x65) Place 6-byte item on stack */ + /** + * (0x65) Place 6-byte item on stack + */ PUSH6(0x65, 0), - /** (0x66) Place 7-byte item on stack */ + /** + * (0x66) Place 7-byte item on stack + */ PUSH7(0x66, 0), - /** (0x67) Place 8-byte item on stack */ + /** + * (0x67) Place 8-byte item on stack + */ PUSH8(0x67, 0), - /** (0x68) Place 9-byte item on stack */ + /** + * (0x68) Place 9-byte item on stack + */ PUSH9(0x68, 0), - /** (0x69) Place 10-byte item on stack */ + /** + * (0x69) Place 10-byte item on stack + */ PUSH10(0x69, 0), - /** (0x6a) Place 11-byte item on stack */ + /** + * (0x6a) Place 11-byte item on stack + */ PUSH11(0x6a, 0), - /** (0x6b) Place 12-byte item on stack */ + /** + * (0x6b) Place 12-byte item on stack + */ PUSH12(0x6b, 0), - /** (0x6c) Place 13-byte item on stack */ + /** + * (0x6c) Place 13-byte item on stack + */ PUSH13(0x6c, 0), - /** (0x6d) Place 14-byte item on stack */ + /** + * (0x6d) Place 14-byte item on stack + */ PUSH14(0x6d, 0), - /** (0x6e) Place 15-byte item on stack */ + /** + * (0x6e) Place 15-byte item on stack + */ PUSH15(0x6e, 0), - /** (0x6f) Place 16-byte item on stack */ + /** + * (0x6f) Place 16-byte item on stack + */ PUSH16(0x6f, 0), - /** (0x70) Place 17-byte item on stack */ + /** + * (0x70) Place 17-byte item on stack + */ PUSH17(0x70, 0), - /** (0x71) Place 18-byte item on stack */ + /** + * (0x71) Place 18-byte item on stack + */ PUSH18(0x71, 0), - /** (0x72) Place 19-byte item on stack */ + /** + * (0x72) Place 19-byte item on stack + */ PUSH19(0x72, 0), - /** (0x73) Place 20-byte item on stack */ + /** + * (0x73) Place 20-byte item on stack + */ PUSH20(0x73, 0), - /** (0x74) Place 21-byte item on stack */ + /** + * (0x74) Place 21-byte item on stack + */ PUSH21(0x74, 0), - /** (0x75) Place 22-byte item on stack */ + /** + * (0x75) Place 22-byte item on stack + */ PUSH22(0x75, 0), - /** (0x76) Place 23-byte item on stack */ + /** + * (0x76) Place 23-byte item on stack + */ PUSH23(0x76, 0), - /** (0x77) Place 24-byte item on stack */ + /** + * (0x77) Place 24-byte item on stack + */ PUSH24(0x77, 0), - /** (0x78) Place 25-byte item on stack */ + /** + * (0x78) Place 25-byte item on stack + */ PUSH25(0x78, 0), - /** (0x79) Place 26-byte item on stack */ + /** + * (0x79) Place 26-byte item on stack + */ PUSH26(0x79, 0), - /** (0x7a) Place 27-byte item on stack */ + /** + * (0x7a) Place 27-byte item on stack + */ PUSH27(0x7a, 0), - /** (0x7b) Place 28-byte item on stack */ + /** + * (0x7b) Place 28-byte item on stack + */ PUSH28(0x7b, 0), - /** (0x7c) Place 29-byte item on stack */ + /** + * (0x7c) Place 29-byte item on stack + */ PUSH29(0x7c, 0), - /** (0x7d) Place 30-byte item on stack */ + /** + * (0x7d) Place 30-byte item on stack + */ PUSH30(0x7d, 0), - /** (0x7e) Place 31-byte item on stack */ + /** + * (0x7e) Place 31-byte item on stack + */ PUSH31(0x7e, 0), - /** (0x7f) Place 32-byte (full word) - * item on stack */ + /** + * (0x7f) Place 32-byte (full word) + * item on stack + */ PUSH32(0x7f, 0), /* Duplicate Nth item from the stack */ - /** (0x80) Duplicate 1st item on stack */ + /** + * (0x80) Duplicate 1st item on stack + */ DUP1(0x80, 1), - /** (0x81) Duplicate 2nd item on stack */ + /** + * (0x81) Duplicate 2nd item on stack + */ DUP2(0x81, 2), - /** (0x82) Duplicate 3rd item on stack */ + /** + * (0x82) Duplicate 3rd item on stack + */ DUP3(0x82, 3), - /** (0x83) Duplicate 4th item on stack */ + /** + * (0x83) Duplicate 4th item on stack + */ DUP4(0x83, 4), - /** (0x84) Duplicate 5th item on stack */ + /** + * (0x84) Duplicate 5th item on stack + */ DUP5(0x84, 5), - /** (0x85) Duplicate 6th item on stack */ + /** + * (0x85) Duplicate 6th item on stack + */ DUP6(0x85, 6), - /** (0x86) Duplicate 7th item on stack */ + /** + * (0x86) Duplicate 7th item on stack + */ DUP7(0x86, 7), - /** (0x87) Duplicate 8th item on stack */ + /** + * (0x87) Duplicate 8th item on stack + */ DUP8(0x87, 8), - /** (0x88) Duplicate 9th item on stack */ + /** + * (0x88) Duplicate 9th item on stack + */ DUP9(0x88, 9), - /** (0x89) Duplicate 10th item on stack */ + /** + * (0x89) Duplicate 10th item on stack + */ DUP10(0x89, 10), - /** (0x8a) Duplicate 11th item on stack */ + /** + * (0x8a) Duplicate 11th item on stack + */ DUP11(0x8a, 11), - /** (0x8b) Duplicate 12th item on stack */ + /** + * (0x8b) Duplicate 12th item on stack + */ DUP12(0x8b, 12), - /** (0x8c) Duplicate 13th item on stack */ + /** + * (0x8c) Duplicate 13th item on stack + */ DUP13(0x8c, 13), - /** (0x8d) Duplicate 14th item on stack */ + /** + * (0x8d) Duplicate 14th item on stack + */ DUP14(0x8d, 14), - /** (0x8e) Duplicate 15th item on stack */ + /** + * (0x8e) Duplicate 15th item on stack + */ DUP15(0x8e, 15), - /** (0x8f) Duplicate 16th item on stack */ + /** + * (0x8f) Duplicate 16th item on stack + */ DUP16(0x8f, 16), /* Swap the Nth item from the stack with the top */ - /** (0x90) Exchange 2nd item from stack with the top */ + /** + * (0x90) Exchange 2nd item from stack with the top + */ SWAP1(0x90, 2), - /** (0x91) Exchange 3rd item from stack with the top */ + /** + * (0x91) Exchange 3rd item from stack with the top + */ SWAP2(0x91, 3), - /** (0x92) Exchange 4th item from stack with the top */ + /** + * (0x92) Exchange 4th item from stack with the top + */ SWAP3(0x92, 4), - /** (0x93) Exchange 5th item from stack with the top */ + /** + * (0x93) Exchange 5th item from stack with the top + */ SWAP4(0x93, 5), - /** (0x94) Exchange 6th item from stack with the top */ + /** + * (0x94) Exchange 6th item from stack with the top + */ SWAP5(0x94, 6), - /** (0x95) Exchange 7th item from stack with the top */ + /** + * (0x95) Exchange 7th item from stack with the top + */ SWAP6(0x95, 7), - /** (0x96) Exchange 8th item from stack with the top */ + /** + * (0x96) Exchange 8th item from stack with the top + */ SWAP7(0x96, 8), - /** (0x97) Exchange 9th item from stack with the top */ + /** + * (0x97) Exchange 9th item from stack with the top + */ SWAP8(0x97, 9), - /** (0x98) Exchange 10th item from stack with the top */ + /** + * (0x98) Exchange 10th item from stack with the top + */ SWAP9(0x98, 10), - /** (0x99) Exchange 11th item from stack with the top */ + /** + * (0x99) Exchange 11th item from stack with the top + */ SWAP10(0x99, 11), - /** (0x9a) Exchange 12th item from stack with the top */ + /** + * (0x9a) Exchange 12th item from stack with the top + */ SWAP11(0x9a, 12), - /** (0x9b) Exchange 13th item from stack with the top */ + /** + * (0x9b) Exchange 13th item from stack with the top + */ SWAP12(0x9b, 13), - /** (0x9c) Exchange 14th item from stack with the top */ + /** + * (0x9c) Exchange 14th item from stack with the top + */ SWAP13(0x9c, 14), - /** (0x9d) Exchange 15th item from stack with the top */ + /** + * (0x9d) Exchange 15th item from stack with the top + */ SWAP14(0x9d, 15), - /** (0x9e) Exchange 16th item from stack with the top */ + /** + * (0x9e) Exchange 16th item from stack with the top + */ SWAP15(0x9e, 16), - /** (0x9f) Exchange 17th item from stack with the top */ + /** + * (0x9f) Exchange 17th item from stack with the top + */ SWAP16(0x9f, 17), - /** (0xa[n]) log some data for some addres with 0..n tags [addr [tag0..tagn] data] */ + /** + * (0xa[n]) log some data for some addres with 0..n tags [addr [tag0..tagn] data] + */ LOG0(0xa0, 2), LOG1(0xa1, 3), LOG2(0xa2, 4), @@ -301,17 +541,28 @@ public enum OpCode { /* System operations */ - /** (0xf0) Create a new account with associated code */ + /** + * (0xf0) Create a new account with associated code + */ CREATE(0xf0, 3), // [in_size] [in_offs] [gas_val] CREATE - /** (cxf1) Message-call into an account */ - CALL(0xf1, 7), // [out_data_size] [out_data_start] [in_data_size] [in_data_start] [value] [to_addr] [gas] CALL - /** (0xf2) Calls self, but grabbing the code from the - * TO argument instead of from one's own address */ + /** + * (cxf1) Message-call into an account + */ + CALL(0xf1, 7), // [out_data_size] [out_data_start] [in_data_size] [in_data_start] [value] [to_addr] + // [gas] CALL + /** + * (0xf2) Calls self, but grabbing the code from the + * TO argument instead of from one's own address + */ CALLCODE(0xf2, 7), - /** (0xf3) Halt execution returning output data */ + /** + * (0xf3) Halt execution returning output data + */ RETURN(0xf3, 2), - /** (0xff) Halt execution and register account for - * later deletion */ + /** + * (0xff) Halt execution and register account for + * later deletion + */ SUICIDE(0xff, 1); private byte opcode; @@ -350,7 +601,7 @@ public enum OpCode { } public static boolean contains(String code) { - return stringToByteMap.containsKey(code.trim()); + return stringToByteMap.containsKey(code.trim()); } public static byte byteVal(String code) { diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/Program.java b/ethereumj-core/src/main/java/org/ethereum/vm/Program.java index 58b46266..88dbb530 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/Program.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/Program.java @@ -28,6 +28,7 @@ import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 01/06/2014 10:45 */ @@ -48,11 +49,11 @@ public class Program { ProgramResult result = new ProgramResult(); ProgramTrace programTrace = new ProgramTrace(); - byte[] ops; - int pc = 0; - byte lastOp = 0; - byte previouslyExecutedOp = 0; - boolean stopped = false; + byte[] ops; + int pc = 0; + byte lastOp = 0; + byte previouslyExecutedOp = 0; + boolean stopped = false; ProgramInvoke invokeData; @@ -76,13 +77,14 @@ public class Program { } public byte getCurrentOp() { - if(ops.length == 0) + if (ops.length == 0) return 0; return ops[pc]; } /** * Last Op can only be set publicly (no getLastOp method), is used for logging + * * @param op */ public void setLastOp(byte op) { @@ -91,6 +93,7 @@ public class Program { /** * Should be set only after the OP is fully executed + * * @param op */ public void setPreviouslyExecutedOp(byte op) { @@ -99,6 +102,7 @@ public class Program { /** * returns the last fully executed OP + * * @return */ public byte getPreviouslyExecutedOp() { @@ -178,6 +182,7 @@ public class Program { /** * Verifies that the stack is at least stackSize + * * @param stackSize int * @throws StackTooSmallException If the stack is * smaller than stackSize @@ -246,7 +251,7 @@ public class Program { allocateMemory(offset, size); byte[] chunk; if (memory != null && size != 0) - chunk = Arrays.copyOfRange(memory.array(), offset, offset+size); + chunk = Arrays.copyOfRange(memory.array(), offset, offset + size); else chunk = new byte[size]; return ByteBuffer.wrap(chunk); @@ -254,7 +259,7 @@ public class Program { /** * Allocates extra memory in the program for - * a specified size, calculated from a given offset + * a specified size, calculated from a given offset * * @param offset the memory address offset * @param size the number of bytes to allocate @@ -264,7 +269,7 @@ public class Program { int memSize = memory != null ? memory.limit() : 0; double newMemSize = Math.max(memSize, size != 0 ? Math.ceil((double) (offset + size) / 32) * 32 : 0); - ByteBuffer tmpMem = ByteBuffer.allocate((int)newMemSize); + ByteBuffer tmpMem = ByteBuffer.allocate((int) newMemSize); if (memory != null) tmpMem.put(memory.array(), 0, memory.limit()); memory = tmpMem; @@ -301,8 +306,8 @@ public class Program { this.spendGas(gasLimit.longValue(), "internal call"); // [2] CREATE THE CONTRACT ADDRESS - byte[] nonce = result.getRepository().getNonce(senderAddress).toByteArray(); - byte[] newAddress = HashUtil.calcNewAddr(this.getOwnerAddress().getLast20Bytes(), nonce); + byte[] nonce = result.getRepository().getNonce(senderAddress).toByteArray(); + byte[] newAddress = HashUtil.calcNewAddr(this.getOwnerAddress().getLast20Bytes(), nonce); result.getRepository().createAccount(newAddress); if (invokeData.byTestingSuite()) { @@ -358,11 +363,11 @@ public class Program { } // 4. CREATE THE CONTRACT OUT OF RETURN - byte[] code = result.getHReturn().array(); + byte[] code = result.getHReturn().array(); long storageCost = code.length * GasCost.CREATE_DATA_BYTE; long afterSpend = invokeData.getGas().longValue() - storageCost - result.getGasUsed(); - if (afterSpend < 0){ + if (afterSpend < 0) { track.saveCode(newAddress, EMPTY_BYTE_ARRAY); } else { @@ -414,9 +419,9 @@ public class Program { // 2.1 PERFORM THE GAS VALUE TX // (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" + - "fromAddress={}, codeAddress={}", + "fromAddress={}, codeAddress={}", Hex.toHexString(senderAddress), Hex.toHexString(codeAddress)); throw new OutOfGasException(); } @@ -493,7 +498,7 @@ public class Program { BigInteger refundGas = msg.getGas().value().subtract(BigInteger.valueOf(result.getGasUsed())); if (refundGas.signum() == 1) { this.refundGas(refundGas.longValue(), "remaining gas from the internal call"); - if(gasLogger.isInfoEnabled()) + if (gasLogger.isInfoEnabled()) gasLogger.info("The remaining gas refunded, account: [{}], gas: [{}] ", Hex.toHexString(senderAddress), refundGas.toString()); @@ -607,7 +612,7 @@ public class Program { } public DataWord getPrevHash() { - return invokeData.getPrevHash().clone(); + return invokeData.getPrevHash().clone(); } public DataWord getCoinbase() { @@ -615,7 +620,7 @@ public class Program { } public DataWord getTimestamp() { - return invokeData.getTimestamp().clone(); + return invokeData.getTimestamp().clone(); } public DataWord getNumber() { @@ -623,7 +628,7 @@ public class Program { } public DataWord getDifficulty() { - return invokeData.getDifficulty().clone(); + return invokeData.getDifficulty().clone(); } public DataWord getGaslimit() { @@ -646,7 +651,7 @@ public class Program { byte value = memory.get(i); // Check if value is ASCII - String character = ((byte) 0x20 <= value && value <= (byte) 0x7e) ? new String(new byte[] { value }) : "?"; + String character = ((byte) 0x20 <= value && value <= (byte) 0x7e) ? new String(new byte[]{value}) : "?"; firstLine.append(character).append(""); secondLine.append(ByteUtil.oneByteToHexString(value)).append(" "); @@ -655,7 +660,7 @@ public class Program { memoryData.append("").append(tmp).append(" "); memoryData.append(firstLine).append(" "); memoryData.append(secondLine); - if (i+1 < memory.limit()) memoryData.append("\n"); + if (i + 1 < memory.limit()) memoryData.append("\n"); firstLine.setLength(0); secondLine.setLength(0); } @@ -677,7 +682,7 @@ public class Program { ContractDetails contractDetails = this.result.getRepository(). getContractDetails(this.programAddress.getLast20Bytes()); StringBuilder storageData = new StringBuilder(); - if(contractDetails != null) { + if (contractDetails != null) { List storageKeys = new ArrayList<>(contractDetails.getStorage().keySet()); Collections.sort((List) storageKeys); for (DataWord key : storageKeys) { @@ -697,7 +702,7 @@ public class Program { if ((i + 1) % 16 == 0) { String tmp = String.format("[%4s]-[%4s]", Integer.toString(i - 15, 16), Integer.toString(i, 16)).replace(" ", "0"); - memoryData.append("" ).append(tmp).append(" "); + memoryData.append("").append(tmp).append(" "); memoryData.append(oneLine); if (i < memory.limit()) memoryData.append("\n"); oneLine.setLength(0); @@ -709,7 +714,7 @@ public class Program { for (int i = 0; i < ops.length; ++i) { String tmpString = Integer.toString(ops[i] & 0xFF, 16); - tmpString = tmpString.length() == 1? "0" + tmpString : tmpString; + tmpString = tmpString.length() == 1 ? "0" + tmpString : tmpString; if (i != pc) opsString.append(tmpString); @@ -756,7 +761,7 @@ public class Program { } } - public void saveOpTrace(){ + public void saveOpTrace() { if (pc >= ops.length) return; @@ -775,7 +780,7 @@ public class Program { programTrace.addOp(op); } - public void saveProgramTraceToFile(String fileName){ + public void saveProgramTraceToFile(String fileName) { if (!CONFIG.vmTrace()) return; @@ -797,7 +802,7 @@ public class Program { objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); String originalJson = programTrace.getJsonString(); - JsonNode tree = objectMapper .readTree(originalJson); + JsonNode tree = objectMapper.readTree(originalJson); String formattedJson = objectMapper.writeValueAsString(tree); bw.write(formattedJson); @@ -818,7 +823,7 @@ public class Program { } public static String stringify(byte[] code, int index, String result) { - if(code == null || code.length == 0) + if (code == null || code.length == 0) return result; OpCode op = OpCode.code(code[index]); @@ -832,7 +837,7 @@ public class Program { result += ' ' + op.name() + ' '; int nPush = op.val() - OpCode.PUSH1.val() + 1; - byte[] data = Arrays.copyOfRange(code, index+1, index + nPush + 1); + byte[] data = Arrays.copyOfRange(code, index + 1, index + nPush + 1); result += new BigInteger(1, data).toString() + ' '; continuedCode = Arrays.copyOfRange(code, index + nPush + 1, code.length); @@ -855,13 +860,16 @@ public class Program { } @SuppressWarnings("serial") - public class OutOfGasException extends RuntimeException {} + public class OutOfGasException extends RuntimeException { + } @SuppressWarnings("serial") - public class IllegalOperationException extends RuntimeException {} + public class IllegalOperationException extends RuntimeException { + } @SuppressWarnings("serial") - public class BadJumpDestinationException extends RuntimeException {} + public class BadJumpDestinationException extends RuntimeException { + } @SuppressWarnings("serial") public class StackTooSmallException extends RuntimeException { @@ -873,17 +881,16 @@ public class Program { /** * used mostly for testing reasons */ - public ByteBuffer getMemory(){ + public ByteBuffer getMemory() { return memory; } /** * used mostly for testing reasons */ - public void initMem(ByteBuffer memory){ + public void initMem(ByteBuffer memory) { this.memory = memory; } - } \ No newline at end of file diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvoke.java b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvoke.java index d013c3b2..42a04710 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvoke.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvoke.java @@ -4,33 +4,50 @@ import org.ethereum.facade.Repository; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 03/06/2014 14:59 */ public interface ProgramInvoke { public DataWord getOwnerAddress(); + public DataWord getBalance(); + public DataWord getOriginAddress(); + public DataWord getCallerAddress(); + public DataWord getMinGasPrice(); + public DataWord getGas(); + public DataWord getCallValue(); + public DataWord getDataSize(); + public DataWord getDataValue(DataWord indexData); - public byte[] getDataCopy(DataWord offsetData, DataWord lengthData); + + public byte[] getDataCopy(DataWord offsetData, DataWord lengthData); + public int countNonZeroData(); - public DataWord getPrevHash(); + public DataWord getPrevHash(); + public DataWord getCoinbase(); + public DataWord getTimestamp(); + public DataWord getNumber(); + public DataWord getDifficulty(); + public DataWord getGaslimit(); public Repository getRepository(); public boolean byTransaction(); + boolean byTestingSuite(); public int getCallDeep(); diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactory.java b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactory.java index 65972700..c0c1ed46 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactory.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactory.java @@ -16,10 +16,11 @@ import java.math.BigInteger; public interface ProgramInvokeFactory { public ProgramInvoke createProgramInvoke(Transaction tx, Block block, Repository repository); + public ProgramInvoke createProgramInvoke(Program program, DataWord toAddress, - DataWord inValue, DataWord inGas, - BigInteger balanceInt, byte[] dataIn, - Repository repository); + DataWord inValue, DataWord inGas, + BigInteger balanceInt, byte[] dataIn, + Repository repository); } diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactoryImpl.java b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactoryImpl.java index 5af0957a..a5992487 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactoryImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactoryImpl.java @@ -36,7 +36,7 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { */ private static final int MAX_DEPTH = 1024; - // Invocation by the wire tx + // Invocation by the wire tx @Override public ProgramInvoke createProgramInvoke(Transaction tx, Block block, Repository repository) { @@ -45,11 +45,11 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { /*** ADDRESS op ***/ // YP: Get address of currently executing account. - byte[] address = tx.isContractCreation() ? tx.getContractAddress(): tx.getReceiveAddress(); + byte[] address = tx.isContractCreation() ? tx.getContractAddress() : tx.getReceiveAddress(); /*** ORIGIN op ***/ // YP: This is the sender of original transaction; it is never a contract. - byte[] origin = tx.getSender(); + byte[] origin = tx.getSender(); /*** CALLER op ***/ // YP: This is the address of the account that is directly responsible for this execution. @@ -92,20 +92,20 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { if (logger.isInfoEnabled()) { logger.info("Top level call: \n" + - "address={}\n" + - "origin={}\n" + - "caller={}\n" + - "balance={}\n" + - "gasPrice={}\n" + - "gas={}\n" + - "callValue={}\n" + - "data={}\n" + - "lastHash={}\n" + - "coinbase={}\n" + - "timestamp={}\n" + - "blockNumber={}\n" + - "difficulty={}\n" + - "gaslimit={}\n", + "address={}\n" + + "origin={}\n" + + "caller={}\n" + + "balance={}\n" + + "gasPrice={}\n" + + "gas={}\n" + + "callValue={}\n" + + "data={}\n" + + "lastHash={}\n" + + "coinbase={}\n" + + "timestamp={}\n" + + "blockNumber={}\n" + + "difficulty={}\n" + + "gaslimit={}\n", Hex.toHexString(address), Hex.toHexString(origin), @@ -124,9 +124,9 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { } ProgramInvoke programInvoke = - new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, data, - lastHash, coinbase, timestamp, number, difficulty, gaslimit, - repository); + new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, data, + lastHash, coinbase, timestamp, number, difficulty, gaslimit, + repository); return programInvoke; } @@ -136,9 +136,9 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { */ @Override public ProgramInvoke createProgramInvoke(Program program, DataWord toAddress, - DataWord inValue, DataWord inGas, - BigInteger balanceInt, byte[] dataIn, - Repository repository) { + DataWord inValue, DataWord inGas, + BigInteger balanceInt, byte[] dataIn, + Repository repository) { DataWord address = toAddress; DataWord origin = program.getOriginAddress(); @@ -150,18 +150,18 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { DataWord callValue = inValue; byte[] data = dataIn; - DataWord lastHash = program.getPrevHash(); - DataWord coinbase = program.getCoinbase(); + DataWord lastHash = program.getPrevHash(); + DataWord coinbase = program.getCoinbase(); DataWord timestamp = program.getTimestamp(); - DataWord number = program.getNumber(); + DataWord number = program.getNumber(); DataWord difficulty = program.getDifficulty(); DataWord gasLimit = program.getGaslimit(); if (logger.isInfoEnabled()) { logger.info("Internal call: \n" + "address={}\n" + - "origin={}\n" + - "caller={}\n" + + "origin={}\n" + + "caller={}\n" + "balance={}\n" + "gasPrice={}\n" + "gas={}\n" + @@ -180,7 +180,7 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { gasPrice.longValue(), gas.longValue(), callValue.toString(), - data == null ? "": Hex.toHexString(data), + data == null ? "" : Hex.toHexString(data), Hex.toHexString(lastHash.getData()), Hex.toHexString(coinbase.getLast20Bytes()), timestamp.longValue(), @@ -194,6 +194,6 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { return new ProgramInvokeImpl(address, origin, caller, balance, gasPrice, gas, callValue, data, lastHash, coinbase, timestamp, number, difficulty, gasLimit, - repository, program.invokeData.getCallDeep()+1); + repository, program.invokeData.getCallDeep() + 1); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeImpl.java b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeImpl.java index 162d928e..8200e745 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeImpl.java @@ -8,19 +8,24 @@ import java.util.Map; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 03/06/2014 15:00 */ public class ProgramInvokeImpl implements ProgramInvoke { - /*** TRANSACTION env ***/ + /** + * TRANSACTION env ** + */ private DataWord address; - private DataWord origin, caller, + private DataWord origin, caller, balance, gas, gasPrice, callValue; byte[] msgData; - /*** BLOCK env ***/ + /** + * BLOCK env ** + */ private DataWord prevHash, coinbase, timestamp, number, difficulty, gaslimit; @@ -31,18 +36,19 @@ public class ProgramInvokeImpl implements ProgramInvoke { private boolean byTestingSuite = false; private int callDeep = 0; - public ProgramInvokeImpl(DataWord address, DataWord origin, DataWord caller, DataWord balance, - DataWord gasPrice, DataWord gas, DataWord callValue, byte[] msgData, - DataWord lastHash, DataWord coinbase, DataWord timestamp, DataWord number, DataWord difficulty, + public ProgramInvokeImpl(DataWord address, DataWord origin, DataWord caller, DataWord balance, + DataWord gasPrice, DataWord gas, DataWord callValue, byte[] msgData, + DataWord lastHash, DataWord coinbase, DataWord timestamp, DataWord number, DataWord + difficulty, DataWord gaslimit, Repository repository, int callDeep) { // Transaction env - this.address = address; - this.origin = origin; - this.caller = caller; - this.balance = balance; - this.gasPrice = gasPrice; - this.gas = gas; + this.address = address; + this.origin = origin; + this.caller = caller; + this.balance = balance; + this.gasPrice = gasPrice; + this.gas = gas; this.callValue = callValue; this.msgData = msgData; @@ -52,7 +58,7 @@ public class ProgramInvokeImpl implements ProgramInvoke { this.timestamp = timestamp; this.number = number; this.difficulty = difficulty; - this.gaslimit = gaslimit; + this.gaslimit = gaslimit; this.repository = repository; this.byTransaction = false; @@ -77,12 +83,12 @@ public class ProgramInvokeImpl implements ProgramInvoke { Repository repository) { // Transaction env - this.address = new DataWord(address); - this.origin = new DataWord(origin); - this.caller = new DataWord(caller); - this.balance = new DataWord(balance); - this.gasPrice = new DataWord(gasPrice); - this.gas = new DataWord(gas); + this.address = new DataWord(address); + this.origin = new DataWord(origin); + this.caller = new DataWord(caller); + this.balance = new DataWord(balance); + this.gasPrice = new DataWord(gasPrice); + this.gas = new DataWord(gas); this.callValue = new DataWord(callValue); this.msgData = msgData; @@ -92,7 +98,7 @@ public class ProgramInvokeImpl implements ProgramInvoke { this.timestamp = new DataWord(timestamp); this.number = new DataWord(number); this.difficulty = new DataWord(difficulty); - this.gaslimit = new DataWord(gaslimit); + this.gaslimit = new DataWord(gaslimit); this.repository = repository; } @@ -139,6 +145,7 @@ public class ProgramInvokeImpl implements ProgramInvoke { * However msgData here is a byte[] and this can't hold more than 2^32-1 */ private static BigInteger MAX_MSG_DATA = BigInteger.valueOf(Integer.MAX_VALUE); + /* CALLDATALOAD op */ public DataWord getDataValue(DataWord indexData) { @@ -175,7 +182,7 @@ public class ProgramInvokeImpl implements ProgramInvoke { if (msgData == null) return data; if (offset > msgData.length) return data; - if (offset + length > msgData.length) length = msgData.length - offset ; + if (offset + length > msgData.length) length = msgData.length - offset; System.arraycopy(msgData, offset, data, 0, length); @@ -184,10 +191,10 @@ public class ProgramInvokeImpl implements ProgramInvoke { @Override - public int countNonZeroData(){ + public int countNonZeroData() { int counter = 0; - for (int i = 0; i < msgData.length; ++i){ + for (int i = 0; i < msgData.length; ++i) { if (msgData[i] != 0) ++counter; } @@ -225,7 +232,9 @@ public class ProgramInvokeImpl implements ProgramInvoke { } /* Storage */ - public Map getStorage() { return storage; } + public Map getStorage() { + return storage; + } public Repository getRepository() { return repository; diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeMockImpl.java b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeMockImpl.java index 9a0c73ef..22785eaf 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeMockImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeMockImpl.java @@ -8,6 +8,7 @@ import org.spongycastle.util.encoders.Hex; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 03/06/2014 15:00 */ @@ -35,13 +36,13 @@ public class ProgramInvokeMockImpl implements ProgramInvoke { this.repository.createAccount(contractAddress); this.repository.saveCode(contractAddress, Hex.decode("385E60076000396000605f556014600054601e60" - + "205463abcddcba6040545b51602001600a525451" - + "6040016014525451606001601e52545160800160" - + "28525460a052546016604860003960166000f260" - + "00603f556103e75660005460005360200235")); + + "205463abcddcba6040545b51602001600a525451" + + "6040016014525451606001601e52545160800160" + + "28525460a052546016604860003960166000f260" + + "00603f556103e75660005460005360200235")); } - public ProgramInvokeMockImpl(boolean defaults){ + public ProgramInvokeMockImpl(boolean defaults) { } @@ -88,7 +89,7 @@ public class ProgramInvokeMockImpl implements ProgramInvoke { return new DataWord(gasLimit); } - public void setGas(long gasLimit){ + public void setGas(long gasLimit) { this.gasLimit = gasLimit; } @@ -112,7 +113,7 @@ public class ProgramInvokeMockImpl implements ProgramInvoke { if (msgData == null) return new DataWord(data); if (index > msgData.length) return new DataWord(data); - if (index + 32 > msgData.length) size = msgData.length - index ; + if (index + 32 > msgData.length) size = msgData.length - index; System.arraycopy(msgData, index, data, 0, size); @@ -137,7 +138,7 @@ public class ProgramInvokeMockImpl implements ProgramInvoke { if (msgData == null) return data; if (offset > msgData.length) return data; - if (offset + length > msgData.length) length = msgData.length - offset ; + if (offset + length > msgData.length) length = msgData.length - offset; System.arraycopy(msgData, offset, data, 0, length); @@ -151,10 +152,10 @@ public class ProgramInvokeMockImpl implements ProgramInvoke { } @Override - public int countNonZeroData(){ + public int countNonZeroData() { int counter = 0; - for (int i = 0; i < msgData.length; ++i){ + for (int i = 0; i < msgData.length; ++i) { if (msgData[i] != 0) ++counter; } diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramResult.java b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramResult.java index 84d86c08..f6aab2ca 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramResult.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramResult.java @@ -8,13 +8,14 @@ import java.util.List; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 07/06/2014 17:45 */ public class ProgramResult { private long gasUsed = 0; - private ByteBuffer hReturn = null; + private ByteBuffer hReturn = null; private RuntimeException exception; private List deleteAccounts; private List logInfoList; @@ -22,16 +23,17 @@ public class ProgramResult { private Repository repository = null; - /* - * for testing runs , - * call/create is not executed - * but dummy recorded - */ + /* + * for testing runs , + * call/create is not executed + * but dummy recorded + */ private List callCreateList; public void spendGas(long gas) { gasUsed += gas; } + public void refundGas(long gas) { gasUsed -= gas; } @@ -71,12 +73,12 @@ public class ProgramResult { deleteAccounts.add(address); } - public void addLogInfo(LogInfo logInfo){ + public void addLogInfo(LogInfo logInfo) { if (this.logInfoList == null) logInfoList = new ArrayList<>(); this.logInfoList.add(logInfo); } - public void addLogInfos(List logInfos){ + public void addLogInfos(List logInfos) { if (logInfos == null) return; if (this.logInfoList == null) logInfoList = new ArrayList<>(); this.logInfoList.addAll(logInfos); @@ -111,7 +113,7 @@ public class ProgramResult { futureRefund += gasValue; } - public long getFutureRefund(){ + public long getFutureRefund() { return futureRefund; } } diff --git a/ethereumj-core/src/main/java/org/ethereum/vm/VM.java b/ethereumj-core/src/main/java/org/ethereum/vm/VM.java index 43bf590c..451f7adf 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/VM.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/VM.java @@ -58,6 +58,7 @@ import static org.ethereum.vm.OpCode.PUSH1; * the spawning execution environment) and which will deal with it separately. * * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 01/06/2014 10:44 */ @@ -88,7 +89,7 @@ public class VM { long oldMemSize = program.getMemSize(); BigInteger newMemSize = BigInteger.ZERO; - long copySize = 0; + long copySize = 0; Stack stack = program.getStack(); String hint = ""; @@ -99,20 +100,21 @@ public class VM { // Calculate fees and spend gas switch (op) { - case STOP: case SUICIDE: + case STOP: + case SUICIDE: // The ops that don't charge by step gasCost = GasCost.STOP; break; case SSTORE: - DataWord newValue = stack.get(stack.size()-2); - DataWord oldValue = program.storageLoad(stack.peek()); + DataWord newValue = stack.get(stack.size() - 2); + DataWord oldValue = program.storageLoad(stack.peek()); if (oldValue == null && !newValue.isZero()) gasCost = GasCost.SSTORE; else if (oldValue != null && newValue.isZero()) { // todo: GASREFUND counter policy // refund step cost policy. - program.futureRefundGas( GasCost.REFUND_SSTORE ); + program.futureRefundGas(GasCost.REFUND_SSTORE); gasCost = 0; } else gasCost = GasCost.RESET_SSTORE; @@ -135,31 +137,32 @@ public class VM { newMemSize = memNeeded(stack.peek(), new DataWord(32)); break; case RETURN: - newMemSize = memNeeded(stack.peek(), stack.get(stack.size()-2)); + newMemSize = memNeeded(stack.peek(), stack.get(stack.size() - 2)); break; case SHA3: gasCost = GasCost.SHA3; - newMemSize = memNeeded(stack.peek(), stack.get(stack.size()-2)); - DataWord size = stack.get(stack.size()-2); + newMemSize = memNeeded(stack.peek(), stack.get(stack.size() - 2)); + DataWord size = stack.get(stack.size() - 2); long chunkUsed = (size.longValue() + 31) / 32; gasCost += chunkUsed * GasCost.SHA3_WORD; break; case CALLDATACOPY: - copySize = stack.get(stack.size()-3).longValue(); - newMemSize = memNeeded(stack.peek(), stack.get(stack.size()-3)); + copySize = stack.get(stack.size() - 3).longValue(); + newMemSize = memNeeded(stack.peek(), stack.get(stack.size() - 3)); break; case CODECOPY: - copySize = stack.get(stack.size()-3).longValue(); - newMemSize = memNeeded(stack.peek(), stack.get(stack.size()-3)); + copySize = stack.get(stack.size() - 3).longValue(); + newMemSize = memNeeded(stack.peek(), stack.get(stack.size() - 3)); break; case EXTCODECOPY: - copySize = stack.get(stack.size()-4).longValue(); - newMemSize = memNeeded(stack.get(stack.size()-2), stack.get(stack.size()-4)); + copySize = stack.get(stack.size() - 4).longValue(); + newMemSize = memNeeded(stack.get(stack.size() - 2), stack.get(stack.size() - 4)); break; - case CALL: case CALLCODE: + case CALL: + case CALLCODE: gasCost = GasCost.CALL; - DataWord callGasWord = stack.get(stack.size()-1); - if(callGasWord.compareTo(program.getGas()) == 1) { + DataWord callGasWord = stack.get(stack.size() - 1); + if (callGasWord.compareTo(program.getGas()) == 1) { throw program.new OutOfGasException(); } callGas = callGasWord.longValue(); @@ -169,28 +172,32 @@ public class VM { break; case CREATE: gasCost = GasCost.CREATE; - newMemSize = memNeeded(stack.get(stack.size()-2), stack.get(stack.size()-3)); + newMemSize = memNeeded(stack.get(stack.size() - 2), stack.get(stack.size() - 3)); break; - case LOG0: case LOG1: case LOG2: case LOG3: case LOG4: + case LOG0: + case LOG1: + case LOG2: + case LOG3: + case LOG4: int nTopics = op.val() - OpCode.LOG0.val(); - newMemSize = memNeeded(stack.peek(), stack.get(stack.size()-2)); + newMemSize = memNeeded(stack.peek(), stack.get(stack.size() - 2)); BigInteger dataSize = stack.get(stack.size() - 2).value(); BigInteger dataCost = dataSize.multiply(BigInteger.valueOf(GasCost.LOG_DATA_GAS)); - if (program.getGas().value().compareTo(dataCost) < 0){ + if (program.getGas().value().compareTo(dataCost) < 0) { throw program.new OutOfGasException(); } gasCost = GasCost.LOG_GAS + - GasCost.LOG_TOPIC_GAS * nTopics + - GasCost.LOG_DATA_GAS * stack.get(stack.size()-2).longValue(); + GasCost.LOG_TOPIC_GAS * nTopics + + GasCost.LOG_DATA_GAS * stack.get(stack.size() - 2).longValue(); break; case EXP: - DataWord exp = stack.get(stack.size()-2); + DataWord exp = stack.get(stack.size() - 2); int bytesOccupied = exp.bytesOccupied(); - gasCost = GasCost.EXP_GAS + GasCost.EXP_BYTE_GAS * bytesOccupied; + gasCost = GasCost.EXP_GAS + GasCost.EXP_BYTE_GAS * bytesOccupied; break; default: break; @@ -198,7 +205,7 @@ public class VM { program.spendGas(gasCost, op.name()); // Avoid overflows - if(newMemSize.compareTo(MAX_GAS) == 1) + if (newMemSize.compareTo(MAX_GAS) == 1) throw program.new OutOfGasException(); // memory gas calc @@ -210,26 +217,27 @@ public class VM { gasCost += memGas; } - if (copySize > 0){ + if (copySize > 0) { long copyGas = GasCost.COPY_GAS * (copySize + 31) / 32; gasCost += copyGas; program.spendGas(copyGas, op.name() + " (copy usage)"); } // Log debugging line for VM - if(program.getNumber().intValue() == CONFIG.dumpBlock()) - this.dumpLine(op, gasBefore, gasCost+callGas, memWords, program); + if (program.getNumber().intValue() == CONFIG.dumpBlock()) + this.dumpLine(op, gasBefore, gasCost + callGas, memWords, program); // Execute operation switch (op) { /** * Stop and Arithmetic Operations */ - case STOP:{ + case STOP: { program.setHReturn(ByteBuffer.allocate(0)); program.stop(); - } break; - case ADD:{ + } + break; + case ADD: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -240,8 +248,9 @@ public class VM { program.stackPush(word1); program.step(); - } break; - case MUL:{ + } + break; + case MUL: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -251,8 +260,9 @@ public class VM { word1.mul(word2); program.stackPush(word1); program.step(); - } break; - case SUB:{ + } + break; + case SUB: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -262,8 +272,9 @@ public class VM { word1.sub(word2); program.stackPush(word1); program.step(); - } break; - case DIV:{ + } + break; + case DIV: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -273,8 +284,9 @@ public class VM { word1.div(word2); program.stackPush(word1); program.step(); - } break; - case SDIV:{ + } + break; + case SDIV: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -284,8 +296,9 @@ public class VM { word1.sDiv(word2); program.stackPush(word1); program.step(); - } break; - case MOD:{ + } + break; + case MOD: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -295,8 +308,9 @@ public class VM { word1.mod(word2); program.stackPush(word1); program.step(); - } break; - case SMOD:{ + } + break; + case SMOD: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -306,8 +320,9 @@ public class VM { word1.sMod(word2); program.stackPush(word1); program.step(); - } break; - case EXP:{ + } + break; + case EXP: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -317,7 +332,8 @@ public class VM { word1.exp(word2); program.stackPush(word1); program.step(); - } break; + } + break; case SIGNEXTEND: { DataWord word1 = program.stackPop(); BigInteger k = word1.value(); @@ -330,8 +346,9 @@ public class VM { program.stackPush(word2); } program.step(); - } break; - case NOT:{ + } + break; + case NOT: { DataWord word1 = program.stackPop(); word1.bnot(); @@ -340,8 +357,9 @@ public class VM { program.stackPush(word1); program.step(); - } break; - case LT:{ + } + break; + case LT: { // TODO: can be improved by not using BigInteger DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -357,8 +375,9 @@ public class VM { } program.stackPush(word1); program.step(); - } break; - case SLT:{ + } + break; + case SLT: { // TODO: can be improved by not using BigInteger DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -374,8 +393,9 @@ public class VM { } program.stackPush(word1); program.step(); - } break; - case SGT:{ + } + break; + case SGT: { // TODO: can be improved by not using BigInteger DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -391,8 +411,9 @@ public class VM { } program.stackPush(word1); program.step(); - } break; - case GT:{ + } + break; + case GT: { // TODO: can be improved by not using BigInteger DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -408,8 +429,9 @@ public class VM { } program.stackPush(word1); program.step(); - } break; - case EQ:{ + } + break; + case EQ: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -424,7 +446,8 @@ public class VM { } program.stackPush(word1); program.step(); - } break; + } + break; case ISZERO: { DataWord word1 = program.stackPop(); if (word1.isZero()) { @@ -438,12 +461,13 @@ public class VM { program.stackPush(word1); program.step(); - } break; + } + break; /** * Bitwise Logic Operations */ - case AND:{ + case AND: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -453,7 +477,8 @@ public class VM { word1.and(word2); program.stackPush(word1); program.step(); - } break; + } + break; case OR: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -464,7 +489,8 @@ public class VM { word1.or(word2); program.stackPush(word1); program.step(); - } break; + } + break; case XOR: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -475,8 +501,9 @@ public class VM { word1.xor(word2); program.stackPush(word1); program.step(); - } break; - case BYTE:{ + } + break; + case BYTE: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); DataWord result = null; @@ -494,30 +521,33 @@ public class VM { program.stackPush(result); program.step(); - } break; - case ADDMOD:{ + } + break; + case ADDMOD: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); DataWord word3 = program.stackPop(); word1.addmod(word2, word3); program.stackPush(word1); program.step(); - } break; - case MULMOD:{ + } + break; + case MULMOD: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); DataWord word3 = program.stackPop(); word1.mulmod(word2, word3); program.stackPush(word1); program.step(); - } break; + } + break; /** * SHA3 */ - case SHA3:{ - DataWord memOffsetData = program.stackPop(); - DataWord lengthData = program.stackPop(); + case SHA3: { + DataWord memOffsetData = program.stackPop(); + DataWord lengthData = program.stackPop(); ByteBuffer buffer = program.memoryChunk(memOffsetData, lengthData); byte[] encoded = HashUtil.sha3(buffer.array()); @@ -528,12 +558,13 @@ public class VM { program.stackPush(word); program.step(); - } break; + } + break; /** * Environmental Information */ - case ADDRESS:{ + case ADDRESS: { DataWord address = program.getOwnerAddress(); if (logger.isInfoEnabled()) @@ -541,8 +572,9 @@ public class VM { program.stackPush(address); program.step(); - } break; - case BALANCE:{ + } + break; + case BALANCE: { DataWord address = program.stackPop(); DataWord balance = program.getBalance(address); @@ -553,8 +585,9 @@ public class VM { program.stackPush(balance); program.step(); - } break; - case ORIGIN:{ + } + break; + case ORIGIN: { DataWord originAddress = program.getOriginAddress(); if (logger.isInfoEnabled()) @@ -562,8 +595,9 @@ public class VM { program.stackPush(originAddress); program.step(); - } break; - case CALLER:{ + } + break; + case CALLER: { DataWord callerAddress = program.getCallerAddress(); if (logger.isInfoEnabled()) @@ -571,8 +605,9 @@ public class VM { program.stackPush(callerAddress); program.step(); - } break; - case CALLVALUE:{ + } + break; + case CALLVALUE: { DataWord callValue = program.getCallValue(); if (logger.isInfoEnabled()) @@ -580,9 +615,10 @@ public class VM { program.stackPush(callValue); program.step(); - } break; - case CALLDATALOAD:{ - DataWord dataOffs = program.stackPop(); + } + break; + case CALLDATALOAD: { + DataWord dataOffs = program.stackPop(); DataWord value = program.getDataValue(dataOffs); if (logger.isInfoEnabled()) @@ -590,8 +626,9 @@ public class VM { program.stackPush(value); program.step(); - } break; - case CALLDATASIZE:{ + } + break; + case CALLDATASIZE: { DataWord dataSize = program.getDataSize(); if (logger.isInfoEnabled()) @@ -599,11 +636,12 @@ public class VM { program.stackPush(dataSize); program.step(); - } break; - case CALLDATACOPY:{ - DataWord memOffsetData = program.stackPop(); + } + break; + case CALLDATACOPY: { + DataWord memOffsetData = program.stackPop(); DataWord dataOffsetData = program.stackPop(); - DataWord lengthData = program.stackPop(); + DataWord lengthData = program.stackPop(); byte[] msgData = program.getDataCopy(dataOffsetData, lengthData); @@ -612,8 +650,10 @@ public class VM { program.memorySave(memOffsetData.intValue(), msgData); program.step(); - } break; - case CODESIZE: case EXTCODESIZE: { + } + break; + case CODESIZE: + case EXTCODESIZE: { int length; if (op == OpCode.CODESIZE) @@ -629,8 +669,10 @@ public class VM { program.stackPush(codeLength); program.step(); - } break; - case CODECOPY: case EXTCODECOPY: { + } + break; + case CODECOPY: + case EXTCODECOPY: { byte[] fullCode = ByteUtil.EMPTY_BYTE_ARRAY; if (op == OpCode.CODECOPY) @@ -641,14 +683,14 @@ public class VM { fullCode = program.getCodeAt(address); } - int memOffset = program.stackPop().intValue(); + int memOffset = program.stackPop().intValue(); int codeOffset = program.stackPop().intValue(); int lengthData = program.stackPop().intValue(); int sizeToBeCopied = - codeOffset + lengthData > fullCode.length ? - (fullCode.length < codeOffset ? 0 : fullCode.length - codeOffset) - : lengthData; + codeOffset + lengthData > fullCode.length ? + (fullCode.length < codeOffset ? 0 : fullCode.length - codeOffset) + : lengthData; byte[] codeCopy = new byte[lengthData]; @@ -660,8 +702,9 @@ public class VM { program.memorySave(memOffset, codeCopy); program.step(); - } break; - case GASPRICE:{ + } + break; + case GASPRICE: { DataWord gasPrice = program.getGasPrice(); if (logger.isInfoEnabled()) @@ -669,7 +712,8 @@ public class VM { program.stackPush(gasPrice); program.step(); - } break; + } + break; /** * Block Information @@ -682,7 +726,8 @@ public class VM { program.stackPush(prevHash); program.step(); - } break; + } + break; case COINBASE: { DataWord coinbase = program.getCoinbase(); @@ -691,8 +736,9 @@ public class VM { program.stackPush(coinbase); program.step(); - } break; - case TIMESTAMP:{ + } + break; + case TIMESTAMP: { DataWord timestamp = program.getTimestamp(); if (logger.isInfoEnabled()) @@ -700,8 +746,9 @@ public class VM { program.stackPush(timestamp); program.step(); - } break; - case NUMBER:{ + } + break; + case NUMBER: { DataWord number = program.getNumber(); if (logger.isInfoEnabled()) @@ -709,8 +756,9 @@ public class VM { program.stackPush(number); program.step(); - } break; - case DIFFICULTY:{ + } + break; + case DIFFICULTY: { DataWord difficulty = program.getDifficulty(); if (logger.isInfoEnabled()) @@ -718,8 +766,9 @@ public class VM { program.stackPush(difficulty); program.step(); - } break; - case GASLIMIT:{ + } + break; + case GASLIMIT: { DataWord gaslimit = program.getGaslimit(); if (logger.isInfoEnabled()) @@ -727,8 +776,9 @@ public class VM { program.stackPush(gaslimit); program.step(); - } break; - case POP:{ + } + break; + case POP: { program.stackPop(); program.step(); } break; @@ -754,8 +804,13 @@ public class VM { stack.set(stack.size() - n, word_1); program.step(); - } break; - case LOG0: case LOG1: case LOG2: case LOG3: case LOG4:{ + } + break; + case LOG0: + case LOG1: + case LOG2: + case LOG3: + case LOG4: { DataWord address = program.programAddress; @@ -765,7 +820,7 @@ public class VM { int nTopics = op.val() - OpCode.LOG0.val(); List topics = new ArrayList(); - for (int i = 0; i < nTopics; ++i){ + for (int i = 0; i < nTopics; ++i) { DataWord topic = stack.pop(); topics.add(topic); } @@ -780,36 +835,40 @@ public class VM { program.getResult().addLogInfo(logInfo); program.step(); - } break; - case MLOAD:{ - DataWord addr = program.stackPop(); - DataWord data = program.memoryLoad(addr); + } + break; + case MLOAD: { + DataWord addr = program.stackPop(); + DataWord data = program.memoryLoad(addr); if (logger.isInfoEnabled()) hint = "data: " + data; program.stackPush(data); program.step(); - } break; - case MSTORE:{ - DataWord addr = program.stackPop(); - DataWord value = program.stackPop(); + } + break; + case MSTORE: { + DataWord addr = program.stackPop(); + DataWord value = program.stackPop(); if (logger.isInfoEnabled()) hint = "addr: " + addr + " value: " + value; program.memorySave(addr, value); program.step(); - } break; - case MSTORE8:{ - DataWord addr = program.stackPop(); - DataWord value = program.stackPop(); + } + break; + case MSTORE8: { + DataWord addr = program.stackPop(); + DataWord value = program.stackPop(); byte[] byteVal = {value.getData()[31]}; program.memorySave(addr.intValue(), byteVal); program.step(); - } break; - case SLOAD:{ - DataWord key = program.stackPop(); + } + break; + case SLOAD: { + DataWord key = program.stackPop(); DataWord val = program.storageLoad(key); if (logger.isInfoEnabled()) @@ -820,21 +879,24 @@ public class VM { program.stackPush(val); program.step(); - } break; - case SSTORE:{ - DataWord addr = program.stackPop(); - DataWord value = program.stackPop(); + } + break; + case SSTORE: { + DataWord addr = program.stackPop(); + DataWord value = program.stackPop(); if (logger.isInfoEnabled()) hint = "addr: " + addr + " value: " + value; program.storageSave(addr, value); program.step(); - } break; - case JUMP:{ - DataWord pos = program.stackPop(); + } + break; + case JUMP: { + DataWord pos = program.stackPop(); int nextPC = pos.intValue(); // possible overflow - if(program.getPreviouslyExecutedOp() < OpCode.PUSH1.val() || program.getPreviouslyExecutedOp() > OpCode.PUSH32.val()) { + if (program.getPreviouslyExecutedOp() < OpCode.PUSH1.val() || program.getPreviouslyExecutedOp() > + OpCode.PUSH32.val()) { if (nextPC != 0 && program.getOp(nextPC) != OpCode.JUMPDEST.val()) throw program.new BadJumpDestinationException(); } @@ -844,14 +906,16 @@ public class VM { program.setPC(nextPC); - } break; - case JUMPI:{ - DataWord pos = program.stackPop(); - DataWord cond = program.stackPop(); + } + break; + case JUMPI: { + DataWord pos = program.stackPop(); + DataWord cond = program.stackPop(); if (!cond.isZero()) { int nextPC = pos.intValue(); // possible overflow - if(program.getPreviouslyExecutedOp() < OpCode.PUSH1.val() || program.getPreviouslyExecutedOp() > OpCode.PUSH32.val()) { + if (program.getPreviouslyExecutedOp() < OpCode.PUSH1.val() || program.getPreviouslyExecutedOp + () > OpCode.PUSH32.val()) { if (nextPC != 0 && program.getOp(nextPC) != OpCode.JUMPDEST.val()) throw program.new BadJumpDestinationException(); } @@ -867,8 +931,9 @@ public class VM { program.step(); } - } break; - case PC:{ + } + break; + case PC: { int pc = program.getPC(); DataWord pcWord = new DataWord(pc); @@ -877,8 +942,9 @@ public class VM { program.stackPush(pcWord); program.step(); - } break; - case MSIZE:{ + } + break; + case MSIZE: { int memSize = program.getMemSize(); DataWord wordMemSize = new DataWord(memSize); @@ -887,8 +953,9 @@ public class VM { program.stackPush(wordMemSize); program.step(); - } break; - case GAS:{ + } + break; + case GAS: { DataWord gas = program.getGas(); if (logger.isInfoEnabled()) @@ -896,12 +963,41 @@ public class VM { program.stackPush(gas); program.step(); - } break; + } + break; - 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 PUSH17: case PUSH18: case PUSH19: case PUSH20: case PUSH21: case PUSH22: case PUSH23: case PUSH24: - case PUSH25: case PUSH26: case PUSH27: case PUSH28: case PUSH29: case PUSH30: case PUSH31: case PUSH32:{ + 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 PUSH17: + case PUSH18: + case PUSH19: + case PUSH20: + case PUSH21: + case PUSH22: + case PUSH23: + case PUSH24: + case PUSH25: + case PUSH26: + case PUSH27: + case PUSH28: + case PUSH29: + case PUSH30: + case PUSH31: + case PUSH32: { program.step(); int nPush = op.val() - PUSH1.val() + 1; @@ -911,14 +1007,16 @@ public class VM { hint = "" + Hex.toHexString(data); program.stackPush(data); - } break; - case JUMPDEST:{ + } + break; + case JUMPDEST: { program.step(); - } break; - case CREATE:{ - DataWord value = program.stackPop(); - DataWord inOffset = program.stackPop(); - DataWord inSize = program.stackPop(); + } + break; + case CREATE: { + DataWord value = program.stackPop(); + DataWord inOffset = program.stackPop(); + DataWord inSize = program.stackPop(); if (logger.isInfoEnabled()) logger.info(logString, program.getPC(), @@ -929,17 +1027,19 @@ public class VM { program.createContract(value, inOffset, inSize); program.step(); - } break; - case CALL: case CALLCODE: { - DataWord gas = program.stackPop(); - DataWord codeAddress = program.stackPop(); - DataWord value = program.stackPop(); + } + break; + case CALL: + case CALLCODE: { + DataWord gas = program.stackPop(); + DataWord codeAddress = program.stackPop(); + DataWord value = program.stackPop(); - DataWord inDataOffs = program.stackPop(); - DataWord inDataSize = program.stackPop(); + DataWord inDataOffs = program.stackPop(); + DataWord inDataSize = program.stackPop(); - DataWord outDataOffs = program.stackPop(); - DataWord outDataSize = program.stackPop(); + DataWord outDataOffs = program.stackPop(); + DataWord outDataSize = program.stackPop(); if (logger.isInfoEnabled()) { hint = "addr: " + Hex.toHexString(codeAddress.getLast20Bytes()) @@ -959,10 +1059,11 @@ public class VM { program.callToAddress(msg); program.step(); - } break; - case RETURN:{ - DataWord offset = program.stackPop(); - DataWord size = program.stackPop(); + } + break; + case RETURN: { + DataWord offset = program.stackPop(); + DataWord size = program.stackPop(); ByteBuffer hReturn = program.memoryChunk(offset, size); program.setHReturn(hReturn); @@ -974,16 +1075,18 @@ public class VM { program.step(); program.stop(); - } break; - case SUICIDE:{ - DataWord address = program.stackPop(); + } + break; + case SUICIDE: { + DataWord address = program.stackPop(); program.suicide(address); if (logger.isInfoEnabled()) hint = "address: " + Hex.toHexString(program.getOwnerAddress().getLast20Bytes()); program.stop(); - } break; + } + break; default: break; } @@ -993,7 +1096,7 @@ public class VM { if (logger.isInfoEnabled() && !op.equals(CALL) && !op.equals(CREATE)) logger.info(logString, stepBefore, String.format("%-12s", - op.name()), program.getGas().longValue(), + op.name()), program.getGas().longValue(), program.invokeData.getCallDeep(), hint); vmCounter++; @@ -1023,7 +1126,7 @@ public class VM { program.spendGas(GasCost.TX_ZERO_DATA * zeroVals, "DATA"); } - while(!program.isStopped()) + while (!program.isStopped()) this.step(program); } catch (RuntimeException e) { @@ -1054,19 +1157,21 @@ public class VM { gasBefore, gasCost, memWords) */ private void dumpLine(OpCode op, long gasBefore, long gasCost, long memWords, Program program) { - if(CONFIG.dumpStyle().equals("standard+")) { + if (CONFIG.dumpStyle().equals("standard+")) { switch (op) { - case STOP: case RETURN: case SUICIDE: + case STOP: + case RETURN: + case SUICIDE: ContractDetails details = program.getResult().getRepository() - .getContractDetails(program.getOwnerAddress().getLast20Bytes()); + .getContractDetails(program.getOwnerAddress().getLast20Bytes()); List storageKeys = new ArrayList<>(details.getStorage().keySet()); Collections.sort((List) storageKeys); for (DataWord key : storageKeys) { dumpLogger.trace("{} {}", - Hex.toHexString(key.getNoLeadZeroesData()), - Hex.toHexString(details.getStorage().get(key).getNoLeadZeroesData())); + Hex.toHexString(key.getNoLeadZeroesData()), + Hex.toHexString(details.getStorage().get(key).getNoLeadZeroesData())); } default: break; @@ -1077,14 +1182,14 @@ public class VM { String gasString = Hex.toHexString(program.getGas().getNoLeadZeroesData()); dumpLogger.trace("{} {} {} {}", addressString, pcString, opString, gasString); - } else if(CONFIG.dumpStyle().equals("pretty")) { + } else if (CONFIG.dumpStyle().equals("pretty")) { dumpLogger.trace(" STACK"); for (DataWord item : program.getStack()) { dumpLogger.trace("{}", item); } dumpLogger.trace(" MEMORY"); String memoryString = program.memoryToString(); - if(!"".equals(memoryString)) + if (!"".equals(memoryString)) dumpLogger.trace("{}", memoryString); dumpLogger.trace(" STORAGE"); @@ -1095,8 +1200,8 @@ public class VM { for (DataWord key : storageKeys) { dumpLogger.trace("{}: {}", - key.shortHex(), - details.getStorage().get(key).shortHex()); + key.shortHex(), + details.getStorage().get(key).shortHex()); } int level = program.invokeData.getCallDeep(); diff --git a/ethereumj-core/src/main/java/org/ethereum/vmtrace/Op.java b/ethereumj-core/src/main/java/org/ethereum/vmtrace/Op.java index c271bac3..5d823c7e 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vmtrace/Op.java +++ b/ethereumj-core/src/main/java/org/ethereum/vmtrace/Op.java @@ -10,7 +10,7 @@ import java.nio.ByteBuffer; import java.util.*; /** - * Data to for one program step to save. + * Data to for one program step to save. * * { * 'op': 'CODECOPY' @@ -29,11 +29,11 @@ import java.util.*; public class Op { - byte op; - int pc; + byte op; + int pc; DataWord gas; Map storage; - byte[] memory; + byte[] memory; List stack; public void setOp(byte op) { @@ -60,7 +60,7 @@ public class Op { } } - public void saveMemory(ByteBuffer memory){ + public void saveMemory(ByteBuffer memory) { if (memory != null) this.memory = Arrays.copyOf(memory.array(), memory.array().length); } @@ -69,12 +69,12 @@ public class Op { this.stack = new ArrayList<>(); - for(DataWord element : stack){ + for (DataWord element : stack) { this.stack.add(0, Hex.toHexString(element.getNoLeadZeroesData())); } } - public String toString(){ + public String toString() { Map jsonData = new LinkedHashMap<>(); @@ -83,7 +83,7 @@ public class Op { jsonData.put("gas", gas.value().toString()); jsonData.put("stack", stack); jsonData.put("memory", memory == null ? "" : Hex.toHexString(memory)); - jsonData.put("storage", new JSONObject(storage) ); + jsonData.put("storage", new JSONObject(storage)); return JSONValue.toJSONString(jsonData); } diff --git a/ethereumj-core/src/main/java/org/ethereum/vmtrace/ProgramTrace.java b/ethereumj-core/src/main/java/org/ethereum/vmtrace/ProgramTrace.java index 51707eb7..aa53d1b4 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vmtrace/ProgramTrace.java +++ b/ethereumj-core/src/main/java/org/ethereum/vmtrace/ProgramTrace.java @@ -10,7 +10,6 @@ import java.util.LinkedHashMap; import java.util.List; /** - * * www.etherj.com * * @author: Roman Mandeleil @@ -26,7 +25,7 @@ public class ProgramTrace { this.txHash = txHash; } - public void addOp(Op op){ + public void addOp(Op op) { ops.add(op); } @@ -35,12 +34,12 @@ public class ProgramTrace { * * @param programTrace */ - public void merge(ProgramTrace programTrace){ + public void merge(ProgramTrace programTrace) { - this.ops.addAll( programTrace.ops ); + this.ops.addAll(programTrace.ops); } - public String getJsonString(){ + public String getJsonString() { return JSONArray.toJSONString(ops); } } diff --git a/ethereumj-core/src/main/java/org/ethereum/wallet/EtherSaleWalletDecoder.java b/ethereumj-core/src/main/java/org/ethereum/wallet/EtherSaleWalletDecoder.java index ec1956ee..d319d1e2 100644 --- a/ethereumj-core/src/main/java/org/ethereum/wallet/EtherSaleWalletDecoder.java +++ b/ethereumj-core/src/main/java/org/ethereum/wallet/EtherSaleWalletDecoder.java @@ -51,7 +51,8 @@ public class EtherSaleWalletDecoder { return result; } - protected byte[] decryptSeed(byte[] pbkdf2PasswordHash, byte[] encseedBytesWithIV) throws InvalidCipherTextException { + protected byte[] decryptSeed(byte[] pbkdf2PasswordHash, byte[] encseedBytesWithIV) throws + InvalidCipherTextException { // first 16 bytes are the IV (0-15) byte[] ivBytes = Arrays.copyOf(encseedBytesWithIV, IV_LENGTH); diff --git a/ethereumj-core/src/test/java/test/ethereum/TestContext.java b/ethereumj-core/src/test/java/test/ethereum/TestContext.java index 841d93c3..dffe68fc 100644 --- a/ethereumj-core/src/test/java/test/ethereum/TestContext.java +++ b/ethereumj-core/src/test/java/test/ethereum/TestContext.java @@ -56,7 +56,7 @@ public class TestContext { @Bean - public DataSourceTransactionManager transactionManager(){ + public DataSourceTransactionManager transactionManager() { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(dataSource()); @@ -64,18 +64,18 @@ public class TestContext { } @Bean(name = "dataSource") - public DriverManagerDataSource dataSource(){ + public DriverManagerDataSource dataSource() { logger.info("Connecting to the block store"); System.setProperty("hsqldb.reconfig_logging", "false"); String url = - String.format("jdbc:hsqldb:file:./%s/blockchain/blockchain.db;" + - "create=%s;hsqldb.default_table_type=cached", + String.format("jdbc:hsqldb:file:./%s/blockchain/blockchain.db;" + + "create=%s;hsqldb.default_table_type=cached", - SystemProperties.CONFIG.databaseDir(), - SystemProperties.CONFIG.databaseReset()); + SystemProperties.CONFIG.databaseDir(), + SystemProperties.CONFIG.databaseReset()); DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName("org.hsqldb.jdbcDriver"); diff --git a/ethereumj-core/src/test/java/test/ethereum/core/BlockTest.java b/ethereumj-core/src/test/java/test/ethereum/core/BlockTest.java index 182ee359..09cc74f7 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/BlockTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/BlockTest.java @@ -37,7 +37,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(loader=AnnotationConfigContextLoader.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class) public class BlockTest { private static final Logger logger = LoggerFactory.getLogger("test"); @@ -47,7 +47,7 @@ public class BlockTest { @ComponentScan(basePackages = "org.ethereum") static class ContextConfiguration extends TestContext { static { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ BlockTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + BlockTest.class); } } @@ -60,11 +60,11 @@ public class BlockTest { private String PoC7_GENESIS_HEX_HASH = "779b1b620b03c0fb24963e183d5e88e3dbe4484e3f6e2aa05942e3be7b48e179"; String block_2 = "f8b5f8b1a0cf4b25b08b39350304fe12a16e4216c01a426f8f3dbf0d392b5b45" - + "8ffb6a399da01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a1" - + "42fd40d493479476f5eabe4b342ee56b8ceba6ab2a770c3e2198e7a08a22d58b" - + "a5c65b2bf660a961b075a43f564374d38bfe6cc69823eea574d1d16e80833fe0" - + "04028609184e72a000830f3aab80845387c60380a00000000000000000000000" - + "0000000000000000000000000033172b6669131179c0c0"; + + "8ffb6a399da01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a1" + + "42fd40d493479476f5eabe4b342ee56b8ceba6ab2a770c3e2198e7a08a22d58b" + + "a5c65b2bf660a961b075a43f564374d38bfe6cc69823eea574d1d16e80833fe0" + + "04028609184e72a000830f3aab80845387c60380a00000000000000000000000" + + "0000000000000000000000000033172b6669131179c0c0"; String block_17 = "f9016df8d3a0aa142573b355c6f2e8306471c869b0d12d0638cea3f57d39991a" + "b1b03ffa40daa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40" @@ -89,7 +89,7 @@ public class BlockTest { @After - public void doReset(){ + public void doReset() { worldManager.reset(); } @@ -160,7 +160,7 @@ public class BlockTest { @Test public void testCalcGasLimit() { - BlockchainImpl blockchain = (BlockchainImpl)worldManager.getBlockchain(); + BlockchainImpl blockchain = (BlockchainImpl) worldManager.getBlockchain(); Block genesis = Genesis.getInstance(); long gasLimit = blockchain.calcGasLimit(genesis.getHeader()); logger.info("Genesis gasLimit: [{}] ", gasLimit); @@ -180,7 +180,7 @@ public class BlockTest { @Test public void testScenario1() throws URISyntaxException, IOException { - BlockchainImpl blockchain = (BlockchainImpl)worldManager.getBlockchain(); + BlockchainImpl blockchain = (BlockchainImpl) worldManager.getBlockchain(); URL scenario1 = ClassLoader .getSystemResource("blockload/scenario1.dmp"); @@ -189,15 +189,15 @@ public class BlockTest { List strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); byte[] root = Genesis.getInstance().getStateRoot(); - for(String blockRLP : strData){ + for (String blockRLP : strData) { Block block = new Block( Hex.decode(blockRLP)); - logger.info("sending block.hash: {}", Hex.toHexString( block.getHash() )); + logger.info("sending block.hash: {}", Hex.toHexString(block.getHash())); blockchain.tryToConnect(block); root = block.getStateRoot(); } - logger.info("asserting root state is: {}", Hex.toHexString( root )); + logger.info("asserting root state is: {}", Hex.toHexString(root)); //expected root: fb8be59e6420892916e3967c60adfdf48836af040db0072ca411d7aaf5663804 assertEquals(Hex.toHexString(root), @@ -207,7 +207,7 @@ public class BlockTest { @Test public void testScenario2() throws URISyntaxException, IOException { - BlockchainImpl blockchain = (BlockchainImpl)worldManager.getBlockchain(); + BlockchainImpl blockchain = (BlockchainImpl) worldManager.getBlockchain(); URL scenario1 = ClassLoader .getSystemResource("blockload/scenario2.dmp"); @@ -216,15 +216,15 @@ public class BlockTest { List strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); byte[] root = Genesis.getInstance().getStateRoot(); - for(String blockRLP : strData){ + for (String blockRLP : strData) { Block block = new Block( Hex.decode(blockRLP)); - logger.info("sending block.hash: {}", Hex.toHexString( block.getHash() )); + logger.info("sending block.hash: {}", Hex.toHexString(block.getHash())); blockchain.tryToConnect(block); root = block.getStateRoot(); } - logger.info("asserting root state is: {}", Hex.toHexString( root )); + logger.info("asserting root state is: {}", Hex.toHexString(root)); //expected root: a5e2a18bdbc4ab97775f44852382ff5585b948ccb15b1d69f0abb71e2d8f727d assertEquals(Hex.toHexString(root), @@ -232,8 +232,6 @@ public class BlockTest { } - - @Test @Ignore public void testUncleValidGenerationGap() { diff --git a/ethereumj-core/src/test/java/test/ethereum/core/BloomTest.java b/ethereumj-core/src/test/java/test/ethereum/core/BloomTest.java index 4b87c4b5..80b80b8f 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/BloomTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/BloomTest.java @@ -16,7 +16,7 @@ public class BloomTest { @Test - public void test1(){ + public void test1() { byte[] key = SHA3Helper.sha3(Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826")); @@ -26,7 +26,7 @@ public class BloomTest { } @Test - public void test2(){ + public void test2() { byte[] key = Hex.decode("0954D2BEF0CA79C1A988AE5FF3072C2AEA90F3967A9596065123F2A15AA37EF3"); @@ -35,7 +35,7 @@ public class BloomTest { } @Test - public void test3(){ + public void test3() { byte[] key = SHA3Helper.sha3(Hex.decode("22341AE42D6DD7384BC8584E50419EA3AC75B83F ")); @@ -45,7 +45,7 @@ public class BloomTest { @Test - public void test4(){ + public void test4() { byte[] key = SHA3Helper.sha3(Hex.decode("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6")); diff --git a/ethereumj-core/src/test/java/test/ethereum/core/ForkTest.java b/ethereumj-core/src/test/java/test/ethereum/core/ForkTest.java index 98b28076..c14009f5 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/ForkTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/ForkTest.java @@ -40,7 +40,7 @@ import static junit.framework.TestCase.assertEquals; */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(loader=AnnotationConfigContextLoader.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ForkTest { @@ -50,7 +50,7 @@ public class ForkTest { @ComponentScan(basePackages = "org.ethereum") static class ContextConfiguration extends TestContext { static { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ ForkTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + ForkTest.class); } } @@ -58,7 +58,7 @@ public class ForkTest { WorldManager worldManager; @After - public void doReset(){ + public void doReset() { worldManager.reset(); } @@ -66,7 +66,7 @@ public class ForkTest { @Test public void fork1() throws URISyntaxException, IOException { - BlockchainImpl blockchain = (BlockchainImpl)worldManager.getBlockchain(); + BlockchainImpl blockchain = (BlockchainImpl) worldManager.getBlockchain(); URL scenario1 = ClassLoader .getSystemResource("fork/scenario1.dmp"); @@ -74,20 +74,20 @@ public class ForkTest { File file = new File(scenario1.toURI()); List strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); - for(String blockRLP : strData){ + for (String blockRLP : strData) { Block block = new Block( Hex.decode(blockRLP)); - logger.info("sending block.hash: {}", Hex.toHexString( block.getHash() )); + logger.info("sending block.hash: {}", Hex.toHexString(block.getHash())); blockchain.tryToConnect(block); } List altChains = blockchain.getAltChains(); - List garbage = blockchain.getGarbage(); + List garbage = blockchain.getGarbage(); - assertEquals(1, altChains.size()); + assertEquals(1, altChains.size()); assertEquals(13, altChains.get(0).getSize()); assertEquals(20, blockchain.getSize()); - assertEquals(0, garbage.size()); + assertEquals(0, garbage.size()); } @Test @@ -102,28 +102,27 @@ public class ForkTest { File file = new File(scenario2.toURI()); List strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); - for(String blockRLP : strData){ + for (String blockRLP : strData) { Block block = new Block( Hex.decode(blockRLP)); - logger.info("sending block.hash: {}", Hex.toHexString( block.getHash() )); + logger.info("sending block.hash: {}", Hex.toHexString(block.getHash())); blockchain.tryToConnect(block); } List altChains = blockchain.getAltChains(); - List garbage = blockchain.getGarbage(); + List garbage = blockchain.getGarbage(); - assertEquals(2, altChains.size()); + assertEquals(2, altChains.size()); // assertEquals(13, altChains.get(0).getSize()); assertEquals(new BigInteger("13238272"), altChains.get(0).getTotalDifficulty()); assertEquals(new BigInteger("13369344"), altChains.get(1).getTotalDifficulty()); - assertEquals(new BigInteger("13238272"), blockchain.getTotalDifficulty() ); + assertEquals(new BigInteger("13238272"), blockchain.getTotalDifficulty()); assertEquals(100, blockchain.getSize()); - assertEquals(0, garbage.size()); + assertEquals(0, garbage.size()); System.out.println(); } - } diff --git a/ethereumj-core/src/test/java/test/ethereum/core/LogInfoTest.java b/ethereumj-core/src/test/java/test/ethereum/core/LogInfoTest.java index 87d9f771..6880ae68 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/LogInfoTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/LogInfoTest.java @@ -21,7 +21,7 @@ public class LogInfoTest { private static final Logger logger = LoggerFactory.getLogger("test"); @Test // rlp decode - public void test_1(){ + public void test_1() { // LogInfo{address=d5ccd26ba09ce1d85148b5081fa3ed77949417be, topics=[000000000000000000000000459d3a7595df9eba241365f4676803586d7d199c 436f696e73000000000000000000000000000000000000000000000000000000 ], data=} byte[] rlp = Hex.decode("f85a94d5ccd26ba09ce1d85148b5081fa3ed77949417bef842a0000000000000000000000000459d3a7595df9eba241365f4676803586d7d199ca0436f696e7300000000000000000000000000000000000000000000000000000080"); @@ -40,7 +40,7 @@ public class LogInfoTest { } @Test // rlp decode - public void test_2(){ + public void test_2() { LogInfo log = new LogInfo(Hex.decode("d5ccd26ba09ce1d85148b5081fa3ed77949417be"), null, null); assertEquals("d794d5ccd26ba09ce1d85148b5081fa3ed77949417bec080", Hex.toHexString(log.getEncoded())); @@ -49,5 +49,4 @@ public class LogInfoTest { } - } diff --git a/ethereumj-core/src/test/java/test/ethereum/core/MinerTest.java b/ethereumj-core/src/test/java/test/ethereum/core/MinerTest.java index cb8002fe..4351d5f2 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/MinerTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/MinerTest.java @@ -25,7 +25,7 @@ public class MinerTest { public void testMine() { boolean miningTestEnabled = false; - if(miningTestEnabled) { + if (miningTestEnabled) { Block block = createBlock(null); assertEquals(rlpWithoutNonce, Hex.toHexString(block.getEncodedWithoutNonce())); System.out.println("Searching for nonce of following block: \n" + block.toString()); @@ -54,7 +54,7 @@ public class MinerTest { public void testMine2() { boolean miningTestEnabled = true; - if(miningTestEnabled) { + if (miningTestEnabled) { Block block = createBlock(null); logger.info("Minning on block: [{}] ", block.getNumber()); @@ -68,7 +68,7 @@ public class MinerTest { assertTrue(valid); logger.info("found nonce: [{}]", Hex.toHexString(block.getNonce())); - while(true){ + while (true) { Block newBlock = createBlock(block); mined = miner.mine(newBlock, newBlock.getDifficulty()); @@ -90,7 +90,7 @@ public class MinerTest { */ private Block createBlock(Block lastBlock) { - if (lastBlock == null){ + if (lastBlock == null) { byte[] parentHash = Hex.decode("0a312c2b0a8f125c60a3976b6e508e740e095eb59943988d9bbfb8aa43922e31"); byte[] unclesHash = Hex.decode("1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"); @@ -106,10 +106,10 @@ public class MinerTest { Block newBlock = new Block(parentHash, unclesHash, coinbase, null, difficulty, number, gasLimit, gasUsed, timestamp, - null, nonce, null, null); + null, nonce, null, null); // Setting stateRoot manually, because don't have state available. return newBlock; - } else{ + } else { Block newBlock = new Block(lastBlock.getHash(), lastBlock.getUnclesHash(), lastBlock.getCoinbase(), null, lastBlock.getDifficulty(), lastBlock.getNumber() + 1, diff --git a/ethereumj-core/src/test/java/test/ethereum/core/StateTest.java b/ethereumj-core/src/test/java/test/ethereum/core/StateTest.java index 495f2251..b4cc03d7 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/StateTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/StateTest.java @@ -71,7 +71,7 @@ public class StateTest { AccountState account_3 = new AccountState(BigInteger.ZERO, new BigInteger("1506260000000000000")); trie.update(minerAddress, account_3.getEncoded()); - assertEquals(expected, Hex.toHexString(trie.getRootHash())); + assertEquals(expected, Hex.toHexString(trie.getRootHash())); /* *** GROSS DATA *** diff --git a/ethereumj-core/src/test/java/test/ethereum/core/TransactionReceiptTest.java b/ethereumj-core/src/test/java/test/ethereum/core/TransactionReceiptTest.java index 5ac7c14a..4d1996f9 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/TransactionReceiptTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/TransactionReceiptTest.java @@ -21,7 +21,7 @@ public class TransactionReceiptTest { @Test // rlp decode - public void test_1(){ + public void test_1() { byte[] rlp = Hex.decode("f8c4a0966265cc49fa1f10f0445f035258d116563931022a3570a640af5d73a214a8da822b6fb84000000010000000010000000000008000000000000000000000000000000000000000000000000000000000020000000000000014000000000400000000000440f85cf85a94d5ccd26ba09ce1d85148b5081fa3ed77949417bef842a0000000000000000000000000459d3a7595df9eba241365f4676803586d7d199ca0436f696e7300000000000000000000000000000000000000000000000000000080"); TransactionReceipt txReceipt = new TransactionReceipt(rlp); diff --git a/ethereumj-core/src/test/java/test/ethereum/core/TransactionTest.java b/ethereumj-core/src/test/java/test/ethereum/core/TransactionTest.java index f20301f3..913bcff6 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/TransactionTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/TransactionTest.java @@ -46,7 +46,7 @@ public class TransactionTest { byte[] cowPrivKey = Hex.decode("c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4"); ECKey key = ECKey.fromPrivate(cowPrivKey); - byte[] data = Hex.decode(txRLPRawData); + byte[] data = Hex.decode(txRLPRawData); // step 1: serialize + RLP encode // step 2: hash = sha3(step1) @@ -69,17 +69,17 @@ public class TransactionTest { byte[] senderPrivKey = HashUtil.sha3("cow".getBytes()); - byte[] gasPrice= Hex.decode("09184e72a000"); - byte[] gas = Hex.decode("4255"); + byte[] gasPrice = Hex.decode("09184e72a000"); + byte[] gas = Hex.decode("4255"); // Tn (nonce); Tp(pgas); Tg(gaslimi); Tt(value); Tv(value); Ti(sender); Tw; Tr; Ts Transaction tx = new Transaction(null, gasPrice, gas, ecKey.getAddress(), value.toByteArray(), - null); + null); tx.sign(senderPrivKey); - System.out.println("v\t\t\t: " + Hex.toHexString(new byte[] { tx.getSignature().v })); + System.out.println("v\t\t\t: " + Hex.toHexString(new byte[]{tx.getSignature().v})); System.out.println("r\t\t\t: " + Hex.toHexString(BigIntegers.asUnsignedByteArray(tx.getSignature().r))); System.out.println("s\t\t\t: " + Hex.toHexString(BigIntegers.asUnsignedByteArray(tx.getSignature().s))); @@ -110,7 +110,7 @@ public class TransactionTest { ECKey ecKey = ECKey.fromPrivate(HashUtil.sha3("cat".getBytes())); byte[] senderPrivKey = HashUtil.sha3("cow".getBytes()); - byte[] nonce = { 0x01 }; + byte[] nonce = {0x01}; byte[] gasPrice = Hex.decode("09184e72a000"); byte[] gasLimit = Hex.decode("4255"); BigInteger value = new BigInteger("1000000000000000000000000"); @@ -120,7 +120,7 @@ public class TransactionTest { tx.sign(senderPrivKey); - System.out.println("v\t\t\t: " + Hex.toHexString(new byte[] { tx.getSignature().v })); + System.out.println("v\t\t\t: " + Hex.toHexString(new byte[]{tx.getSignature().v})); System.out.println("r\t\t\t: " + Hex.toHexString(BigIntegers.asUnsignedByteArray(tx.getSignature().r))); System.out.println("s\t\t\t: " + Hex.toHexString(BigIntegers.asUnsignedByteArray(tx.getSignature().s))); @@ -222,12 +222,12 @@ public class TransactionTest { String RLP_TX_SIGNED = "f86b8085e8d4a510008227109413978aee95f38490e9769c39b2773ed763d9cd5f872386f26fc10000801ba0eab47c1a49bf2fe5d40e01d313900e19ca485867d462fe06e139e3a536c6d4f4a014a569d327dcda4b29f74f93c0e9729d2f49ad726e703f9cd90dbb0fbf6649f1"; String HASH_TX_UNSIGNED = "328ea6d24659dec48adea1aced9a136e5ebdf40258db30d1b1d97ed2b74be34e"; - byte[] nonce = BigIntegers.asUnsignedByteArray(BigInteger.ZERO); - byte[] gasPrice = Hex.decode("e8d4a51000"); // 1000000000000 - byte[] gas = Hex.decode("2710"); // 10000 - byte[] recieveAddress = Hex.decode("13978aee95f38490e9769c39b2773ed763d9cd5f"); - byte[] value = Hex.decode("2386f26fc10000"); //10000000000000000" - byte[] data = new byte[0]; + byte[] nonce = BigIntegers.asUnsignedByteArray(BigInteger.ZERO); + byte[] gasPrice = Hex.decode("e8d4a51000"); // 1000000000000 + byte[] gas = Hex.decode("2710"); // 10000 + byte[] recieveAddress = Hex.decode("13978aee95f38490e9769c39b2773ed763d9cd5f"); + byte[] value = Hex.decode("2386f26fc10000"); //10000000000000000" + byte[] data = new byte[0]; Transaction tx = new Transaction(nonce, gasPrice, gas, recieveAddress, value, data); @@ -246,16 +246,18 @@ public class TransactionTest { @Test public void testTransactionCreateContract() { -// String rlp = "f89f808609184e72a0008203e8808203e8b84b4560005444602054600f60056002600a02010b0d630000001d596002602054630000003b5860066000530860056006600202010a0d6300000036596004604054630000003b5860056060541ca0ddc901d83110ea50bc40803f42083afea1bbd420548f6392a679af8e24b21345a06620b3b512bea5f0a272703e8d6933177c23afc79516fd0ca4a204aa6e34c7e9"; +// String rlp = +// "f89f808609184e72a0008203e8808203e8b84b4560005444602054600f60056002600a02010b0d630000001d596002602054630000003b5860066000530860056006600202010a0d6300000036596004604054630000003b5860056060541ca0ddc901d83110ea50bc40803f42083afea1bbd420548f6392a679af8e24b21345a06620b3b512bea5f0a272703e8d6933177c23afc79516fd0ca4a204aa6e34c7e9"; byte[] senderPrivKey = HashUtil.sha3("cow".getBytes()); - byte[] nonce = BigIntegers.asUnsignedByteArray(BigInteger.ZERO); - byte[] gasPrice = Hex.decode("09184e72a000"); // 10000000000000 - byte[] gas = Hex.decode("03e8"); // 1000 - byte[] recieveAddress = null; - byte[] endowment = Hex.decode("03e8"); //10000000000000000" - byte[] init = Hex.decode("4560005444602054600f60056002600a02010b0d630000001d596002602054630000003b5860066000530860056006600202010a0d6300000036596004604054630000003b586005606054"); + byte[] nonce = BigIntegers.asUnsignedByteArray(BigInteger.ZERO); + byte[] gasPrice = Hex.decode("09184e72a000"); // 10000000000000 + byte[] gas = Hex.decode("03e8"); // 1000 + byte[] recieveAddress = null; + byte[] endowment = Hex.decode("03e8"); //10000000000000000" + byte[] init = Hex.decode + ("4560005444602054600f60056002600a02010b0d630000001d596002602054630000003b5860066000530860056006600202010a0d6300000036596004604054630000003b586005606054"); Transaction tx1 = new Transaction(nonce, gasPrice, gas, diff --git a/ethereumj-core/src/test/java/test/ethereum/core/WalletTest.java b/ethereumj-core/src/test/java/test/ethereum/core/WalletTest.java index 8815380d..add158a0 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/WalletTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/WalletTest.java @@ -30,12 +30,13 @@ import java.math.BigInteger; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 17/05/14 17:06 */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(loader=AnnotationConfigContextLoader.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class) public class WalletTest { private static final Logger logger = LoggerFactory.getLogger("test"); @@ -44,7 +45,7 @@ public class WalletTest { @ComponentScan(basePackages = "org.ethereum") static class ContextConfiguration extends TestContext { static { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ WalletTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + WalletTest.class); } } @@ -52,13 +53,13 @@ public class WalletTest { WorldManager worldManager; @After - public void doReset(){ + public void doReset() { worldManager.reset(); } @Test // Testing account for simple balance set - public void accountTest_1(){ + public void accountTest_1() { Repository repository = worldManager.getRepository(); @@ -78,7 +79,7 @@ public class WalletTest { @Test // test account balance with pending "unblocked" transaction - public void accountTest_2(){ + public void accountTest_2() { Repository repository = worldManager.getRepository(); diff --git a/ethereumj-core/src/test/java/test/ethereum/crypto/ECKeyTest.java b/ethereumj-core/src/test/java/test/ethereum/crypto/ECKeyTest.java index c010b176..4a7076bc 100644 --- a/ethereumj-core/src/test/java/test/ethereum/crypto/ECKeyTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/crypto/ECKeyTest.java @@ -64,7 +64,7 @@ public class ECKeyTest { assertArrayEquals(pubKey, key.getPubKey()); } - @Test(expected=IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) public void testPrivatePublicKeyBytesNoArg() { new ECKey(null, null); fail("Expecting an IllegalArgumentException for using only null-parameters"); @@ -196,26 +196,32 @@ public class ECKeyTest { @Test public void testIsPubKeyCanonicalCorect() { // Test correct prefix 4, right length 65 - byte[] canonicalPubkey1 = new byte[65]; canonicalPubkey1[0] = 0x04; + byte[] canonicalPubkey1 = new byte[65]; + canonicalPubkey1[0] = 0x04; assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey1)); // Test correct prefix 2, right length 33 - byte[] canonicalPubkey2 = new byte[33]; canonicalPubkey2[0] = 0x02; + byte[] canonicalPubkey2 = new byte[33]; + canonicalPubkey2[0] = 0x02; assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey2)); // Test correct prefix 3, right length 33 - byte[] canonicalPubkey3 = new byte[33]; canonicalPubkey3[0] = 0x03; + byte[] canonicalPubkey3 = new byte[33]; + canonicalPubkey3[0] = 0x03; assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey3)); } @Test public void testIsPubKeyCanonicalWrongLength() { // Test correct prefix 4, but wrong length !65 - byte[] nonCanonicalPubkey1 = new byte[64]; nonCanonicalPubkey1[0] = 0x04; + byte[] nonCanonicalPubkey1 = new byte[64]; + nonCanonicalPubkey1[0] = 0x04; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey1)); // Test correct prefix 2, but wrong length !33 - byte[] nonCanonicalPubkey2 = new byte[32]; nonCanonicalPubkey2[0] = 0x02; + byte[] nonCanonicalPubkey2 = new byte[32]; + nonCanonicalPubkey2[0] = 0x02; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey2)); // Test correct prefix 3, but wrong length !33 - byte[] nonCanonicalPubkey3 = new byte[32]; nonCanonicalPubkey3[0] = 0x03; + byte[] nonCanonicalPubkey3 = new byte[32]; + nonCanonicalPubkey3[0] = 0x03; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey3)); } diff --git a/ethereumj-core/src/test/java/test/ethereum/db/ByteArrayWrapperTest.java b/ethereumj-core/src/test/java/test/ethereum/db/ByteArrayWrapperTest.java index 57482782..964c75e8 100644 --- a/ethereumj-core/src/test/java/test/ethereum/db/ByteArrayWrapperTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/db/ByteArrayWrapperTest.java @@ -114,7 +114,7 @@ public class ByteArrayWrapperTest { public void testEqualsPerformance() { boolean testEnabled = false; - if(testEnabled) { + if (testEnabled) { final int ITERATIONS = 10000000; long start1 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { diff --git a/ethereumj-core/src/test/java/test/ethereum/db/RepositoryTest.java b/ethereumj-core/src/test/java/test/ethereum/db/RepositoryTest.java index a744e7fa..cbbbed44 100644 --- a/ethereumj-core/src/test/java/test/ethereum/db/RepositoryTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/db/RepositoryTest.java @@ -30,12 +30,12 @@ public class RepositoryTest { @Test - public void test1(){ + public void test1() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); repository.increaseNonce(cow); @@ -49,12 +49,12 @@ public class RepositoryTest { @Test - public void test2(){ + public void test2() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); repository.addBalance(cow, BigInteger.TEN); @@ -68,12 +68,12 @@ public class RepositoryTest { @Test - public void test3(){ + public void test3() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); byte[] cowCode = Hex.decode("A1A2A3"); @@ -89,21 +89,21 @@ public class RepositoryTest { } @Test - public void test4(){ + public void test4() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); - byte[] cowKey = Hex.decode("A1A2A3"); + byte[] cowKey = Hex.decode("A1A2A3"); byte[] cowValue = Hex.decode("A4A5A6"); byte[] horseKey = Hex.decode("B1B2B3"); byte[] horseValue = Hex.decode("B4B5B6"); - repository.addStorageRow(cow, new DataWord(cowKey), new DataWord(cowValue)); + repository.addStorageRow(cow, new DataWord(cowKey), new DataWord(cowValue)); repository.addStorageRow(horse, new DataWord(horseKey), new DataWord(horseValue)); assertEquals(new DataWord(cowValue), repository.getStorageValue(cow, new DataWord(cowKey))); @@ -114,18 +114,24 @@ public class RepositoryTest { @Test - public void test5(){ + public void test5() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); Repository track = repository.startTracking(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); - track.increaseNonce(cow); track.increaseNonce(cow); track.increaseNonce(cow); - track.increaseNonce(cow); track.increaseNonce(cow); track.increaseNonce(cow); - track.increaseNonce(cow); track.increaseNonce(cow); track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); track.increaseNonce(cow); track.increaseNonce(horse); @@ -139,18 +145,24 @@ public class RepositoryTest { } @Test - public void test6(){ + public void test6() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); Repository track = repository.startTracking(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); - track.increaseNonce(cow); track.increaseNonce(cow); track.increaseNonce(cow); - track.increaseNonce(cow); track.increaseNonce(cow); track.increaseNonce(cow); - track.increaseNonce(cow); track.increaseNonce(cow); track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); + track.increaseNonce(cow); track.increaseNonce(cow); track.increaseNonce(horse); @@ -167,16 +179,16 @@ public class RepositoryTest { } @Test - public void test7(){ + public void test7() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); Repository track = repository.startTracking(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); - track.addBalance(cow, BigInteger.TEN); + track.addBalance(cow, BigInteger.TEN); track.addBalance(horse, BigInteger.ONE); assertEquals(BigInteger.TEN, track.getBalance(cow)); @@ -192,16 +204,16 @@ public class RepositoryTest { @Test - public void test8(){ + public void test8() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); Repository track = repository.startTracking(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); - track.addBalance(cow, BigInteger.TEN); + track.addBalance(cow, BigInteger.TEN); track.addBalance(horse, BigInteger.ONE); assertEquals(BigInteger.TEN, track.getBalance(cow)); @@ -216,55 +228,55 @@ public class RepositoryTest { } @Test - public void test9(){ + public void test9() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); Repository track = repository.startTracking(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); - DataWord cowKey = new DataWord(Hex.decode("A1A2A3")); - DataWord cowValue = new DataWord(Hex.decode("A4A5A6")); + DataWord cowKey = new DataWord(Hex.decode("A1A2A3")); + DataWord cowValue = new DataWord(Hex.decode("A4A5A6")); - DataWord horseKey = new DataWord(Hex.decode("B1B2B3")); + DataWord horseKey = new DataWord(Hex.decode("B1B2B3")); DataWord horseValue = new DataWord(Hex.decode("B4B5B6")); - track.addStorageRow(cow, cowKey, cowValue); + track.addStorageRow(cow, cowKey, cowValue); track.addStorageRow(horse, horseKey, horseValue); - assertEquals(cowValue, track.getStorageValue(cow, cowKey)); + assertEquals(cowValue, track.getStorageValue(cow, cowKey)); assertEquals(horseValue, track.getStorageValue(horse, horseKey)); track.commit(); - assertEquals(cowValue, repository.getStorageValue(cow, cowKey)); + assertEquals(cowValue, repository.getStorageValue(cow, cowKey)); assertEquals(horseValue, repository.getStorageValue(horse, horseKey)); repository.close(); } @Test - public void test10(){ + public void test10() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); Repository track = repository.startTracking(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); - DataWord cowKey = new DataWord(Hex.decode("A1A2A3")); - DataWord cowValue = new DataWord(Hex.decode("A4A5A6")); + DataWord cowKey = new DataWord(Hex.decode("A1A2A3")); + DataWord cowValue = new DataWord(Hex.decode("A4A5A6")); - DataWord horseKey = new DataWord(Hex.decode("B1B2B3")); + DataWord horseKey = new DataWord(Hex.decode("B1B2B3")); DataWord horseValue = new DataWord(Hex.decode("B4B5B6")); - track.addStorageRow(cow, cowKey, cowValue); + track.addStorageRow(cow, cowKey, cowValue); track.addStorageRow(horse, horseKey, horseValue); - assertEquals(cowValue, track.getStorageValue(cow, cowKey)); + assertEquals(cowValue, track.getStorageValue(cow, cowKey)); assertEquals(horseValue, track.getStorageValue(horse, horseKey)); track.rollback(); @@ -277,27 +289,27 @@ public class RepositoryTest { @Test - public void test11(){ + public void test11() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); Repository track = repository.startTracking(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); - byte[] cowCode = Hex.decode("A1A2A3"); + byte[] cowCode = Hex.decode("A1A2A3"); byte[] horseCode = Hex.decode("B1B2B3"); - track.saveCode(cow, cowCode); + track.saveCode(cow, cowCode); track.saveCode(horse, horseCode); - assertArrayEquals(cowCode, track.getCode(cow)); + assertArrayEquals(cowCode, track.getCode(cow)); assertArrayEquals(horseCode, track.getCode(horse)); track.commit(); - assertArrayEquals(cowCode, repository.getCode(cow)); + assertArrayEquals(cowCode, repository.getCode(cow)); assertArrayEquals(horseCode, repository.getCode(horse)); repository.close(); @@ -305,36 +317,36 @@ public class RepositoryTest { @Test - public void test12(){ + public void test12() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); Repository track = repository.startTracking(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); - byte[] cowCode = Hex.decode("A1A2A3"); + byte[] cowCode = Hex.decode("A1A2A3"); byte[] horseCode = Hex.decode("B1B2B3"); - track.saveCode(cow, cowCode); + track.saveCode(cow, cowCode); track.saveCode(horse, horseCode); - assertArrayEquals(cowCode, track.getCode(cow)); + assertArrayEquals(cowCode, track.getCode(cow)); assertArrayEquals(horseCode, track.getCode(horse)); track.rollback(); - assertArrayEquals(null, repository.getCode(cow)); - assertArrayEquals(null, repository.getCode(horse)); + assertArrayEquals(null, repository.getCode(cow)); + assertArrayEquals(null, repository.getCode(horse)); repository.close(); } @Test // Let's upload genesis pre-mine just like in the real world - public void test13(){ + public void test13() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); Repository track = repository.startTracking(); @@ -344,26 +356,26 @@ public class RepositoryTest { track.commit(); - assertArrayEquals(Genesis.getInstance().getStateRoot(), repository.getRoot()); + assertArrayEquals(Genesis.getInstance().getStateRoot(), repository.getRoot()); repository.close(); } @Test - public void test14(){ + public void test14() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); final BigInteger ELEVEN = BigInteger.TEN.add(BigInteger.ONE); // changes level_1 Repository track1 = repository.startTracking(); - track1.addBalance(cow, BigInteger.TEN); + track1.addBalance(cow, BigInteger.TEN); track1.addBalance(horse, BigInteger.ONE); assertEquals(BigInteger.TEN, track1.getBalance(cow)); @@ -372,7 +384,7 @@ public class RepositoryTest { // changes level_2 Repository track2 = track1.startTracking(); - track2.addBalance(cow, BigInteger.ONE); + track2.addBalance(cow, BigInteger.ONE); track2.addBalance(horse, BigInteger.TEN); assertEquals(ELEVEN, track2.getBalance(cow)); @@ -389,19 +401,19 @@ public class RepositoryTest { @Test - public void test15(){ + public void test15() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); final BigInteger ELEVEN = BigInteger.TEN.add(BigInteger.ONE); // changes level_1 Repository track1 = repository.startTracking(); - track1.addBalance(cow, BigInteger.TEN); + track1.addBalance(cow, BigInteger.TEN); track1.addBalance(horse, BigInteger.ONE); assertEquals(BigInteger.TEN, track1.getBalance(cow)); @@ -409,7 +421,7 @@ public class RepositoryTest { // changes level_2 Repository track2 = track1.startTracking(); - track2.addBalance(cow, BigInteger.ONE); + track2.addBalance(cow, BigInteger.ONE); track2.addBalance(horse, BigInteger.TEN); assertEquals(ELEVEN, track2.getBalance(cow)); @@ -426,62 +438,62 @@ public class RepositoryTest { @Test - public void test16(){ + public void test16() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); byte[] horse = Hex.decode("13978AEE95F38490E9769C39B2773ED763D9CD5F"); - byte[] cowKey1 = "key-c-1".getBytes(); + byte[] cowKey1 = "key-c-1".getBytes(); byte[] cowValue1 = "val-c-1".getBytes(); - byte[] horseKey1 = "key-h-1".getBytes(); + byte[] horseKey1 = "key-h-1".getBytes(); byte[] horseValue1 = "val-h-1".getBytes(); - byte[] cowKey2 = "key-c-2".getBytes(); + byte[] cowKey2 = "key-c-2".getBytes(); byte[] cowValue2 = "val-c-2".getBytes(); - byte[] horseKey2 = "key-h-2".getBytes(); + byte[] horseKey2 = "key-h-2".getBytes(); byte[] horseValue2 = "val-h-2".getBytes(); // changes level_1 Repository track1 = repository.startTracking(); - track1.addStorageRow(cow, new DataWord(cowKey1), new DataWord(cowValue1)); + track1.addStorageRow(cow, new DataWord(cowKey1), new DataWord(cowValue1)); track1.addStorageRow(horse, new DataWord(horseKey1), new DataWord(horseValue1)); - assertEquals(new DataWord(cowValue1), track1.getStorageValue(cow, new DataWord(cowKey1))); + assertEquals(new DataWord(cowValue1), track1.getStorageValue(cow, new DataWord(cowKey1))); assertEquals(new DataWord(horseValue1), track1.getStorageValue(horse, new DataWord(horseKey1))); // changes level_2 Repository track2 = track1.startTracking(); - track2.addStorageRow(cow, new DataWord(cowKey2), new DataWord(cowValue2)); + track2.addStorageRow(cow, new DataWord(cowKey2), new DataWord(cowValue2)); track2.addStorageRow(horse, new DataWord(horseKey2), new DataWord(horseValue2)); - assertEquals(new DataWord(cowValue1), track2.getStorageValue(cow, new DataWord(cowKey1))); + assertEquals(new DataWord(cowValue1), track2.getStorageValue(cow, new DataWord(cowKey1))); assertEquals(new DataWord(horseValue1), track2.getStorageValue(horse, new DataWord(horseKey1))); - assertEquals(new DataWord(cowValue2), track2.getStorageValue(cow, new DataWord(cowKey2))); + assertEquals(new DataWord(cowValue2), track2.getStorageValue(cow, new DataWord(cowKey2))); assertEquals(new DataWord(horseValue2), track2.getStorageValue(horse, new DataWord(horseKey2))); track2.commit(); // leaving level_2 - assertEquals(new DataWord(cowValue1), track1.getStorageValue(cow, new DataWord(cowKey1))); + assertEquals(new DataWord(cowValue1), track1.getStorageValue(cow, new DataWord(cowKey1))); assertEquals(new DataWord(horseValue1), track1.getStorageValue(horse, new DataWord(horseKey1))); - assertEquals(new DataWord(cowValue2), track1.getStorageValue(cow, new DataWord(cowKey2))); + assertEquals(new DataWord(cowValue2), track1.getStorageValue(cow, new DataWord(cowKey2))); assertEquals(new DataWord(horseValue2), track1.getStorageValue(horse, new DataWord(horseKey2))); track1.commit(); // leaving level_1 - assertEquals(new DataWord(cowValue1), repository.getStorageValue(cow, new DataWord(cowKey1))); + assertEquals(new DataWord(cowValue1), repository.getStorageValue(cow, new DataWord(cowKey1))); assertEquals(new DataWord(horseValue1), repository.getStorageValue(horse, new DataWord(horseKey1))); - assertEquals(new DataWord(cowValue2), repository.getStorageValue(cow, new DataWord(cowKey2))); + assertEquals(new DataWord(cowValue2), repository.getStorageValue(cow, new DataWord(cowKey2))); assertEquals(new DataWord(horseValue2), repository.getStorageValue(horse, new DataWord(horseKey2))); repository.close(); @@ -489,14 +501,14 @@ public class RepositoryTest { @Test - public void test17(){ + public void test17() { - SystemProperties.CONFIG.setDataBaseDir("test_db/"+ RepositoryTest.class); + SystemProperties.CONFIG.setDataBaseDir("test_db/" + RepositoryTest.class); Repository repository = new RepositoryImpl(); - byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); + byte[] cow = Hex.decode("CD2A3D9F938E13CD947EC05ABC7FE734DF8DD826"); - byte[] cowKey1 = "key-c-1".getBytes(); + byte[] cowKey1 = "key-c-1".getBytes(); byte[] cowValue1 = "val-c-1".getBytes(); // changes level_1 @@ -504,15 +516,15 @@ public class RepositoryTest { // changes level_2 Repository track2 = track1.startTracking(); - track2.addStorageRow(cow, new DataWord(cowKey1), new DataWord(cowValue1)); - assertEquals(new DataWord(cowValue1), track2.getStorageValue(cow, new DataWord(cowKey1))); + track2.addStorageRow(cow, new DataWord(cowKey1), new DataWord(cowValue1)); + assertEquals(new DataWord(cowValue1), track2.getStorageValue(cow, new DataWord(cowKey1))); track2.rollback(); // leaving level_2 track1.commit(); // leaving level_1 - Assert.assertEquals( Hex.toHexString(HashUtil.EMPTY_TRIE_HASH), Hex.toHexString(repository.getRoot()) ); + Assert.assertEquals(Hex.toHexString(HashUtil.EMPTY_TRIE_HASH), Hex.toHexString(repository.getRoot())); repository.close(); } diff --git a/ethereumj-core/src/test/java/test/ethereum/db/TrackDatabaseTest.java b/ethereumj-core/src/test/java/test/ethereum/db/TrackDatabaseTest.java index 2f6fad14..e2b45363 100644 --- a/ethereumj-core/src/test/java/test/ethereum/db/TrackDatabaseTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/db/TrackDatabaseTest.java @@ -30,22 +30,22 @@ public class TrackDatabaseTest { TrackDatabase trackDatabase1 = new TrackDatabase(db1); trackDatabase1.put(Hex.decode("abcdef"), Hex.decode("abcdef")); - byte[] value = trackDatabase1.get(Hex.decode("abcdef")); + byte[] value = trackDatabase1.get(Hex.decode("abcdef")); assertEquals("abcdef", Hex.toHexString(value)); trackDatabase1.startTrack(); trackDatabase1.put(Hex.decode("abcdef"), Hex.decode("ffffff")); - value = trackDatabase1.get(Hex.decode("abcdef")); + value = trackDatabase1.get(Hex.decode("abcdef")); assertEquals("ffffff", Hex.toHexString(value)); trackDatabase1.rollbackTrack(); - value = trackDatabase1.get(Hex.decode("abcdef")); + value = trackDatabase1.get(Hex.decode("abcdef")); assertEquals("abcdef", Hex.toHexString(value)); trackDatabase1.startTrack(); trackDatabase1.put(Hex.decode("abcdef"), Hex.decode("ffffff")); trackDatabase1.commitTrack(); - value = trackDatabase1.get(Hex.decode("abcdef")); + value = trackDatabase1.get(Hex.decode("abcdef")); assertEquals("ffffff", Hex.toHexString(value)); db1.close(); diff --git a/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubJSONTestSuite.java b/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubJSONTestSuite.java index 776c514a..de61855b 100644 --- a/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubJSONTestSuite.java +++ b/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubJSONTestSuite.java @@ -25,7 +25,7 @@ import org.slf4j.LoggerFactory; */ @RunWith(Suite.class) @SuiteClasses({ - GitHubVMTest.class, + GitHubVMTest.class, }) public class GitHubJSONTestSuite { @@ -36,12 +36,12 @@ public class GitHubJSONTestSuite { Assume.assumeFalse("Online test is not available", json.equals("")); JSONParser parser = new JSONParser(); - JSONObject testSuiteObj = (JSONObject)parser.parse(json); + JSONObject testSuiteObj = (JSONObject) parser.parse(json); TestSuite testSuite = new TestSuite(testSuiteObj); Iterator testIterator = testSuite.iterator(); - while (testIterator.hasNext()){ + while (testIterator.hasNext()) { TestCase testCase = testIterator.next(); @@ -55,11 +55,11 @@ public class GitHubJSONTestSuite { Assume.assumeFalse("Online test is not available", json.equals("")); JSONParser parser = new JSONParser(); - JSONObject testSuiteObj = (JSONObject)parser.parse(json); + JSONObject testSuiteObj = (JSONObject) parser.parse(json); StateTestSuite testSuite = new StateTestSuite(testSuiteObj); - for(StateTestCase testCase : testSuite.getAllTests()){ + for (StateTestCase testCase : testSuite.getAllTests()) { if (testCase.getName().equals(testName)) logger.info(" => " + testCase.getName()); else @@ -70,8 +70,8 @@ public class GitHubJSONTestSuite { TestRunner runner = new TestRunner(); List result = runner.runTestCase(testCase); - if (!result.isEmpty()){ - for (String single : result){ + if (!result.isEmpty()) { + for (String single : result) { logger.info(single); } } @@ -83,12 +83,12 @@ public class GitHubJSONTestSuite { Assume.assumeFalse("Online test is not available", json.equals("")); JSONParser parser = new JSONParser(); - JSONObject testSuiteObj = (JSONObject)parser.parse(json); + JSONObject testSuiteObj = (JSONObject) parser.parse(json); StateTestSuite testSuite = new StateTestSuite(testSuiteObj); - Collection testCollection = testSuite.getAllTests(); + Collection testCollection = testSuite.getAllTests(); - for(StateTestCase testCase : testSuite.getAllTests()){ + for (StateTestCase testCase : testSuite.getAllTests()) { String prefix = " "; if (exclude.contains(testCase.getName())) prefix = "[X] "; @@ -96,14 +96,14 @@ public class GitHubJSONTestSuite { logger.info(prefix + testCase.getName()); } - for (StateTestCase testCase : testCollection){ + for (StateTestCase testCase : testCollection) { if (exclude.contains(testCase.getName())) continue; TestRunner runner = new TestRunner(); List result = runner.runTestCase(testCase); - if (!result.isEmpty()){ - for (String single : result){ + if (!result.isEmpty()) { + for (String single : result) { logger.info(single); } } @@ -117,19 +117,19 @@ public class GitHubJSONTestSuite { Assume.assumeFalse("Online test is not available", json.equals("")); JSONParser parser = new JSONParser(); - JSONObject testSuiteObj = (JSONObject)parser.parse(json); + JSONObject testSuiteObj = (JSONObject) parser.parse(json); StateTestSuite testSuite = new StateTestSuite(testSuiteObj); - Collection testCollection = testSuite.getAllTests(); + Collection testCollection = testSuite.getAllTests(); - for (StateTestCase testCase : testCollection){ + for (StateTestCase testCase : testCollection) { TestRunner runner = new TestRunner(); List result = runner.runTestCase(testCase); - if (!result.isEmpty()){ - for (String single : result){ + if (!result.isEmpty()) { + for (String single : result) { logger.info(single); } } diff --git a/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubStateTest.java b/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubStateTest.java index 9b40e3e4..1be274cb 100644 --- a/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubStateTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubStateTest.java @@ -96,7 +96,5 @@ public class GitHubStateTest { } - - } diff --git a/ethereumj-core/src/test/java/test/ethereum/mine/ForkGenTest.java b/ethereumj-core/src/test/java/test/ethereum/mine/ForkGenTest.java index 15e054fb..8df94814 100644 --- a/ethereumj-core/src/test/java/test/ethereum/mine/ForkGenTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/mine/ForkGenTest.java @@ -19,7 +19,7 @@ public class ForkGenTest { @Test @Ignore - public void mineOnBlock(){ + public void mineOnBlock() { byte[] blockRaw = Hex.decode("f90139f90134a077702830ce2f66cdbf82cabd600ddb760a68b73c93739bdd439309989b22f93ba01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794907a0f5f767664ac77c8e431b99e74abc9288a40a0a2deb803ea8704997ae17efd0adf038df2833505da8776f095e32174dcb8e4aba056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b840000000000000000000000000000000000000000000002000000000004000000000000020000000000000000000000000000000000000000000000000000000008301f2363c8609184e72a000830e63bb80845461623980a05643fd40385c6520e3320109adc71917fdbbcdffe61f0b476ccb3b34111af194c0c0"); byte[] coinbase = Hex.decode("cd2a3d9f938e13cd947ec05abc7fe734df8dd826"); @@ -40,14 +40,14 @@ public class ForkGenTest { @Test @Ignore - public void makeFork(){ + public void makeFork() { - MineSwarm swarm = new MineSwarm (); + MineSwarm swarm = new MineSwarm(); swarm.start(); - while(swarm.started.get()){ + while (swarm.started.get()) { try { Thread.sleep(1000); } catch (InterruptedException e) { diff --git a/ethereumj-core/src/test/java/test/ethereum/mine/MineSwarm.java b/ethereumj-core/src/test/java/test/ethereum/mine/MineSwarm.java index e203717d..13e54779 100644 --- a/ethereumj-core/src/test/java/test/ethereum/mine/MineSwarm.java +++ b/ethereumj-core/src/test/java/test/ethereum/mine/MineSwarm.java @@ -54,11 +54,15 @@ public class MineSwarm { miner3.start(); workers.add(mt3); - while(!mt1.isDone() || !mt2.isDone() || !mt3.isDone()){ - try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} + while (!mt1.isDone() || !mt2.isDone() || !mt3.isDone()) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } } - while(!blockAppearQueue.isEmpty()){ + while (!blockAppearQueue.isEmpty()) { System.out.println( Hex.toHexString(blockAppearQueue.poll().getEncoded()) ); @@ -77,12 +81,12 @@ public class MineSwarm { public void announceBlock(Block block) { - for(MinerThread mt : workers){ - mt.onNewBlock(block); + for (MinerThread mt : workers) { + mt.onNewBlock(block); } } - public void addToQueue(Block block){ + public void addToQueue(Block block) { synchronized (blockAppearQueue) { blockAppearQueue.add(block); } diff --git a/ethereumj-core/src/test/java/test/ethereum/mine/MinerThread.java b/ethereumj-core/src/test/java/test/ethereum/mine/MinerThread.java index aa9f0beb..5cd25c1f 100644 --- a/ethereumj-core/src/test/java/test/ethereum/mine/MinerThread.java +++ b/ethereumj-core/src/test/java/test/ethereum/mine/MinerThread.java @@ -22,19 +22,19 @@ public class MinerThread implements Runnable { private final static Logger logger = LoggerFactory.getLogger("miner"); private final byte[] coinbase; - private MineSwarm mineSwarm; - private String name; - private boolean done = false; + private MineSwarm mineSwarm; + private String name; + private boolean done = false; private Miner miner = new Miner(); - private Chain mainChain = new Chain(); - private List altChains = new ArrayList<>(); - private Block tmpBlock = null; - private List uncles = new ArrayList<>(); + private Chain mainChain = new Chain(); + private List altChains = new ArrayList<>(); + private Block tmpBlock = null; + private List uncles = new ArrayList<>(); private Block announcedBlock = null; - public MinerThread(String name, MineSwarm mineSwarm, byte[] coinbase) { + public MinerThread(String name, MineSwarm mineSwarm, byte[] coinbase) { this.name = name; this.mineSwarm = mineSwarm; this.coinbase = coinbase; @@ -51,9 +51,9 @@ public class MinerThread implements Runnable { logger.debug("{} end", name); } - public void onNewBlock(Block foundBlock){ + public void onNewBlock(Block foundBlock) { - if (mainChain.getLast().isEqual(foundBlock)){ + if (mainChain.getLast().isEqual(foundBlock)) { // That is our announcement, do nothing. return; } @@ -63,20 +63,20 @@ public class MinerThread implements Runnable { Hex.toHexString(foundBlock.getParentHash()).substring(0, 6)); - if ( mainChain.getLast().isParentOf(foundBlock) ){ + if (mainChain.getLast().isParentOf(foundBlock)) { logger.info("{}: adding by announce to main chain. hash:{} ", name, Hex.toHexString(foundBlock.getHash()).substring(0, 6)); // add it as main block announcedBlock = foundBlock; miner.stop(); - } else{ + } else { - if (mainChain.isParentOnTheChain(foundBlock)){ + if (mainChain.isParentOnTheChain(foundBlock)) { logger.info("{} found an uncle. on index: {}", name, foundBlock.getNumber()); // add it as a future uncle uncles.add(foundBlock); - } else{ + } else { logger.info("{}: nothing to do, maybe alt chain: {}: {} ^ {}", name, foundBlock.getNumber(), Hex.toHexString(foundBlock.getHash()).substring(0, 6), Hex.toHexString(foundBlock.getParentHash()).substring(0, 6)); @@ -84,7 +84,7 @@ public class MinerThread implements Runnable { } } - public void announceBlock(Block block){ + public void announceBlock(Block block) { mineSwarm.announceBlock(block); } @@ -92,7 +92,7 @@ public class MinerThread implements Runnable { Block genesis = mainChain.getLast(); tmpBlock = createBlock(genesis, coinbase); - while (!done){ + while (!done) { this.announcedBlock = null; logger.info("{}: before mining: chain.size: [{}], chain.TD: [{}]", name, @@ -100,7 +100,7 @@ public class MinerThread implements Runnable { boolean found = miner.mine(tmpBlock, tmpBlock.getDifficulty()); logger.info("{}: finished mining, found: [{}]", name, found); - if (!found && announcedBlock != null){ + if (!found && announcedBlock != null) { mainChain.add(announcedBlock); tmpBlock = createBlock(announcedBlock, coinbase); } @@ -111,7 +111,7 @@ public class MinerThread implements Runnable { Hex.toHexString(tmpBlock.getHash()).substring(0, 6), Hex.toHexString(tmpBlock.getParentHash()).substring(0, 6)); if (announcedBlock != null) - logger.info("{}: forked on: {}",name, tmpBlock.getNumber()); + logger.info("{}: forked on: {}", name, tmpBlock.getNumber()); logger.info("{}: adding to main chain. hash:{} ", name, Hex.toHexString(tmpBlock.getHash()).substring(0, 6)); @@ -121,8 +121,8 @@ public class MinerThread implements Runnable { tmpBlock = createBlock(tmpBlock, coinbase); } - if (!uncles.isEmpty()){ - for (Block uncle : uncles){ + if (!uncles.isEmpty()) { + for (Block uncle : uncles) { BlockHeader uncleHeader = uncle.getHeader(); tmpBlock.addUncle(uncleHeader); logger.info("{} adding {} uncles to block: {}", name, uncles.size(), tmpBlock.getNumber()); @@ -138,9 +138,9 @@ public class MinerThread implements Runnable { public static Block createBlock(Block lastBlock, byte[] coinbase) { - long timeDiff = System.currentTimeMillis() - lastBlock.getTimestamp(); + long timeDiff = System.currentTimeMillis() - lastBlock.getTimestamp(); - byte[] difficulty = lastBlock.getDifficulty(); + byte[] difficulty = lastBlock.getDifficulty(); // if (timeDiff < 5000){ // System.out.println("increase"); // BigInteger diff = (new BigInteger(1, lastBlock.getDifficulty()).add(new BigInteger("FFF", 16))); @@ -148,9 +148,9 @@ public class MinerThread implements Runnable { // } Block newBlock = new Block(lastBlock.getHash(), lastBlock.getUnclesHash(), coinbase, lastBlock.getLogBloom(), - difficulty , lastBlock.getNumber() + 1, + difficulty, lastBlock.getNumber() + 1, lastBlock.getGasLimit(), lastBlock.getGasUsed(), System.currentTimeMillis() / 1000, - null, null, null, null); + null, null, null, null); return newBlock; } @@ -163,7 +163,7 @@ public class MinerThread implements Runnable { return mainChain; } - private void sleep(){ + private void sleep() { try { Thread.sleep(500); } catch (InterruptedException e) { diff --git a/ethereumj-core/src/test/java/test/ethereum/net/BlockHashesMessageTest.java b/ethereumj-core/src/test/java/test/ethereum/net/BlockHashesMessageTest.java index e71f4314..5584f5a3 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/BlockHashesMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/BlockHashesMessageTest.java @@ -1,4 +1,4 @@ - package test.ethereum.net; +package test.ethereum.net; import static org.junit.Assert.assertEquals; @@ -33,8 +33,8 @@ public class BlockHashesMessageTest { @Test /* BlockHashesMessage 2 from new */ public void test_2() { List blockHashes = Arrays.asList( - Hex.decode("4ee6424d776b3f59affc20bc2de59e67f36e22cc07897ff8df152242c921716b"), - Hex.decode("7d2fe4df0dbbc9011da2b3bf177f0c6b7e71a11c509035c5d751efa5cf9b4817") + Hex.decode("4ee6424d776b3f59affc20bc2de59e67f36e22cc07897ff8df152242c921716b"), + Hex.decode("7d2fe4df0dbbc9011da2b3bf177f0c6b7e71a11c509035c5d751efa5cf9b4817") ); BlockHashesMessage blockHashesMessage = new BlockHashesMessage(blockHashes); System.out.println(blockHashesMessage); diff --git a/ethereumj-core/src/test/java/test/ethereum/net/BlocksMessageTest.java b/ethereumj-core/src/test/java/test/ethereum/net/BlocksMessageTest.java index 01da5bc7..682e6d28 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/BlocksMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/BlocksMessageTest.java @@ -59,7 +59,7 @@ public class BlocksMessageTest { assertEquals(1, block.getTransactionsList().size()); assertEquals(3911, block.getNumber()); assertEquals("140446b9f55bbbe9bad9fe963157cf0fc6ab2d068433eb95e161847f197362b2", - Hex.toHexString(block.getHash())); + Hex.toHexString(block.getHash())); assertEquals("396d2ff722ae3811cb5deb69270933c8016f2397a5189aac429bc6fc466607bb", Hex.toHexString(block.getStateRoot())); } @@ -102,7 +102,7 @@ public class BlocksMessageTest { BlocksMessage blocksMessage = new BlocksMessage(data); int size = blocksMessage.getBlocks().size(); - for (int i = 0; i < size; ++i){ + for (int i = 0; i < size; ++i) { Block block = blocksMessage.getBlocks().get(i); diff --git a/ethereumj-core/src/test/java/test/ethereum/net/HelloMessageTest.java b/ethereumj-core/src/test/java/test/ethereum/net/HelloMessageTest.java index e7cad5a0..2b174c2f 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/HelloMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/HelloMessageTest.java @@ -32,7 +32,7 @@ public class HelloMessageTest { assertEquals(P2pMessageCodes.HELLO, helloMessage.getCommand()); assertEquals(2, helloMessage.getP2PVersion()); assertEquals("Ethereum(++)/v0.7.9/Release/Linux/g++", helloMessage.getClientId()); - assertEquals(2, helloMessage.getCapabilities().size()); + assertEquals(2, helloMessage.getCapabilities().size()); assertEquals(992, helloMessage.getListenPort()); assertEquals( "1fbf1e41f08078918c9f7b6734594ee56d7f538614f602c71194db0a1af5a77f9b86eb14669fe7a8a46a2dd1b7d070b94e463f4ecd5b337c8b4d31bbf8dd5646", diff --git a/ethereumj-core/src/test/java/test/ethereum/net/NewBlockMessageTest.java b/ethereumj-core/src/test/java/test/ethereum/net/NewBlockMessageTest.java index 452fdf8c..c8013493 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/NewBlockMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/NewBlockMessageTest.java @@ -22,11 +22,11 @@ public class NewBlockMessageTest { byte[] payload = Hex.decode(newBlockRaw); NewBlockMessage newBlockMessage = new NewBlockMessage(payload); - logger.info( newBlockMessage.toString() ); + logger.info(newBlockMessage.toString()); } @Test - public void test_2(){ + public void test_2() { Block block = new Block( Hex.decode("f90277f8cfa0887ef3904d3c464cbb3ce2a7e2ce02c57b1a38caaa5013ad1202ead0fc1077baa0a962ba850109a5112e7bd3109db477014057b478772825173cc3da54cfc3264e94407d73d8a49eeb85d32cf465507dd71d507100c180a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b42180830200000380830f42408086014997893f1080a000000000000000000000000000000000000000000000000000000000000018e9c0f901a2f8cfa0955f36d073ccb026b78ab3424c15cf966a7563aa270413859f78702b9e8e22cba01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942bd26d8f796719923ff13d295644f9b45db1f73080a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b42180830200000180830f4240808601499789326680a00000000000000000000000000000000000000000000000000000000000010da5f8cfa0717e058643634a0f80b9cf33da423d304dabaa826c586f50a783ba6c70cfd60da01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794f92c0f3e4825f09490ca264dc0cdacffeb566f0680a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b42180830200000280830f424080860149978936fe80a0000000000000000000000000000000000000000000000000000000000001d01f")); diff --git a/ethereumj-core/src/test/java/test/ethereum/net/PeersMessageTest.java b/ethereumj-core/src/test/java/test/ethereum/net/PeersMessageTest.java index 1989298d..c3bc5c56 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/PeersMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/PeersMessageTest.java @@ -39,7 +39,7 @@ public class PeersMessageTest { String peersMessageRaw = "f84b05f848846894d84870b84036659c3656c488437cceb11abeb9b9fc69b8055144a7e7db3584d03e606083f90e17a1d3021d674579407cdaaafdfeef485872ab719db9f2b6283f498bb90a71"; byte[] payload = Hex.decode(peersMessageRaw); - PeersMessage peersMessage= new PeersMessage(payload); + PeersMessage peersMessage = new PeersMessage(payload); logger.info(peersMessage.toString()); assertEquals(1, peersMessage.getPeers().size()); diff --git a/ethereumj-core/src/test/java/test/ethereum/net/StatusMessageTest.java b/ethereumj-core/src/test/java/test/ethereum/net/StatusMessageTest.java index 47ba0c0e..063938ee 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/StatusMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/StatusMessageTest.java @@ -15,7 +15,7 @@ public class StatusMessageTest { private static final Logger logger = LoggerFactory.getLogger("test"); @Test - public void test1(){ + public void test1() { String raw = "f84a1027808425c60144a0832056d3c93ff2739ace7199952e5365aa29f18805be05634c4db125c5340216a0955f36d073ccb026b78ab3424c15cf966a7563aa270413859f78702b9e8e22cb"; byte[] payload = Hex.decode(raw); diff --git a/ethereumj-core/src/test/java/test/ethereum/net/TransactionsMessageTest.java b/ethereumj-core/src/test/java/test/ethereum/net/TransactionsMessageTest.java index 6bdfaa15..41965155 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/TransactionsMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/TransactionsMessageTest.java @@ -62,7 +62,7 @@ public class TransactionsMessageTest { assertEquals("09184e72a000", Hex.toHexString(tx.getGasLimit())); assertEquals("", ByteUtil.toHexString(tx.getData())); - assertEquals("1b", Hex.toHexString(new byte[] { tx.getSignature().v })); + assertEquals("1b", Hex.toHexString(new byte[]{tx.getSignature().v})); assertEquals("5c89ebf2b77eeab88251e553f6f9d53badc1d800bbac02d830801c2aa94a4c9f", Hex.toHexString(tx.getSignature().r.toByteArray())); assertEquals("0b7907532b1f29c79942b75fff98822293bf5fdaa3653a8d9f424c6a3265f06c", Hex.toHexString(tx.getSignature().s.toByteArray())); } @@ -100,7 +100,8 @@ public class TransactionsMessageTest { assertEquals(3, transactionsMessage.getTransactions().size()); Iterator txIter = transactionsMessage.getTransactions().iterator(); - Transaction tx1 = txIter.next(); txIter.next(); // skip one + Transaction tx1 = txIter.next(); + txIter.next(); // skip one Transaction tx3 = txIter.next(); assertEquals("1b9d9456293cbcbc2f28a0fdc67028128ea571b033fb0e21d0ee00bcd6167e5d", @@ -124,7 +125,7 @@ public class TransactionsMessageTest { Hex.toHexString(tx3.getData())); assertEquals("33", - Hex.toHexString(new byte[] {tx3.getSignature().v})); + Hex.toHexString(new byte[]{tx3.getSignature().v})); assertEquals("1c", Hex.toHexString(tx3.getSignature().r.toByteArray())); @@ -151,11 +152,12 @@ public class TransactionsMessageTest { assertEquals("ccdeac59d35627b7de09332e819d5159e7bb7250", Hex.toHexString(tx1.getGasLimit())); - assertEquals("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000002d0aceee7e5ab874e22ccf8d1a649f59106d74e8", + assertEquals + ("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000002d0aceee7e5ab874e22ccf8d1a649f59106d74e8", Hex.toHexString(tx1.getData())); assertEquals("1b", - Hex.toHexString(new byte[] {tx1.getSignature().v})); + Hex.toHexString(new byte[]{tx1.getSignature().v})); assertEquals("00d05887574456c6de8f7a0d172342c2cbdd4cf7afe15d9dbb8b75b748ba6791c9", Hex.toHexString(tx1.getSignature().r.toByteArray())); @@ -167,18 +169,19 @@ public class TransactionsMessageTest { @Test /* Transactions msg encode */ public void test_3() throws Exception { - String expected = "f87302f870808b00d3c21bcecceda10000009479b08ad8787060333663d19704909ee7b1903e588609184e72a000824255801ca00f410a70e42b2c9854a8421d32c87c370a2b9fff0a27f9f031bb4443681d73b5a018a7dc4c4f9dee9f3dc35cb96ca15859aa27e219a8e4a8547be6bd3206979858"; + String expected = + "f87302f870808b00d3c21bcecceda10000009479b08ad8787060333663d19704909ee7b1903e588609184e72a000824255801ca00f410a70e42b2c9854a8421d32c87c370a2b9fff0a27f9f031bb4443681d73b5a018a7dc4c4f9dee9f3dc35cb96ca15859aa27e219a8e4a8547be6bd3206979858"; BigInteger value = new BigInteger("1000000000000000000000000"); byte[] privKey = HashUtil.sha3("cat".getBytes()); ECKey ecKey = ECKey.fromPrivate(privKey); - byte[] gasPrice= Hex.decode("09184e72a000"); - byte[] gas = Hex.decode("4255"); + byte[] gasPrice = Hex.decode("09184e72a000"); + byte[] gas = Hex.decode("4255"); Transaction tx = new Transaction(null, value.toByteArray(), - ecKey.getAddress(), gasPrice, gas, null); + ecKey.getAddress(), gasPrice, gas, null); tx.sign(privKey); tx.getEncoded(); diff --git a/ethereumj-core/src/test/java/test/ethereum/net/wire/AdaptiveMessageIdsTest.java b/ethereumj-core/src/test/java/test/ethereum/net/wire/AdaptiveMessageIdsTest.java index c2892896..11eddf4f 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/wire/AdaptiveMessageIdsTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/wire/AdaptiveMessageIdsTest.java @@ -15,63 +15,62 @@ import java.util.Arrays; import java.util.List; /** - * * @author: Roman Mandeleil * Created on: 15/10/2014 12:34 */ public class AdaptiveMessageIdsTest { @Before - public void setUp(){ - EthMessageCodes.setOffset((byte)0x00); - ShhMessageCodes.setOffset((byte)0x00); + public void setUp() { + EthMessageCodes.setOffset((byte) 0x00); + ShhMessageCodes.setOffset((byte) 0x00); } @Test public void test1() { - Assert.assertEquals(7, P2pMessageCodes.values().length ); + Assert.assertEquals(7, P2pMessageCodes.values().length); - Assert.assertEquals(0, P2pMessageCodes.HELLO.asByte()); - Assert.assertEquals(1, P2pMessageCodes.DISCONNECT.asByte()); - Assert.assertEquals(2, P2pMessageCodes.PING.asByte()); - Assert.assertEquals(3, P2pMessageCodes.PONG.asByte()); - Assert.assertEquals(4, P2pMessageCodes.GET_PEERS.asByte()); - Assert.assertEquals(5, P2pMessageCodes.PEERS.asByte()); + Assert.assertEquals(0, P2pMessageCodes.HELLO.asByte()); + Assert.assertEquals(1, P2pMessageCodes.DISCONNECT.asByte()); + Assert.assertEquals(2, P2pMessageCodes.PING.asByte()); + Assert.assertEquals(3, P2pMessageCodes.PONG.asByte()); + Assert.assertEquals(4, P2pMessageCodes.GET_PEERS.asByte()); + Assert.assertEquals(5, P2pMessageCodes.PEERS.asByte()); Assert.assertEquals(15, P2pMessageCodes.USER.asByte()); } @Test public void test2() { - Assert.assertEquals(9, EthMessageCodes.values().length ); + Assert.assertEquals(9, EthMessageCodes.values().length); - Assert.assertEquals(0, EthMessageCodes.STATUS.asByte()); - Assert.assertEquals(1, EthMessageCodes.GET_TRANSACTIONS.asByte()); - Assert.assertEquals(2, EthMessageCodes.TRANSACTIONS.asByte()); - Assert.assertEquals(3, EthMessageCodes.GET_BLOCK_HASHES.asByte()); - Assert.assertEquals(4, EthMessageCodes.BLOCK_HASHES.asByte()); - Assert.assertEquals(5, EthMessageCodes.GET_BLOCKS.asByte()); - Assert.assertEquals(6, EthMessageCodes.BLOCKS.asByte()); - Assert.assertEquals(7, EthMessageCodes.NEW_BLOCK.asByte()); - Assert.assertEquals(8, EthMessageCodes.PACKET_COUNT.asByte()); + Assert.assertEquals(0, EthMessageCodes.STATUS.asByte()); + Assert.assertEquals(1, EthMessageCodes.GET_TRANSACTIONS.asByte()); + Assert.assertEquals(2, EthMessageCodes.TRANSACTIONS.asByte()); + Assert.assertEquals(3, EthMessageCodes.GET_BLOCK_HASHES.asByte()); + Assert.assertEquals(4, EthMessageCodes.BLOCK_HASHES.asByte()); + Assert.assertEquals(5, EthMessageCodes.GET_BLOCKS.asByte()); + Assert.assertEquals(6, EthMessageCodes.BLOCKS.asByte()); + Assert.assertEquals(7, EthMessageCodes.NEW_BLOCK.asByte()); + Assert.assertEquals(8, EthMessageCodes.PACKET_COUNT.asByte()); - EthMessageCodes.setOffset((byte)0x10); - Assert.assertEquals(0x10 + 0, EthMessageCodes.STATUS.asByte()); - Assert.assertEquals(0x10 + 1, EthMessageCodes.GET_TRANSACTIONS.asByte()); - Assert.assertEquals(0x10 + 2, EthMessageCodes.TRANSACTIONS.asByte()); - Assert.assertEquals(0x10 + 3, EthMessageCodes.GET_BLOCK_HASHES.asByte()); - Assert.assertEquals(0x10 + 4, EthMessageCodes.BLOCK_HASHES.asByte()); - Assert.assertEquals(0x10 + 5, EthMessageCodes.GET_BLOCKS.asByte()); - Assert.assertEquals(0x10 + 6, EthMessageCodes.BLOCKS.asByte()); - Assert.assertEquals(0x10 + 7, EthMessageCodes.NEW_BLOCK.asByte()); + EthMessageCodes.setOffset((byte) 0x10); + Assert.assertEquals(0x10 + 0, EthMessageCodes.STATUS.asByte()); + Assert.assertEquals(0x10 + 1, EthMessageCodes.GET_TRANSACTIONS.asByte()); + Assert.assertEquals(0x10 + 2, EthMessageCodes.TRANSACTIONS.asByte()); + Assert.assertEquals(0x10 + 3, EthMessageCodes.GET_BLOCK_HASHES.asByte()); + Assert.assertEquals(0x10 + 4, EthMessageCodes.BLOCK_HASHES.asByte()); + Assert.assertEquals(0x10 + 5, EthMessageCodes.GET_BLOCKS.asByte()); + Assert.assertEquals(0x10 + 6, EthMessageCodes.BLOCKS.asByte()); + Assert.assertEquals(0x10 + 7, EthMessageCodes.NEW_BLOCK.asByte()); Assert.assertEquals(0x10 + 8, EthMessageCodes.PACKET_COUNT.asByte()); } @Test - public void test3(){ + public void test3() { - Assert.assertEquals(5, ShhMessageCodes.values().length ); + Assert.assertEquals(5, ShhMessageCodes.values().length); Assert.assertEquals(0, ShhMessageCodes.STATUS.asByte()); Assert.assertEquals(1, ShhMessageCodes.MESSAGE.asByte()); @@ -88,7 +87,7 @@ public class AdaptiveMessageIdsTest { } @Test - public void test4(){ + public void test4() { P2pHandler p2pHandler = new P2pHandler(); @@ -115,7 +114,7 @@ public class AdaptiveMessageIdsTest { } @Test // Capabilities should be read in alphabetical order - public void test5(){ + public void test5() { P2pHandler p2pHandler = new P2pHandler(); diff --git a/ethereumj-core/src/test/java/test/ethereum/serpent/MachineCompileTest.java b/ethereumj-core/src/test/java/test/ethereum/serpent/MachineCompileTest.java index a0ed541a..44e394e3 100644 --- a/ethereumj-core/src/test/java/test/ethereum/serpent/MachineCompileTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/serpent/MachineCompileTest.java @@ -8,6 +8,7 @@ import org.spongycastle.util.encoders.Hex; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 28/05/2014 20:05 */ diff --git a/ethereumj-core/src/test/java/test/ethereum/serpent/SerpentCompileTest.java b/ethereumj-core/src/test/java/test/ethereum/serpent/SerpentCompileTest.java index 23493f7d..b2cd9e99 100644 --- a/ethereumj-core/src/test/java/test/ethereum/serpent/SerpentCompileTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/serpent/SerpentCompileTest.java @@ -1,6 +1,7 @@ package test.ethereum.serpent; import org.antlr.v4.runtime.tree.ParseTree; + import static org.junit.Assert.*; import org.ethereum.serpent.*; @@ -8,6 +9,7 @@ import org.junit.Test; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 13/05/14 10:07 */ @@ -34,7 +36,7 @@ public class SerpentCompileTest { public void test2() { String code = "a=2\n" + - "b=6"; + "b=6"; String expected = "2 0 MSTORE 6 32 MSTORE"; SerpentParser parser = ParserUtils.getParser(SerpentLexer.class, @@ -52,8 +54,8 @@ public class SerpentCompileTest { public void test3() { String code = "a=2\n" + - "b=6\n" + - "c=b"; + "b=6\n" + + "c=b"; String expected = "2 0 MSTORE 6 32 MSTORE 32 MLOAD 64 MSTORE"; SerpentParser parser = ParserUtils.getParser(SerpentLexer.class, @@ -71,9 +73,9 @@ public class SerpentCompileTest { public void test4() { String code = "a=2\n" + - "b=6\n" + - "c=b\n" + - "a=c"; + "b=6\n" + + "c=b\n" + + "a=c"; String expected = "2 0 MSTORE 6 32 MSTORE 32 MLOAD 64 MSTORE 64 MLOAD 0 MSTORE"; SerpentParser parser = ParserUtils.getParser(SerpentLexer.class, @@ -87,7 +89,7 @@ public class SerpentCompileTest { assertEquals(expected, result); } - @Test(expected=SerpentToAssemblyCompiler.UnassignVarException.class) // assign test 5 + @Test(expected = SerpentToAssemblyCompiler.UnassignVarException.class) // assign test 5 public void test5() { String code = "a=2\n" + @@ -278,7 +280,7 @@ public class SerpentCompileTest { public void test16() { String code = "if 1>2: \n" + - " a=2"; + " a=2"; String expected = "2 1 GT NOT REF_1 JUMPI 2 0 MSTORE REF_0 JUMP LABEL_1 LABEL_0"; /** @@ -288,7 +290,7 @@ public class SerpentCompileTest { REF_0 JUMP LABEL_1 LABEL_0 - */ + */ SerpentParser parser = ParserUtils.getParser(SerpentLexer.class, SerpentParser.class, code); ParseTree tree = parser.parse(); @@ -304,7 +306,7 @@ public class SerpentCompileTest { public void test17() { String code = "if 10 > 2 + 5: \n" + - " a=2"; + " a=2"; String expected = "5 2 ADD 10 GT NOT REF_1 JUMPI 2 0 MSTORE REF_0 JUMP LABEL_1 LABEL_0"; /** @@ -314,7 +316,7 @@ public class SerpentCompileTest { REF_0 JUMP LABEL_1 LABEL_0 - */ + */ SerpentParser parser = ParserUtils.getParser(SerpentLexer.class, SerpentParser.class, code); @@ -331,9 +333,9 @@ public class SerpentCompileTest { public void test18() { String code = "if 10 > 2 + 5: \n" + - " a=2\n" + - "else: \n" + - " c=3\n"; + " a=2\n" + + "else: \n" + + " c=3\n"; String expected = "5 2 ADD 10 GT NOT REF_1 JUMPI 2 0 MSTORE REF_0 JUMP LABEL_1 3 32 MSTORE LABEL_0"; /** @@ -760,13 +762,13 @@ public class SerpentCompileTest { assertEquals(expected, result); } - @Test(expected=ParserUtils.AntlrParseException.class) // if elif else test 14 + @Test(expected = ParserUtils.AntlrParseException.class) // if elif else test 14 public void test29() { - String code = " if 2>4: \n" + - " a=20 \n" + - " \n" + - " \n"; + String code = " if 2>4: \n" + + " a=20 \n" + + " \n" + + " \n"; SerpentParser parser = ParserUtils.getParser(SerpentLexer.class, SerpentParser.class, code); @@ -775,13 +777,13 @@ public class SerpentCompileTest { fail("Should be indent error thrown"); } - @Test(expected=ParserUtils.AntlrParseException.class) // if elif else test 15 + @Test(expected = ParserUtils.AntlrParseException.class) // if elif else test 15 public void test30() { - String code = "if 2>4: \n" + - " a=20 \n" + - " else: \n" + - " a=40 \n"; + String code = "if 2>4: \n" + + " a=20 \n" + + " else: \n" + + " a=40 \n"; SerpentParser parser = ParserUtils.getParser(SerpentLexer.class, SerpentParser.class, code); @@ -790,15 +792,15 @@ public class SerpentCompileTest { fail("Should be indent error thrown"); } - @Test(expected=ParserUtils.AntlrParseException.class) // if elif else test 16 + @Test(expected = ParserUtils.AntlrParseException.class) // if elif else test 16 public void test31() { - String code = "if 2>4: \n" + - " a=20 \n" + - " elif 2<9: \n" + - " a=40 \n" + - "else: \n" + - " a=40 \n"; + String code = "if 2>4: \n" + + " a=20 \n" + + " elif 2<9: \n" + + " a=40 \n" + + "else: \n" + + " a=40 \n"; SerpentParser parser = ParserUtils.getParser(SerpentLexer.class, SerpentParser.class, code); @@ -841,15 +843,15 @@ public class SerpentCompileTest { assertEquals(expected, result); } - @Test(expected=ParserUtils.AntlrParseException.class) // if elif else test 18 + @Test(expected = ParserUtils.AntlrParseException.class) // if elif else test 18 public void test33() { - String code = "if 2*2==4: \n" + - " if 3*3==9: \n" + - " if 4*4==16: \n" + - " a=20 \n" + - " else: \n" + - " \n"; + String code = "if 2*2==4: \n" + + " if 3*3==9: \n" + + " if 4*4==16: \n" + + " a=20 \n" + + " else: \n" + + " \n"; SerpentParser parser = ParserUtils.getParser(SerpentLexer.class, SerpentParser.class, code); @@ -948,9 +950,9 @@ public class SerpentCompileTest { @Test // while test 1 public void test36() { - String code = "a = 20 \n" + - "while a>0: \n" + - " a = a - 1 \n" ; + String code = "a = 20 \n" + + "while a>0: \n" + + " a = a - 1 \n"; String expected = "20 0 MSTORE LABEL_0 0 0 MLOAD GT NOT REF_1 JUMPI 1 0 MLOAD SUB 0 MSTORE REF_0 JUMP LABEL_1"; @@ -1054,13 +1056,13 @@ public class SerpentCompileTest { assertEquals(expected, result); } - @Test(expected=ParserUtils.AntlrParseException.class) // while test 4 + @Test(expected = ParserUtils.AntlrParseException.class) // while test 4 public void test39() { - String code = "x = 0xFF\n" + - "while x > 1:\n" + - "x = x +2\n" + - "x = 3 * x + 1" ; + String code = "x = 0xFF\n" + + "while x > 1:\n" + + "x = x +2\n" + + "x = 3 * x + 1"; SerpentParser parser = ParserUtils.getParser(SerpentLexer.class, SerpentParser.class, code); @@ -1151,12 +1153,12 @@ public class SerpentCompileTest { @Test // compile to machine code 1 public void test42() { - String code = "x = 256 \n" + + String code = "x = 256 \n" + "while x > 1: \n" + " if (x % 2) == 0: \n" + " x = x / 2 \n" + " else: \n " + - " x = 3 * x + 1 \n" ; + " x = 3 * x + 1 \n"; String expected = "97 1 0 96 0 84 96 1 96 0 83 11 12 13 99 0 0 0 53 89 96 0 96 2 96 0 83 6 12 13 99 0 0 0 39 89 96 2 96 0 83 4 96 0 84 99 0 0 0 51 88 96 1 96 0 83 96 3 2 1 96 0 84 99 0 0 0 6 88"; @@ -1167,11 +1169,11 @@ public class SerpentCompileTest { @Test // test init/code blocks 1 public void test43() { - String code = "init:\n" + - " a = 2\n" + - "code:\n" + - " b=msg.data[1]\n" + - " stop\n" ; + String code = "init:\n" + + " a = 2\n" + + "code:\n" + + " b=msg.data[1]\n" + + " stop\n"; String expected = "[init 2 0 MSTORE init] [code 1 32 MUL CALLDATALOAD 0 MSTORE STOP code]"; String asmResult = SerpentCompiler.compileFullNotion(code); @@ -1256,7 +1258,7 @@ public class SerpentCompileTest { @Test // test create(gas, mem_start , mem_size) public void test51() { - String code = "\n" + + String code = "\n" + "create(100, 0, 32) \n"; String expected = "32 0 100 CREATE"; diff --git a/ethereumj-core/src/test/java/test/ethereum/trie/TrieTest.java b/ethereumj-core/src/test/java/test/ethereum/trie/TrieTest.java index 4ea08ed3..228eb808 100644 --- a/ethereumj-core/src/test/java/test/ethereum/trie/TrieTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/trie/TrieTest.java @@ -147,8 +147,8 @@ public class TrieTest { trie.update(cat, dog); assertEquals(dog, new String(trie.get(cat))); - trie.update(cat, dog+"1"); - assertEquals(dog+"1", new String(trie.get(cat))); + trie.update(cat, dog + "1"); + assertEquals(dog + "1", new String(trie.get(cat))); } @Test @@ -156,8 +156,8 @@ public class TrieTest { TrieImpl trie = new TrieImpl(mockDb); trie.update(cat, LONG_STRING); assertEquals(LONG_STRING, new String(trie.get(cat))); - trie.update(cat, LONG_STRING+"1"); - assertEquals(LONG_STRING+"1", new String(trie.get(cat))); + trie.update(cat, LONG_STRING + "1"); + assertEquals(LONG_STRING + "1", new String(trie.get(cat))); } @Test @@ -167,8 +167,8 @@ public class TrieTest { trie.update(cat, dog); assertEquals(dog, new String(trie.get(cat))); - trie.update(cat, LONG_STRING+"1"); - assertEquals(LONG_STRING+"1", new String(trie.get(cat))); + trie.update(cat, LONG_STRING + "1"); + assertEquals(LONG_STRING + "1", new String(trie.get(cat))); } @Test @@ -178,8 +178,8 @@ public class TrieTest { trie.update(cat, LONG_STRING); assertEquals(LONG_STRING, new String(trie.get(cat))); - trie.update(cat, dog+"1"); - assertEquals(dog+"1", new String(trie.get(cat))); + trie.update(cat, dog + "1"); + assertEquals(dog + "1", new String(trie.get(cat))); } @Test @@ -528,7 +528,7 @@ public class TrieTest { public void testMasiveUpdate(){ boolean massiveUpdateTestEnabled = false; - if(massiveUpdateTestEnabled) { + if (massiveUpdateTestEnabled) { List randomWords = Arrays.asList(randomDictionary.split(",")); HashMap testerMap = new HashMap<>(); @@ -536,7 +536,7 @@ public class TrieTest { Random generator = new Random(); // Random insertion - for (int i = 0; i < 100000; ++i ){ + for (int i = 0; i < 100000; ++i) { int randomIndex1 = generator.nextInt(randomWords.size()); int randomIndex2 = generator.nextInt(randomWords.size()); @@ -549,7 +549,7 @@ public class TrieTest { } int half = testerMap.size() / 2; - for (int r = 0; r < half; ++r){ + for (int r = 0; r < half; ++r) { int randomIndex = generator.nextInt(randomWords.size()); String word1 = randomWords.get(randomIndex).trim(); @@ -563,7 +563,7 @@ public class TrieTest { // Assert the result now Iterator keys = testerMap.keySet().iterator(); - while (keys.hasNext()){ + while (keys.hasNext()) { String mapWord1 = keys.next(); String mapWord2 = testerMap.get(mapWord1); @@ -590,9 +590,9 @@ public class TrieTest { // 1. load the data from massive-upload.dmp // which includes deletes/upadtes (5000 operations) TrieImpl trieSingle = new TrieImpl(mockDb_2); - for (int i = 0; i < strData.size() ; ++i){ + for (int i = 0; i < strData.size(); ++i) { - String[] keyVal= strData.get(i).split("="); + String[] keyVal = strData.get(i).split("="); if (keyVal[0].equals("*")) trieSingle.delete(keyVal[1].trim()); @@ -611,9 +611,9 @@ public class TrieTest { // 3. the rest of the data loaded with part of the trie not in the cache TrieImpl trie = new TrieImpl(mockDb); - for (int i = 0; i < 2000; ++i){ + for (int i = 0; i < 2000; ++i) { - String[] keyVal= strData.get(i).split("="); + String[] keyVal = strData.get(i).split("="); if (keyVal[0].equals("*")) trie.delete(keyVal[1].trim()); @@ -626,9 +626,9 @@ public class TrieTest { TrieImpl trie2 = new TrieImpl(mockDb, trie.getRootHash()); - for (int i = 2000; i < strData.size(); ++i){ + for (int i = 2000; i < strData.size(); ++i) { - String[] keyVal= strData.get(i).split("="); + String[] keyVal = strData.get(i).split("="); if (keyVal[0].equals("*")) trie2.delete(keyVal[1].trim()); @@ -636,17 +636,17 @@ public class TrieTest { trie2.update(keyVal[0].trim(), keyVal[1].trim()); } - System.out.println("root_2: => " + Hex.toHexString( trie2.getRootHash())); + System.out.println("root_2: => " + Hex.toHexString(trie2.getRootHash())); assertEquals(trieSingle.getRootHash(), trie2.getRootHash()); } @Test // tests saving keys to the file // - public void testMasiveUpdateFromDB(){ + public void testMasiveUpdateFromDB() { boolean massiveUpdateFromDBEnabled = false; - if(massiveUpdateFromDBEnabled) { + if (massiveUpdateFromDBEnabled) { List randomWords = Arrays.asList(randomDictionary.split(",")); Map testerMap = new HashMap<>(); @@ -654,7 +654,7 @@ public class TrieTest { Random generator = new Random(); // Random insertion - for (int i = 0; i < 50000; ++i ){ + for (int i = 0; i < 50000; ++i) { int randomIndex1 = generator.nextInt(randomWords.size()); int randomIndex2 = generator.nextInt(randomWords.size()); @@ -671,7 +671,7 @@ public class TrieTest { // Assert the result now Iterator keys = testerMap.keySet().iterator(); - while (keys.hasNext()){ + while (keys.hasNext()) { String mapWord1 = keys.next(); String mapWord2 = testerMap.get(mapWord1); @@ -684,7 +684,7 @@ public class TrieTest { // Assert the result now keys = testerMap.keySet().iterator(); - while (keys.hasNext()){ + while (keys.hasNext()) { String mapWord1 = keys.next(); String mapWord2 = testerMap.get(mapWord1); @@ -710,9 +710,9 @@ public class TrieTest { List roots = new ArrayList<>(); Map trieDumps = new HashMap<>(); - for (int i = 0; i < 100; ++i){ + for (int i = 0; i < 100; ++i) { - String[] keyVal= strData.get(i).split("="); + String[] keyVal = strData.get(i).split("="); if (keyVal[0].equals("*")) trieSingle.delete(keyVal[1].trim()); @@ -722,17 +722,17 @@ public class TrieTest { byte[] hash = trieSingle.getRootHash(); roots.add(hash); - String key = Hex.toHexString(hash); + String key = Hex.toHexString(hash); String dump = trieSingle.getTrieDump(); trieDumps.put(key, dump); } // compare all 100 rollback dumps and // the originaly saved dumps - for (int i = 1; i < roots.size(); ++i){ + for (int i = 1; i < roots.size(); ++i) { byte[] root = roots.get(i); - logger.info("rollback over root : {}", Hex.toHexString(root) ); + logger.info("rollback over root : {}", Hex.toHexString(root)); trieSingle.setRoot(root); String currDump = trieSingle.getTrieDump(); @@ -763,7 +763,7 @@ public class TrieTest { */ @Test - public void storageHashCalc_1(){ + public void storageHashCalc_1() { byte[] key1 = Hex.decode("0000000000000000000000000000000000000000000000000000000000000010"); byte[] key2 = Hex.decode("0000000000000000000000000000000000000000000000000000000000000014"); @@ -801,13 +801,13 @@ public class TrieTest { String testSrc = new String(testData); JSONParser parser = new JSONParser(); - JSONArray dbDumpJSONArray = (JSONArray)parser.parse(testSrc); + JSONArray dbDumpJSONArray = (JSONArray) parser.parse(testSrc); DatabaseImpl db = new DatabaseImpl("testState"); - for (int i = 0; i < dbDumpJSONArray.size(); ++i){ + for (int i = 0; i < dbDumpJSONArray.size(); ++i) { - JSONObject obj = (JSONObject)dbDumpJSONArray.get(i); + JSONObject obj = (JSONObject) dbDumpJSONArray.get(i); byte[] key = Hex.decode(obj.get("key").toString()); byte[] val = Hex.decode(obj.get("val").toString()); @@ -840,10 +840,9 @@ public class TrieTest { } - @Test // update the trie with blog key/val // each time dump the entire trie - public void testSample_1(){ + public void testSample_1() { TrieImpl trie = new TrieImpl(mockDb); diff --git a/ethereumj-core/src/test/java/test/ethereum/util/ByteUtilTest.java b/ethereumj-core/src/test/java/test/ethereum/util/ByteUtilTest.java index d756a5c9..f6796127 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/ByteUtilTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/ByteUtilTest.java @@ -54,8 +54,8 @@ public class ByteUtilTest { @Test public void testCalcPacketLength() { - byte[] test = new byte[] { 0x0f, 0x10, 0x43 }; - byte[] expected = new byte[] { 0x00, 0x00, 0x00, 0x03 }; + byte[] test = new byte[]{0x0f, 0x10, 0x43}; + byte[] expected = new byte[]{0x00, 0x00, 0x00, 0x03}; assertArrayEquals(expected, ByteUtil.calcPacketLength(test)); } @@ -96,9 +96,9 @@ public class ByteUtilTest { @Test public void testStripLeadingZeroes() { - byte[] test1 = new byte[] { 0x00, 0x01 }; - byte[] test2 = new byte[] { 0x00, 0x00, 0x01 }; - byte[] expected = new byte[] { 0x01 }; + byte[] test1 = new byte[]{0x00, 0x01}; + byte[] test2 = new byte[]{0x00, 0x00, 0x01}; + byte[] expected = new byte[]{0x01}; assertArrayEquals(expected, ByteUtil.stripLeadingZeroes(test1)); assertArrayEquals(expected, ByteUtil.stripLeadingZeroes(test2)); } @@ -106,16 +106,17 @@ public class ByteUtilTest { @Test public void testMatchingNibbleLength1() { // a larger than b - byte[] a = new byte[] { 0x00, 0x01 }; - byte[] b = new byte[] { 0x00 }; + byte[] a = new byte[]{0x00, 0x01}; + byte[] b = new byte[]{0x00}; int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(1, result); } + @Test public void testMatchingNibbleLength2() { // b larger than a - byte[] a = new byte[] { 0x00 }; - byte[] b = new byte[] { 0x00, 0x01 }; + byte[] a = new byte[]{0x00}; + byte[] b = new byte[]{0x00, 0x01}; int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(1, result); } @@ -123,8 +124,8 @@ public class ByteUtilTest { @Test public void testMatchingNibbleLength3() { // a and b the same length equal - byte[] a = new byte[] { 0x00 }; - byte[] b = new byte[] { 0x00 }; + byte[] a = new byte[]{0x00}; + byte[] b = new byte[]{0x00}; int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(1, result); } @@ -132,38 +133,38 @@ public class ByteUtilTest { @Test public void testMatchingNibbleLength4() { // a and b the same length not equal - byte[] a = new byte[] { 0x01 }; - byte[] b = new byte[] { 0x00 }; + byte[] a = new byte[]{0x01}; + byte[] b = new byte[]{0x00}; int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(0, result); } @Test - public void testNiceNiblesOutput_1(){ + public void testNiceNiblesOutput_1() { byte[] test = {7, 0, 7, 5, 7, 0, 7, 0, 7, 9}; String result = "\\x07\\x00\\x07\\x05\\x07\\x00\\x07\\x00\\x07\\x09"; assertEquals(result, ByteUtil.nibblesToPrettyString(test)); } @Test - public void testNiceNiblesOutput_2(){ + public void testNiceNiblesOutput_2() { byte[] test = {7, 0, 7, 0xf, 7, 0, 0xa, 0, 7, 9}; String result = "\\x07\\x00\\x07\\x0f\\x07\\x00\\x0a\\x00\\x07\\x09"; assertEquals(result, ByteUtil.nibblesToPrettyString(test)); } - @Test(expected=NullPointerException.class) + @Test(expected = NullPointerException.class) public void testMatchingNibbleLength5() { // a == null byte[] a = null; - byte[] b = new byte[] { 0x00 }; + byte[] b = new byte[]{0x00}; ByteUtil.matchingNibbleLength(a, b); } - @Test(expected=NullPointerException.class) + @Test(expected = NullPointerException.class) public void testMatchingNibbleLength6() { // b == null - byte[] a = new byte[] { 0x00 }; + byte[] a = new byte[]{0x00}; byte[] b = null; ByteUtil.matchingNibbleLength(a, b); } @@ -172,7 +173,7 @@ public class ByteUtilTest { public void testMatchingNibbleLength7() { // a or b is empty byte[] a = new byte[0]; - byte[] b = new byte[] { 0x00 }; + byte[] b = new byte[]{0x00}; int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(0, result); } @@ -188,12 +189,12 @@ public class ByteUtilTest { public void testIncrementPerformance() { boolean testEnabled = false; - if(testEnabled) { + if (testEnabled) { byte[] counter1 = new byte[4]; byte[] max = ByteBuffer.allocate(4).putInt(Integer.MAX_VALUE).array(); long start1 = System.currentTimeMillis(); - while(ByteUtil.increment(counter1)) { - if(FastByteComparisons.compareTo(counter1, 0, 4, max, 0, 4) == 0) { + while (ByteUtil.increment(counter1)) { + if (FastByteComparisons.compareTo(counter1, 0, 4, max, 0, 4) == 0) { break; } } @@ -201,8 +202,8 @@ public class ByteUtilTest { BigInteger counter2 = BigInteger.ZERO; long start2 = System.currentTimeMillis(); - while(true) { - if(counter2.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) == 0) { + while (true) { + if (counter2.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) == 0) { break; } counter2 = counter2.add(BigInteger.ONE); @@ -294,20 +295,20 @@ public class ByteUtilTest { ByteUtil.setBit(data, 2, 1); List found = new ArrayList(); - for(int i=0; i < (data.length * 8); i++) { + for (int i = 0; i < (data.length * 8); i++) { int res = ByteUtil.getBit(data, i); - if(res == 1) - if(i != 24 && i != 25 && i != 2) + if (res == 1) + if (i != 24 && i != 25 && i != 2) assertTrue(false); else found.add(i); else { - if(i == 24 || i == 25 || i == 2) + if (i == 24 || i == 25 || i == 2) assertTrue(false); } } - if(found.size() != 3) + if (found.size() != 3) assertTrue(false); assertTrue(found.get(0) == 2); assertTrue(found.get(1) == 24); diff --git a/ethereumj-core/src/test/java/test/ethereum/util/CompactEncoderTest.java b/ethereumj-core/src/test/java/test/ethereum/util/CompactEncoderTest.java index 307924f6..24043bff 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/CompactEncoderTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/CompactEncoderTest.java @@ -11,78 +11,78 @@ public class CompactEncoderTest { @Test public void testCompactEncodeOddCompact() { - byte[] test = new byte[] { 1, 2, 3, 4, 5 }; - byte[] expectedData = new byte[] { 0x11, 0x23, 0x45 }; + byte[] test = new byte[]{1, 2, 3, 4, 5}; + byte[] expectedData = new byte[]{0x11, 0x23, 0x45}; assertArrayEquals("odd compact encode fail", expectedData, CompactEncoder.packNibbles(test)); } @Test public void testCompactEncodeEvenCompact() { - byte[] test = new byte[] { 0, 1, 2, 3, 4, 5 }; - byte[] expectedData = new byte[] { 0x00, 0x01, 0x23, 0x45 }; + byte[] test = new byte[]{0, 1, 2, 3, 4, 5}; + byte[] expectedData = new byte[]{0x00, 0x01, 0x23, 0x45}; assertArrayEquals("even compact encode fail", expectedData, CompactEncoder.packNibbles(test)); } @Test public void testCompactEncodeEvenTerminated() { - byte[] test = new byte[] { 0, 15, 1, 12, 11, 8, T }; - byte[] expectedData = new byte[] { 0x20, 0x0f, 0x1c, (byte) 0xb8 }; + byte[] test = new byte[]{0, 15, 1, 12, 11, 8, T}; + byte[] expectedData = new byte[]{0x20, 0x0f, 0x1c, (byte) 0xb8}; assertArrayEquals("even terminated compact encode fail", expectedData, CompactEncoder.packNibbles(test)); } @Test public void testCompactEncodeOddTerminated() { - byte[] test = new byte[] { 15, 1, 12, 11, 8, T }; - byte[] expectedData = new byte[] { 0x3f, 0x1c, (byte) 0xb8 }; + byte[] test = new byte[]{15, 1, 12, 11, 8, T}; + byte[] expectedData = new byte[]{0x3f, 0x1c, (byte) 0xb8}; assertArrayEquals("odd terminated compact encode fail", expectedData, CompactEncoder.packNibbles(test)); } @Test public void testCompactDecodeOddCompact() { - byte[] test = new byte[] { 0x11, 0x23, 0x45 }; - byte[] expected = new byte[] {1, 2, 3, 4, 5}; + byte[] test = new byte[]{0x11, 0x23, 0x45}; + byte[] expected = new byte[]{1, 2, 3, 4, 5}; assertArrayEquals("odd compact decode fail", expected, CompactEncoder.unpackToNibbles(test)); } @Test public void testCompactDecodeEvenCompact() { - byte[] test = new byte[] { 0x00, 0x01, 0x23, 0x45 }; - byte[] expected = new byte[] {0, 1, 2, 3, 4, 5}; + byte[] test = new byte[]{0x00, 0x01, 0x23, 0x45}; + byte[] expected = new byte[]{0, 1, 2, 3, 4, 5}; assertArrayEquals("even compact decode fail", expected, CompactEncoder.unpackToNibbles(test)); } @Test public void testCompactDecodeEvenTerminated() { - byte[] test = new byte[] { 0x20, 0x0f, 0x1c, (byte) 0xb8 }; - byte[] expected = new byte[] {0, 15, 1, 12, 11, 8, T}; + byte[] test = new byte[]{0x20, 0x0f, 0x1c, (byte) 0xb8}; + byte[] expected = new byte[]{0, 15, 1, 12, 11, 8, T}; assertArrayEquals("even terminated compact decode fail", expected, CompactEncoder.unpackToNibbles(test)); } @Test public void testCompactDecodeOddTerminated() { - byte[] test = new byte[] { 0x3f, 0x1c, (byte) 0xb8 }; - byte[] expected = new byte[] {15, 1, 12, 11, 8, T}; + byte[] test = new byte[]{0x3f, 0x1c, (byte) 0xb8}; + byte[] expected = new byte[]{15, 1, 12, 11, 8, T}; assertArrayEquals("odd terminated compact decode fail", expected, CompactEncoder.unpackToNibbles(test)); } @Test public void testCompactHexEncode_1() { byte[] test = "stallion".getBytes(); - byte[] result = new byte[] { 7, 3, 7, 4, 6, 1, 6, 12, 6, 12, 6, 9, 6, 15, 6, 14, T }; + byte[] result = new byte[]{7, 3, 7, 4, 6, 1, 6, 12, 6, 12, 6, 9, 6, 15, 6, 14, T}; assertArrayEquals(result, CompactEncoder.binToNibbles(test)); } @Test public void testCompactHexEncode_2() { byte[] test = "verb".getBytes(); - byte[] result = new byte[] { 7, 6, 6, 5, 7, 2, 6, 2, T }; + byte[] result = new byte[]{7, 6, 6, 5, 7, 2, 6, 2, T}; assertArrayEquals(result, CompactEncoder.binToNibbles(test)); } @Test public void testCompactHexEncode_3() { byte[] test = "puppy".getBytes(); - byte[] result = new byte[] { 7, 0, 7, 5, 7, 0, 7, 0, 7, 9, T }; + byte[] result = new byte[]{7, 0, 7, 5, 7, 0, 7, 0, 7, 9, T}; assertArrayEquals(result, CompactEncoder.binToNibbles(test)); } } diff --git a/ethereumj-core/src/test/java/test/ethereum/util/RLPTest.java b/ethereumj-core/src/test/java/test/ethereum/util/RLPTest.java index c96cdd2d..21d5ebf3 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/RLPTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/RLPTest.java @@ -41,7 +41,7 @@ public class RLPTest { byte[] ip = RLP.decodeIP4Bytes(payload, 5); - assertEquals(InetAddress.getByAddress(ip).toString(),("/54.204.10.41")); + assertEquals(InetAddress.getByAddress(ip).toString(), ("/54.204.10.41")); } @Test @@ -55,7 +55,7 @@ public class RLPTest { "17 08 9F EA F8 4C 21 B0"; byte[] payload = Hex.decode(peersPacket); - int oneInt = RLP.decodeInt(payload, 11); + int oneInt = RLP.decodeInt(payload, 11); assertEquals(oneInt, 30303); } @@ -82,11 +82,11 @@ public class RLPTest { assertEquals("/54.204.10.41", InetAddress.getByAddress(ip).toString()); nextIndex = RLP.getNextElementIndex(payload, nextIndex); - int port = RLP.decodeInt(payload, nextIndex); + int port = RLP.decodeInt(payload, nextIndex); assertEquals(30303, port); nextIndex = RLP.getNextElementIndex(payload, nextIndex); - BigInteger peerId = RLP.decodeBigInteger(payload, nextIndex); + BigInteger peerId = RLP.decodeBigInteger(payload, nextIndex); BigInteger expectedPeerId = new BigInteger("9650128800487972697726795438087510101805200020100629942070155319087371611597658887860952245483247188023303607186148645071838189546969115967896446355306572"); @@ -98,99 +98,103 @@ public class RLPTest { assertEquals("/54.2.10.41", InetAddress.getByAddress(ip).toString()); nextIndex = RLP.getNextElementIndex(payload, nextIndex); - port = RLP.decodeInt(payload, nextIndex); + port = RLP.decodeInt(payload, nextIndex); assertEquals(30303, port); nextIndex = RLP.getNextElementIndex(payload, nextIndex); - peerId = RLP.decodeBigInteger(payload, nextIndex); + peerId = RLP.decodeBigInteger(payload, nextIndex); expectedPeerId = new BigInteger("9650128800487972697726795438087510101805200020100629942070155319087371611597658887860952245483247188023303607186148645071838189546969115967896446355306572"); - assertEquals(expectedPeerId ,peerId); + assertEquals(expectedPeerId, peerId); nextIndex = RLP.getNextElementIndex(payload, nextIndex); nextIndex = RLP.getFirstListElement(payload, nextIndex); assertEquals(-1, nextIndex); } - @Test /** encode byte */ + @Test + /** encode byte */ public void test4() { - byte[] expected = {(byte)0x80}; - byte[] data = RLP.encodeByte((byte)0); + byte[] expected = {(byte) 0x80}; + byte[] data = RLP.encodeByte((byte) 0); assertArrayEquals(expected, data); - byte[] expected2 = {(byte)0x78}; - data = RLP.encodeByte((byte)120); + byte[] expected2 = {(byte) 0x78}; + data = RLP.encodeByte((byte) 120); assertArrayEquals(expected2, data); - byte[] expected3 = {(byte)0x81, (byte)0x7F}; - data = RLP.encodeByte((byte)127); + byte[] expected3 = {(byte) 0x81, (byte) 0x7F}; + data = RLP.encodeByte((byte) 127); assertArrayEquals(expected3, data); } - @Test /** encode short */ + @Test + /** encode short */ public void test5() { - byte[] expected = {(byte)0x80}; + byte[] expected = {(byte) 0x80}; byte[] data = RLP.encodeShort((byte) 0); assertArrayEquals(expected, data); - byte[] expected2 = {(byte)0x78}; + byte[] expected2 = {(byte) 0x78}; data = RLP.encodeShort((byte) 120); assertArrayEquals(expected2, data); - byte[] expected3 = {(byte)0x81, (byte)0x7F}; + byte[] expected3 = {(byte) 0x81, (byte) 0x7F}; data = RLP.encodeShort((byte) 127); assertArrayEquals(expected3, data); - byte[] expected4 = {(byte)0x82, (byte)0x76, (byte)0x5F}; - data = RLP.encodeShort((short)30303); + byte[] expected4 = {(byte) 0x82, (byte) 0x76, (byte) 0x5F}; + data = RLP.encodeShort((short) 30303); assertArrayEquals(expected4, data); - byte[] expected5 = {(byte)0x82, (byte)0x4E, (byte)0xEA}; - data = RLP.encodeShort((short)20202); + byte[] expected5 = {(byte) 0x82, (byte) 0x4E, (byte) 0xEA}; + data = RLP.encodeShort((short) 20202); assertArrayEquals(expected5, data); } - @Test /** encode int */ + @Test + /** encode int */ public void testEncodeInt() { - byte[] expected = {(byte)0x80}; + byte[] expected = {(byte) 0x80}; byte[] data = RLP.encodeInt(0); assertArrayEquals(expected, data); - byte[] expected2 = {(byte)0x78}; + byte[] expected2 = {(byte) 0x78}; data = RLP.encodeInt(120); assertArrayEquals(expected2, data); - byte[] expected3 = {(byte)0x81, (byte)0x7F}; + byte[] expected3 = {(byte) 0x81, (byte) 0x7F}; data = RLP.encodeInt(127); assertArrayEquals(expected3, data); - byte[] expected4 = {(byte)0x82, (byte)0x76, (byte)0x5F}; + byte[] expected4 = {(byte) 0x82, (byte) 0x76, (byte) 0x5F}; data = RLP.encodeInt(30303); assertArrayEquals(expected4, data); - byte[] expected5 = {(byte)0x82, (byte)0x4E, (byte)0xEA}; + byte[] expected5 = {(byte) 0x82, (byte) 0x4E, (byte) 0xEA}; data = RLP.encodeInt(20202); assertArrayEquals(expected5, data); - byte[] expected6 = {(byte)0x83, 1, 0, 0}; + byte[] expected6 = {(byte) 0x83, 1, 0, 0}; data = RLP.encodeInt(65536); assertArrayEquals(expected6, data); - byte[] expected7 = {(byte)0x80}; + byte[] expected7 = {(byte) 0x80}; data = RLP.encodeInt(Integer.MIN_VALUE); assertArrayEquals(expected7, data); - byte[] expected8 = {(byte)0x84, (byte)0x7F, (byte)0xFF, (byte)0xFF, (byte)0xFF}; + byte[] expected8 = {(byte) 0x84, (byte) 0x7F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF}; data = RLP.encodeInt(Integer.MAX_VALUE); assertArrayEquals(expected8, data); } - @Test /** encode BigInteger */ + @Test + /** encode BigInteger */ public void test6() { byte[] expected = new byte[]{(byte) 0x80}; @@ -198,15 +202,16 @@ public class RLPTest { assertArrayEquals(expected, data); } - @Test /** encode string */ + @Test + /** encode string */ public void test7() { byte[] data = RLP.encodeString(""); - assertArrayEquals(new byte[]{(byte)0x80}, data); + assertArrayEquals(new byte[]{(byte) 0x80}, data); - byte[] expected = { (byte)0x90, (byte)0x45, (byte)0x74, (byte)0x68, (byte)0x65, (byte)0x72, (byte)0x65, - (byte)0x75, (byte)0x6D, (byte)0x4A, (byte)0x20, (byte)0x43, (byte)0x6C, - (byte)0x69, (byte)0x65, (byte)0x6E, (byte)0x74}; + byte[] expected = {(byte) 0x90, (byte) 0x45, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x72, (byte) 0x65, + (byte) 0x75, (byte) 0x6D, (byte) 0x4A, (byte) 0x20, (byte) 0x43, (byte) 0x6C, + (byte) 0x69, (byte) 0x65, (byte) 0x6E, (byte) 0x74}; String test = "EthereumJ Client"; data = RLP.encodeString(test); @@ -215,41 +220,42 @@ public class RLPTest { String test2 = "Ethereum(++)/ZeroGox/v0.5.0/ncurses/Linux/g++"; - byte[] expected2 = { (byte)0xAD, (byte)0x45, (byte)0x74, (byte)0x68, (byte)0x65, (byte)0x72, (byte)0x65, - (byte)0x75, (byte)0x6D, (byte)0x28, (byte)0x2B, (byte)0x2B, (byte)0x29, (byte)0x2F, - (byte)0x5A, (byte)0x65, (byte)0x72, (byte)0x6F, (byte)0x47, (byte)0x6F, (byte)0x78, - (byte)0x2F, (byte)0x76, (byte)0x30, (byte)0x2E, (byte)0x35, (byte)0x2E, (byte)0x30, - (byte)0x2F, (byte)0x6E, (byte)0x63, (byte)0x75, (byte)0x72, (byte)0x73, (byte)0x65, - (byte)0x73, (byte)0x2F, (byte)0x4C, (byte)0x69, (byte)0x6E, (byte)0x75, (byte)0x78, - (byte)0x2F, (byte)0x67, (byte)0x2B, (byte)0x2B}; + byte[] expected2 = {(byte) 0xAD, (byte) 0x45, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x72, (byte) 0x65, + (byte) 0x75, (byte) 0x6D, (byte) 0x28, (byte) 0x2B, (byte) 0x2B, (byte) 0x29, (byte) 0x2F, + (byte) 0x5A, (byte) 0x65, (byte) 0x72, (byte) 0x6F, (byte) 0x47, (byte) 0x6F, (byte) 0x78, + (byte) 0x2F, (byte) 0x76, (byte) 0x30, (byte) 0x2E, (byte) 0x35, (byte) 0x2E, (byte) 0x30, + (byte) 0x2F, (byte) 0x6E, (byte) 0x63, (byte) 0x75, (byte) 0x72, (byte) 0x73, (byte) 0x65, + (byte) 0x73, (byte) 0x2F, (byte) 0x4C, (byte) 0x69, (byte) 0x6E, (byte) 0x75, (byte) 0x78, + (byte) 0x2F, (byte) 0x67, (byte) 0x2B, (byte) 0x2B}; data = RLP.encodeString(test2); assertArrayEquals(expected2, data); String test3 = "Ethereum(++)/ZeroGox/v0.5.0/ncurses/Linux/g++Ethereum(++)/ZeroGox/v0.5.0/ncurses/Linux/g++"; - byte[] expected3 = {(byte)0xB8, (byte)0x5A, - (byte)0x45, (byte)0x74, (byte)0x68, (byte)0x65, (byte)0x72, (byte)0x65, - (byte)0x75, (byte)0x6D, (byte)0x28, (byte)0x2B, (byte)0x2B, (byte)0x29, (byte)0x2F, - (byte)0x5A, (byte)0x65, (byte)0x72, (byte)0x6F, (byte)0x47, (byte)0x6F, (byte)0x78, - (byte)0x2F, (byte)0x76, (byte)0x30, (byte)0x2E, (byte)0x35, (byte)0x2E, (byte)0x30, - (byte)0x2F, (byte)0x6E, (byte)0x63, (byte)0x75, (byte)0x72, (byte)0x73, (byte)0x65, - (byte)0x73, (byte)0x2F, (byte)0x4C, (byte)0x69, (byte)0x6E, (byte)0x75, (byte)0x78, - (byte)0x2F, (byte)0x67, (byte)0x2B, (byte)0x2B, + byte[] expected3 = {(byte) 0xB8, (byte) 0x5A, + (byte) 0x45, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x72, (byte) 0x65, + (byte) 0x75, (byte) 0x6D, (byte) 0x28, (byte) 0x2B, (byte) 0x2B, (byte) 0x29, (byte) 0x2F, + (byte) 0x5A, (byte) 0x65, (byte) 0x72, (byte) 0x6F, (byte) 0x47, (byte) 0x6F, (byte) 0x78, + (byte) 0x2F, (byte) 0x76, (byte) 0x30, (byte) 0x2E, (byte) 0x35, (byte) 0x2E, (byte) 0x30, + (byte) 0x2F, (byte) 0x6E, (byte) 0x63, (byte) 0x75, (byte) 0x72, (byte) 0x73, (byte) 0x65, + (byte) 0x73, (byte) 0x2F, (byte) 0x4C, (byte) 0x69, (byte) 0x6E, (byte) 0x75, (byte) 0x78, + (byte) 0x2F, (byte) 0x67, (byte) 0x2B, (byte) 0x2B, - (byte)0x45, (byte)0x74, (byte)0x68, (byte)0x65, (byte)0x72, (byte)0x65, - (byte)0x75, (byte)0x6D, (byte)0x28, (byte)0x2B, (byte)0x2B, (byte)0x29, (byte)0x2F, - (byte)0x5A, (byte)0x65, (byte)0x72, (byte)0x6F, (byte)0x47, (byte)0x6F, (byte)0x78, - (byte)0x2F, (byte)0x76, (byte)0x30, (byte)0x2E, (byte)0x35, (byte)0x2E, (byte)0x30, - (byte)0x2F, (byte)0x6E, (byte)0x63, (byte)0x75, (byte)0x72, (byte)0x73, (byte)0x65, - (byte)0x73, (byte)0x2F, (byte)0x4C, (byte)0x69, (byte)0x6E, (byte)0x75, (byte)0x78, - (byte)0x2F, (byte)0x67, (byte)0x2B, (byte)0x2B}; + (byte) 0x45, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x72, (byte) 0x65, + (byte) 0x75, (byte) 0x6D, (byte) 0x28, (byte) 0x2B, (byte) 0x2B, (byte) 0x29, (byte) 0x2F, + (byte) 0x5A, (byte) 0x65, (byte) 0x72, (byte) 0x6F, (byte) 0x47, (byte) 0x6F, (byte) 0x78, + (byte) 0x2F, (byte) 0x76, (byte) 0x30, (byte) 0x2E, (byte) 0x35, (byte) 0x2E, (byte) 0x30, + (byte) 0x2F, (byte) 0x6E, (byte) 0x63, (byte) 0x75, (byte) 0x72, (byte) 0x73, (byte) 0x65, + (byte) 0x73, (byte) 0x2F, (byte) 0x4C, (byte) 0x69, (byte) 0x6E, (byte) 0x75, (byte) 0x78, + (byte) 0x2F, (byte) 0x67, (byte) 0x2B, (byte) 0x2B}; data = RLP.encodeString(test3); assertArrayEquals(expected3, data); } - @Test /** encode byte array */ + @Test + /** encode byte array */ public void test8() { String byteArr = "ce73660a06626c1b3fda7b18ef7ba3ce17b6bf604f9541d3c6c654b7ae88b239" @@ -262,48 +268,56 @@ public class RLPTest { assertEquals(expected, Hex.toHexString(RLP.encodeElement(byteArray))); } - @Test /** encode list */ + @Test + /** encode list */ public void test9() { byte[] actuals = RLP.encodeList(); - assertArrayEquals(new byte[] { (byte) 0xc0 }, actuals); + assertArrayEquals(new byte[]{(byte) 0xc0}, actuals); } - @Test /** encode null value */ + @Test + /** encode null value */ public void testEncodeElementNull() { byte[] actuals = RLP.encodeElement(null); - assertArrayEquals(new byte[] { (byte) 0x80 }, actuals); + assertArrayEquals(new byte[]{(byte) 0x80}, actuals); } - @Test /** encode single byte 0x00 */ + @Test + /** encode single byte 0x00 */ public void testEncodeElementZero() { - byte[] actuals = RLP.encodeElement(new byte[] {0x00}); - assertArrayEquals(new byte[] { (byte) 0x00 }, actuals); + byte[] actuals = RLP.encodeElement(new byte[]{0x00}); + assertArrayEquals(new byte[]{(byte) 0x00}, actuals); } - @Test /** encode single byte 0x01 */ + @Test + /** encode single byte 0x01 */ public void testEncodeElementOne() { - byte[] actuals = RLP.encodeElement(new byte[] {0x00}); - assertArrayEquals(new byte[] { (byte) 0x00 }, actuals); + byte[] actuals = RLP.encodeElement(new byte[]{0x00}); + assertArrayEquals(new byte[]{(byte) 0x00}, actuals); } - @Test /** found bug encode list affects element value, - hhh... not really at the end but keep the test */ + @Test + /** found bug encode list affects element value, + hhh... not really at the end but keep the test */ public void test10() { - /* 2 */ byte[] prevHash = + /* 2 */ + byte[] prevHash = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; prevHash = RLP.encodeElement(prevHash); - /* 2 */ byte[] uncleList = HashUtil.sha3(RLP.encodeList(new byte[]{})); + /* 2 */ + byte[] uncleList = HashUtil.sha3(RLP.encodeList(new byte[]{})); - /* 3 */ byte[] coinbase = + /* 3 */ + byte[] coinbase = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; @@ -343,7 +357,166 @@ public class RLPTest { @Test /* very long peers msg */ public void test13() { - String peers= "f9 14 90 11 f8 4c c6 81 83 68 81 fc 04 82 76 5f b8 40 07 7e 53 7a 8b 36 73 e8 f1 b6 25 db cc 90 2e a7 d4 ce d9 40 2e 46 64 e8 73 67 95 12 cc 23 60 69 8e 53 42 56 52 a0 46 24 fc f7 8c db a1 a3 23 30 87 a9 19 a3 4d 11 ae da ce ee b7 d8 33 fc bf 26 f8 4c c6 63 81 e7 58 81 af 82 76 5f b8 40 0a b2 cd e8 3a 09 84 03 dd c2 ea 54 14 74 0d 8a 01 93 e4 49 c9 6e 11 24 19 96 7a bc 62 eb 17 cd ce d7 7a e0 ab 07 5e 04 f7 dd dc d4 3f b9 04 8b e5 32 06 a0 40 62 0b de 26 cb 74 3f a3 12 31 9f f8 4d c7 81 cf 81 db 45 81 9a 82 76 5f b8 40 19 c3 3d a7 03 1c ff 17 7e fa 84 2f aa 3d 31 bd 83 e1 76 4e c6 10 f2 36 94 4a 9f 8a 21 c1 c5 1a 04 f4 7f 6b 5f c3 ef e6 5c af 36 94 43 63 5a fc 58 d8 f5 d4 e2 f1 2a f9 ee ec 3c 6e 30 bf 0a 2b f8 4c c6 44 30 81 ad 81 a3 82 76 5f b8 40 1e 59 c2 82 08 12 94 80 84 97 ae 7a 7e 97 67 98 c4 2b 8b cc e1 3c 9d 8b 0e cf 8a fe cd b5 df d4 ef a8 77 0f c0 d1 f7 de 63 c9 16 40 e7 e8 b4 35 8c 9e 3e d0 f3 d6 c9 86 20 ad 7e a4 24 18 c9 ec f8 4b c5 1f 12 81 9e 48 82 76 5f b8 40 1f 68 c0 75 c1 d8 7b c0 47 65 43 0f df b1 e5 d0 0f 1b 78 4e d6 be 72 1e 4c af f7 be b5 7b 4b 21 7b 95 da 19 b5 ec 66 04 58 68 b3 9a ac 2e 08 76 cf 80 f0 b6 8d 0f a2 0b db 90 36 be aa 70 61 ea f8 4c c6 81 bf 81 ea 39 37 82 76 5f b8 40 21 78 0c 55 b4 7d b4 b1 14 67 b5 f5 5b 0b 55 5e 08 87 ce 36 fb d9 75 e2 24 b1 c7 0e ac 7a b8 e8 c2 db 37 f0 a4 8b 90 ff dd 5a 37 9a da 99 b6 a0 f6 42 9c 4a 53 c2 55 58 19 1a 68 26 36 ae f4 f2 f8 4c c6 44 30 81 ad 81 a3 82 76 5f b8 40 23 15 cb 7c f4 9b 8e ab 21 2c 5a 45 79 0b 50 79 77 39 73 8f 5f 73 34 39 b1 90 11 97 37 ee 8c 09 bc 72 37 94 71 2a a8 2f 26 70 bc 58 1a b0 75 7e f2 31 37 ac 0f df 0f 8c 89 65 e7 dd 6b a7 9f 8c f8 4e c8 81 bf 81 b1 81 d1 81 9f 82 76 5f b8 40 24 9a 36 41 e5 a8 d0 8e 41 a5 cf c8 da e1 1f 17 61 25 4f 4f d4 7d 9b 13 33 8d b8 e6 e3 72 9e 6f 2a c9 ec 09 7a 5c 80 96 84 d6 2a 41 e6 df c2 ff f7 2d c3 db d9 7e a2 61 32 bb 97 64 05 65 bb 0c f8 4a c4 55 41 7e 2d 82 76 5f b8 40 2a 38 ea 5d 9a 7e fd 7f ff c0 a8 1d 8e a7 ed 28 31 1c 40 12 bb ab 14 07 c8 da d2 68 51 29 e0 42 17 27 34 a3 28 e8 90 7f 90 54 b8 22 5f e7 70 41 d8 a4 86 a9 79 76 d2 83 72 42 ab 6c 8c 59 05 e4 f8 4c c6 81 83 68 81 fc 04 82 76 5f b8 40 32 4d d9 36 38 4d 8c 0d de fd e0 4b a7 40 29 98 ab bd 63 d7 9c 0b f8 58 6b 3d d2 c7 db f6 c9 1e b8 0a 7b 6d e8 f1 6a 50 04 4f 14 9c 7b 39 aa fb 9c 3a d7 f2 ca a4 03 55 aa b0 98 88 18 6f cc a2 f8 4c c6 44 30 81 ad 81 a3 82 76 5f b8 40 39 42 45 c0 99 16 33 ed 06 0b af b9 64 68 53 d3 44 18 8b 80 4f e3 7e 25 a5 bc ac 44 ed 44 3a 84 a6 8b 3a af 15 5e fe 48 61 e8 4b 4b 51 5f 9a 5d ec db d7 da e9 81 92 d7 a3 20 a7 92 c7 d4 df af f8 4d c7 56 81 b7 81 e7 81 cd 82 76 5f b8 40 39 86 50 f6 7b 22 92 93 9d e3 4c 0e ae b9 14 1f 94 84 a0 fb 17 3f a3 3f 81 a1 f7 31 5d 0e b7 7b de 3a 76 c3 86 36 fa e6 6f a1 4b f2 af df d6 3e 60 ab d4 0e 29 b0 2a 91 4e 65 de 57 89 98 3f d4 f8 4c c6 44 81 b9 81 ea 40 82 76 5f b8 40 3a 15 58 7a 1c 3a da bf 02 91 b3 07 f7 1b 2c 04 d1 98 aa e3 6b 83 49 95 d3 30 5d ff 42 f1 ab 86 f4 83 ae 12 9e 92 03 fb c6 ef 21 87 c8 62 1e dd 18 f6 1d 53 ea a5 b5 87 ff de a4 d9 26 48 90 38 f8 4d c7 81 cf 81 db 45 81 9a 82 76 5f b8 40 3b 14 62 04 0e a7 78 e3 f7 5e 65 ce 24 53 41 8a 66 2e 62 12 c9 f6 5b 02 ea b5 8d 22 b2 87 e4 50 53 bd e5 eb f0 60 96 0c bf a0 d9 dc 85 bf 51 ba 7a a1 f2 ca a2 c1 36 82 d9 32 77 64 1d 60 db eb f8 4c c6 6a 81 a8 0e 81 f9 82 76 5f b8 40 3e cc 97 ab 15 d2 2f 7b 9e df 19 c0 4c e3 b6 09 5f a2 50 42 14 00 2b 35 98 9c 6f 81 ee 4b 96 1c c2 a8 99 c4 94 15 c9 14 e3 13 90 83 40 04 7d 1d 3b 25 d7 4f 5b 9c 85 a0 6a fa 26 59 a5 39 99 2e f8 4b c5 2e 04 81 c1 09 82 76 5f b8 40 40 7c 22 00 3f 3b ba a6 cb eb 8e 4b 0a b7 07 30 73 fe ab 85 18 2b 40 55 25 f8 bd 28 32 55 04 3d 71 35 18 f7 47 48 d9 2c 43 fb b9 9e cc 7c 3f ba b9 5d 59 80 06 51 3a a8 e5 9c 48 04 1c 8b 41 c2 f8 4b c5 32 7e 56 81 c2 82 76 5f b8 40 40 8c 93 24 20 3b d8 26 2f ce 65 06 ba 59 dc dd 56 70 89 b0 eb 9a 5b b1 83 47 7b ab bf 61 63 91 4a cd c7 f4 95 f8 96 4d 8a c1 2f e2 40 18 87 b8 cd 8d 97 c0 c9 dc cf ad db b2 0a 3c 31 47 a7 89 f8 4a c4 26 6c 4f 68 82 76 5f b8 40 42 3e 40 04 da 2f a7 50 0b c0 12 c0 67 4a a6 57 15 02 c5 3a a4 d9 1e fa 6e 2b 5c b1 e4 68 c4 62 ca 31 14 a2 e2 eb 09 65 b7 04 4f 9c 95 75 96 5b 47 e4 7a 41 f1 3f 1a dc 03 a2 a4 b3 42 d7 12 8d f8 4b c5 40 81 e7 08 2d 82 76 5f b8 40 42 83 93 75 27 2c 2f 3d ea db 28 08 5d 06 05 5e 35 31 35 c6 c8 d8 96 09 7a 1b c4 80 c4 88 4f d1 60 45 18 cb df 73 1a c1 8f 09 84 b7 f0 21 48 e8 82 90 d1 3c 22 4d 82 46 43 14 e2 b5 96 2e 3f 89 f8 4d c7 32 81 aa 81 d8 81 c8 82 76 5f b8 40 44 cf 19 44 6c a4 65 01 8e 4d e6 c6 0f c0 df 52 9e ba 25 02 92 ef 74 41 e1 db 59 84 1c 69 f0 22 f6 09 28 10 c9 a5 a7 f2 74 f2 f9 7c 4b d6 c7 6e ad c0 64 c7 d6 59 7c ae b1 7e d8 7c b2 57 73 5f f8 4b c5 32 81 9c 5a 53 82 76 5f b8 40 46 1c 9b 54 e9 19 53 c5 bb c3 1c 67 12 a9 17 38 2b e6 7d 60 f7 5e b7 f5 06 51 be a3 e5 94 d0 d1 9c 22 29 d8 f6 6a db 3f 20 3f 60 00 38 e7 cc 93 4d c9 27 87 fa c4 39 2b 9b fa 7c bc 78 6f d0 5b f8 4b c5 81 86 64 7d 29 82 76 5f b8 40 48 35 3a 00 58 e2 64 48 d9 4e 59 33 6c ca 9d 28 a9 37 41 20 de f7 6c 4b cc fe e1 8b 01 23 e5 91 92 39 3a 2e e3 04 4d 80 e0 ee cb b0 94 76 be 62 fd e1 e8 74 f9 3d 05 ea 5c 4a 9a 45 c0 6e 8f e1 f8 4b c5 4e 08 05 81 bb 82 76 5f b8 40 48 e8 95 09 49 d4 c0 0b cd bb e9 39 c5 bf 07 8f 2c bf f1 08 84 af 16 60 b1 c3 22 b9 ca a3 ba 35 7b b4 15 7f c6 b0 03 9a f9 43 8d fe 51 ec 27 8a 47 fc d3 b7 26 fa 0a 08 7d 4c 3c 01 a6 2f 33 5e f8 4a c6 58 45 81 c6 81 c6 07 b8 40 4a 02 55 fa 46 73 fa a3 0f c5 ab fd 3c 55 0b fd bc 0d 3c 97 3d 35 f7 26 46 3a f8 1c 54 a0 32 81 cf ff 22 c5 f5 96 5b 38 ac 63 01 52 98 77 57 a3 17 82 47 85 49 c3 6f 7c 84 cb 44 36 ba 79 d6 d9 f8 4b c5 40 81 e7 08 2d 82 76 5f b8 40 4c 75 47 ab 4d 54 1e 10 16 4c d3 74 1f 34 76 ed 19 4b 0a b9 a1 36 df ca c3 94 3f 97 35 8c 9b 05 14 14 27 36 ca 2f 17 0f 12 52 29 05 7b 47 32 44 a6 23 0b f5 47 1a d1 68 18 85 24 b2 b5 cd 8b 7b f8 4c c6 44 30 81 ad 81 a3 82 76 5f b8 40 4d 5e 48 75 d6 0e b4 ee af b6 b2 a7 d3 93 6e d3 c9 bc 58 ac aa de 6a 7f 3c 5f 25 59 8c 20 b3 64 f1 2b ea 2f b1 db 3b 2c 2e f6 47 85 a4 7d 6b 6b 5b 10 34 27 cb ac 0c 88 b1 8f e9 2a 9f 53 93 f8 f8 4b c5 52 0c 81 e3 54 82 76 5f b8 40 4f d8 98 62 75 74 d3 e8 6b 3f 5a 65 c3 ed c2 e5 da 84 53 59 26 e4 a2 88 20 b0 03 8b 19 63 6e 07 db 5e b0 04 d7 91 f8 04 1a 00 6e 33 e1 08 e4 ec 53 54 99 d1 28 d8 d9 c5 ca f6 bb dc 22 04 f7 6a f8 4b c5 81 b4 20 2b 08 82 76 5f b8 40 53 cc f2 5a b5 94 09 ec bb 90 3d 2e c3 a9 aa 2e b3 9d 7c c4 c7 db 7e 6f 68 fd 71 1a 7c eb c6 06 21 6d e7 37 82 6d a4 20 93 e3 e6 52 1e e4 77 0e b2 d6 69 dc 4b f3 54 6c c7 57 c3 40 12 69 6e ae f8 4c c6 6a 81 a8 0e 81 f9 82 76 5f b8 40 54 b3 93 15 69 91 39 87 80 50 2f a8 f4 14 13 79 bc e2 69 31 be 87 ba 8e 0b 74 9b a9 05 a9 e9 76 e5 de 6d 39 c9 8c f0 48 f2 5c 3c bb b8 c7 f3 02 c4 e6 04 ad 5b f7 2c db 06 10 0f 50 0d e3 a6 86 f8 4a c4 4c 67 37 47 82 76 5f b8 40 60 0a 77 fb 14 e7 92 c0 c7 0d c4 ad e3 82 ed 60 43 62 b9 78 b1 9b 94 c4 ed 18 83 38 a1 79 5d 2d b4 5f 7f 22 3b 66 ba eb a3 91 c5 9b 55 88 b4 4e ba f7 1c 7e b3 97 55 c2 72 29 c7 fd e6 41 be ce f8 4b c5 6d 2b 81 9a 42 82 76 5f b8 40 69 dd 44 5f 67 c3 be f3 94 f9 54 9f da e1 62 3d bc 20 88 4a 62 fd 56 16 dd bb 49 f8 4b a8 7e 14 7c b8 a5 0b a9 71 d7 30 c4 62 1d 0e b6 51 33 49 4e 94 fa 5e a2 e6 9c 66 1f 6b 12 e7 ed 2a 8d 4e f8 4b c5 18 09 3d 81 9b 82 76 5f b8 40 6b 5d 4c 35 ff d1 f5 a1 98 03 8a 90 83 4d 29 a1 b8 8b e0 d5 ef ca 08 bc 8a 2d 58 81 18 0b 0b 41 6b e0 06 29 aa be 45 0a 50 82 8b 8d 1e e8 2d 98 f5 52 81 87 ee 67 ed 6e 07 3b ce ef cd fb 2b c9 f8 4a c4 55 41 7e 2d 82 76 5f b8 40 6c bb 1e d5 36 dc 38 58 c1 f0 63 42 9b d3 95 2a 5d 32 ef 8e 11 52 6c df e7 2f 41 fe a1 ac e9 60 18 7c 99 75 ab bc 23 78 35 11 c0 0f 26 98 35 47 47 f9 05 aa ac 11 dc d2 b7 47 8b 3e af 32 7a c6 f8 4b c5 40 81 e7 08 2d 82 76 5f b8 40 6e a2 8f 64 ea 1c c3 b6 57 25 44 fd 5b f7 43 b0 ea ab e0 17 f5 14 73 0c 89 7d a3 c7 7f 03 c5 16 f1 e5 f3 1d 79 3b 4b ce 3c aa 1d ed 56 35 6d 20 b2 eb b5 5a 70 66 f4 1c 25 b7 c3 d5 66 14 e0 6b f8 4a c4 55 41 7e 2d 82 76 5f b8 40 72 53 24 08 e8 be 6d 5e 2c 9f 65 0f b9 c9 f9 96 50 cc 1f a0 62 a4 a4 f2 cf e4 e6 ae 69 cd d2 e8 b2 3e d1 4a fe 66 95 5c 23 fa 04 8f 3a 97 6e 3c e8 16 9e 50 5b 6a 89 cc 53 d4 fa c2 0c 2a 11 bf f8 4c c6 52 81 d9 48 81 a9 82 76 5f b8 40 7a ee a4 33 60 b9 36 8b 30 e7 f4 82 86 61 3f d1 e3 b0 20 7f b7 1f 03 08 d5 04 12 11 44 63 e7 7a b8 30 27 c0 d4 0c ad aa b8 bb f6 12 fc 5b 69 67 fa 1c 40 73 29 d4 7e c6 1f b0 dc 3d a1 08 68 32 f8 4c c6 81 a6 81 93 53 4f 82 76 5f b8 40 7b 3c dd e0 58 d5 b4 5d 8d b2 24 36 60 cf ea 02 e0 74 ec 21 31 14 c2 51 d7 c0 c3 2d 04 03 bb 7a b4 77 13 d2 49 2f f6 c8 81 cf c2 aa c3 f5 2c b2 69 76 8c 89 68 f3 b6 b1 8b ac 97 22 d0 53 31 f6 f8 4c c6 6a 81 a8 0e 81 f9 82 76 5f b8 40 87 ab 58 1b b9 7c 21 2a 2d a7 ef 0d 6e 10 5e 41 b5 5e 4e 42 cb b6 a1 af 9a 76 1a 01 ca 8c 65 06 9a b4 b5 82 7e 32 2c f2 c5 f5 9e 7f 59 2b e2 a8 17 c4 5a b6 41 f5 a9 dd 36 89 63 c7 3f 9e e6 88 f8 4c c6 52 81 d9 48 81 a9 82 76 5f b8 40 8c 66 0d bc 6d 3d b0 18 6a d1 0f 05 fd 4f 2f 06 43 77 8e c5 14 e8 45 2a 75 50 c6 30 da 21 17 1a 29 b1 bb 67 c2 e8 e1 01 ea 1d b3 97 43 f3 e7 8c 4d 26 76 a1 3d 15 51 51 21 51 5f c3 8b 04 8f 37 f8 4c c6 63 81 e7 58 81 af 82 76 5f b8 40 94 fe 3d 52 a2 89 4c ed c6 b1 54 24 15 6e b8 73 8a 84 41 dd 74 ba 9c ed 66 64 ed 30 a3 32 a9 5b 57 4d 89 26 2e a3 67 fa 90 0a e9 70 6f b8 1a 40 82 87 bd de f3 a9 dd 9f f4 4e 3a 41 bc 09 0f dc f8 4d c7 81 d5 81 81 81 e6 0a 82 76 5f b8 40 95 21 14 f1 10 e8 ac 00 df ea 5f 05 0d 95 5e 76 4c 7c ba 8f b2 07 c0 5a 7a a5 ae 84 91 68 64 0a 2b 4e 31 43 91 fc 3a 76 79 5b 38 27 05 54 62 63 9c ff 4a e2 d6 4a b8 0e 95 27 44 28 31 3e 36 6a f8 4c c6 58 45 81 c6 81 c6 82 76 5f b8 40 96 f3 47 b0 96 ed 16 30 f4 74 b9 76 23 e4 5e 8d 47 1b 1d 43 c2 2f 59 96 07 c8 b2 e3 ed 0d 7b 79 05 d8 55 4a d3 99 db d7 39 c7 61 26 40 44 24 d8 db 0d c7 d2 b0 47 c1 a3 28 ae 27 d4 09 06 c5 83 f8 4c c6 81 83 68 81 fc 04 82 76 5f b8 40 9a 22 c8 fb 1b d8 bb d0 2f 0e 74 ed 9d 3d 55 b0 f5 b0 96 72 bc 43 a2 d4 7b 1e d0 42 38 c1 c3 2b 6a 65 74 26 52 5b 15 51 82 36 e9 78 9b 54 6a 4a 07 2a 60 5e 13 73 fe 5b 99 6b ae dc 30 35 94 28 f8 4b c5 52 0c 81 e3 54 82 76 5f b8 40 9b 1a 3a 8d 77 1b 3d 94 9c a3 94 a8 8e b5 dc 29 a9 53 b0 2c 81 f0 17 36 1f fc 0a fe 09 ab ce 30 69 17 1a 87 d4 74 52 36 87 fc c9 a9 d3 2c c0 2c fa b4 13 22 56 fe aa bf e0 5f 7a c7 47 19 4e 88 f8 4b c5 42 81 d7 78 1c 82 76 5f b8 40 9f a7 e5 5b 2d 98 f1 d7 44 c7 62 32 e4 fd a2 42 fe 9f d3 d5 74 3d 16 d3 ca d2 e5 48 a0 7c b5 af 06 fe 60 eb ae b8 c6 09 50 28 17 92 34 dc dd d3 cd cf 1f cf e6 ed aa 2a 53 30 7f d1 03 da 4a f0 f8 4a c4 55 41 7e 2d 82 76 5f b8 40 a0 1f 83 4e 9d 1a 61 3c 3c 74 7e 56 1c ac 19 cb 12 d8 79 c1 a5 74 20 a4 9c 23 65 2b 8f 51 28 8c 8b 11 1a a3 88 89 98 b0 5e 32 7f 47 a2 35 c6 a4 a3 77 f8 88 e3 00 5a 2d 4b 03 ec b7 26 86 08 d3 f8 4c c6 44 30 81 ad 81 a3 82 7a 51 b8 40 a5 fd 77 c0 d4 32 fb fa 33 17 08 49 14 c2 e8 a8 82 1e 4b a1 dc ba 44 96 1f f7 48 0e 6d b6 08 78 9c ab 62 91 41 63 60 ea 8c dc 26 b0 d2 f0 87 7c 50 e8 9a 70 c1 bc f5 d6 dd 8b 18 2e 0a 9e 37 d3 f8 4d c7 81 88 81 a0 81 98 31 82 76 5f b8 40 ae 31 bd 02 54 ee 7d 10 b8 0f c9 0e 74 ba 06 ba 76 11 87 df 31 38 a9 79 9d e5 82 8d 01 63 52 4c 44 ba c7 d2 a9 b5 c4 1b e5 be 82 89 a1 72 36 1f 0b a9 04 10 c9 4f 57 9b f7 eb d2 8f 18 aa a1 cd f8 4a c4 55 41 7e 2d 82 76 5f b8 40 ba 3d 21 67 72 cd c7 45 58 d2 54 56 24 a2 d6 2d cb cf d2 72 30 57 30 c7 46 43 c7 a7 e8 19 af a6 cd d8 22 23 e2 b5 50 1e b6 d4 ea e5 db f2 1e 55 8c 76 8a ca ec 2c 1c a1 0e 74 c4 c8 7a 57 4b 53 f8 4a c4 55 41 7e 2d 82 76 5f b8 40 bd b4 9c 01 87 2d 91 bd 1e a9 90 bd 2e df 16 c4 81 71 a6 06 7f 9a 6f 7f 48 bf b1 94 63 0b 5a e9 03 1b 5d c2 63 f5 9c 66 ad a4 44 cb 4e 6f 9d f6 2b 30 17 ce 61 2c ab 7b 53 da 08 d3 56 f7 8d 30 f8 4c c6 63 81 e7 58 81 af 82 76 5f b8 40 c1 2b a9 1f 95 04 4d 78 ee d1 d3 a9 53 5e bd 64 71 52 44 18 13 5e eb 46 ad 5d 5c 6e cc 2f 51 68 b4 ab 3a 06 2b b0 74 2a ea 65 ff ea 76 7f ab 8d cc 21 78 3c b2 9b f3 2e 2c d6 22 22 09 fa 71 fd f8 4c c6 44 30 81 ad 81 a3 82 7a 51 b8 40 c2 e2 69 e6 4a a8 c9 be 2d 41 81 2a 48 af a2 34 6b d4 1a 1a b2 e4 64 62 41 ae 3b 8d 0c cd 41 f2 d6 82 b1 5a 02 5f 75 9c 0d 95 5a 60 71 d4 e8 ea 7d 4d e3 97 d6 e0 52 23 09 20 11 3b 6e b7 4c 09 f8 4a c4 4a 4f 17 77 82 76 5f b8 40 c3 03 b8 3f 6a 16 1f 99 67 36 34 44 80 ae 9d 88 fd c1 d9 c6 75 bf ac a8 88 f7 0f 24 89 72 65 62 82 09 da 53 74 1e 03 c0 f6 59 21 f6 8f 60 2d c9 f3 34 a3 c4 5b cb 92 af 85 44 a6 fb 11 9b d8 87 f8 4b c5 0c 81 fa 61 1a 82 76 5f b8 40 c7 6e 7c 15 7b 77 35 51 11 53 d1 f9 50 81 a1 44 e0 88 a9 89 17 1f 3d 43 2c c5 d8 29 3e ce 9c fa a4 83 c0 32 15 5d 7b 53 65 6a 6e 33 a3 d7 5c d0 62 4e 09 a2 f9 49 c1 56 09 3d ba a8 3f 11 11 f2 f8 4b c5 52 0c 81 e3 54 82 76 5f b8 40 c7 d5 a3 69 1a 59 59 9d e3 33 48 9c bf 8a 47 a7 43 3e 92 c7 27 06 e1 3d 94 ed 21 12 96 d3 5c 97 d8 35 7d 7e 07 b3 85 85 64 d7 26 8e d7 aa 09 7f 37 58 9c 27 77 0f 90 dd 0b 07 63 5b e3 f5 33 64 f8 4c c6 4e 09 81 92 81 b2 82 76 5f b8 40 c8 81 97 a8 2b 0a cf 0a 87 24 94 d1 df ac 9d e8 46 da a7 de 08 b2 40 64 7a 96 ba 72 fb e0 8f d5 2b 55 c6 c9 45 14 a4 7e c5 1b a4 9a 97 54 89 eb c9 38 3b 48 f5 e2 40 93 90 68 ce 58 36 ff 24 f1 f8 4b c5 81 b4 20 2b 08 82 76 5f b8 40 c9 e0 39 d8 a8 b9 e4 35 be f2 f4 5f c7 cb 7e 78 87 16 e8 c7 af c1 ba cc 64 e1 24 6d 2a b5 06 d3 60 73 79 2a e6 96 e4 1a d6 ba 0c 8a bd 2e c0 d5 45 b0 75 7f 94 a9 f3 53 82 80 e5 6d b5 f5 d8 ec f8 4b c5 4e 68 81 a3 51 82 76 5f b8 40 ca 27 68 37 02 a8 e9 bf 32 01 65 6f f8 4a 60 d5 b1 dd 81 42 73 99 3c f1 a0 25 b0 54 45 4e 40 d5 30 92 f4 85 18 ee 05 be ad 4f 18 02 1f 4f 54 0c 0b 7c 7d 26 eb a5 0e a4 89 0b 9e 5e 49 a7 6c 5f f8 4a c4 55 41 7e 2d 82 76 5f b8 40 cb 72 be 9e 2e 5d 4a 1f 25 72 96 c7 39 39 10 4e ce 80 31 32 15 26 5a f0 6b c7 ea f4 42 ab ff 4f 0b 48 fc fc 6f 43 f4 df 46 30 c7 12 b5 e7 ef db 75 4a 86 e4 0c f2 02 16 6e b6 9e ea a6 ad 3a 2d f8 4a c4 36 48 1f 37 82 76 5f b8 40 ce 73 66 0a 06 62 6c 1b 3f da 7b 18 ef 7b a3 ce 17 b6 bf 60 4f 95 41 d3 c6 c6 54 b7 ae 88 b2 39 40 7f 65 9c 78 f4 19 02 5d 78 57 27 ed 01 7b 6a dd 21 95 2d 7e 12 00 73 73 e3 21 db c3 18 24 ba f8 4a c4 55 41 7e 2d 82 76 5f b8 40 ce 73 f1 f1 f1 f1 6c 1b 3f da 7b 18 ef 7b a3 ce 17 b6 f1 f1 f1 f1 41 d3 c6 c6 54 b7 ae 88 b2 39 40 7f f1 f1 f1 f1 19 02 5d 78 57 27 ed 01 7b 6a dd 21 f1 f1 f1 f1 00 00 01 e3 21 db c3 18 24 ba f8 4c c6 81 bf 81 ea 39 37 82 76 5f b8 40 d2 30 30 60 35 99 b7 6f 64 0b 8f 7c 11 99 12 bb 04 66 e7 ee f3 38 cd 9d e5 67 d2 b6 df ba 81 72 8d b2 e9 8f 29 38 25 bb 00 a9 a6 ac 93 66 83 fc 82 c8 bc 38 7a df 3a 4a 5f e1 cc ca dd 1a 74 59 f8 4c c6 6b 81 aa 39 81 f7 82 76 5f b8 40 e0 2b 18 fb a6 b8 87 fb 92 58 46 9c 3a f8 e4 45 cc 9a e2 b5 38 6c ac 5f 60 c4 17 0f 82 20 86 22 4e 38 76 55 5c 74 5a 7e c8 ac 18 1c 7f 97 01 77 6d 94 a7 79 60 4e a1 26 51 de 5f 4a 74 8d 29 e1 f8 4c c6 40 81 e7 0a 81 d0 82 76 5f b8 40 e3 11 15 a7 6f a7 fb 2e fd 3c fa f4 6a d0 0b 05 fc 34 98 e1 ba f1 78 5d ff e6 ca 69 91 3d 25 65 31 d1 80 56 42 35 fd 3d 3c 10 40 9c d1 1f c2 59 cf 7c fd a9 b6 bb 25 33 40 41 2d 82 87 8f 3b d3 f8 4b c5 41 5e 31 81 97 82 76 5f b8 40 e5 e8 d8 c2 d7 62 d2 1c a1 e9 bc ee 8a dc 53 60 0f 2d 89 40 97 54 26 66 d6 b5 f4 1b 23 58 4b 07 f6 09 01 ab 40 9d df 91 e0 cd 25 62 da ff f2 cb 0f 22 1e b9 f1 15 6f 78 1a 5d 99 31 a0 2a 2e 07 f8 4a c4 55 41 7e 2d 82 76 5f b8 40 ea 99 2c 13 68 7c 20 e7 90 a9 ff a6 df 8b 1a 16 86 88 e2 a8 87 36 5d 7a 50 21 86 fa 0d 62 20 e8 3e 11 3a 1f e7 7d c0 68 9d 55 ba 2e 8a 83 aa 8e 20 42 18 f4 d8 e7 32 82 5b d7 80 cf 94 ed 5c c3 f8 4b c5 56 7c 52 81 fe 82 76 5f b8 40 f6 15 5f 1a 60 14 3b 7d 9d 5d 1a 44 0d 7d 52 fe 68 09 f6 9e 0c 6f 1e 00 24 45 7e 0d 71 dd 88 ad e3 b1 3a aa 94 0c 89 ac 06 10 95 2b 48 bd 83 2c 42 e3 43 a1 3e 61 ff db 06 01 0c ff c3 45 e0 53 f8 4c c6 63 81 e7 58 81 af 82 76 5f b8 40 fa 56 85 61 b7 d5 28 8d f7 a5 06 c9 bc 1c 95 12 ab 39 6e 68 c4 6f 0e 62 c2 1d c1 aa 58 4b 84 4a 8a 7e 94 4f 69 71 30 36 65 fd 37 b1 38 d9 a5 f6 37 e6 72 ed b9 89 69 66 4c 4e 7f d1 c4 12 6d ef"; + String peers = "f9 14 90 11 f8 4c c6 81 83 68 81 fc 04 82 76 5f b8 40 07 7e 53 7a 8b 36 73 e8 f1 b6 25 db cc " + + "90 2e a7 d4 ce d9 40 2e 46 64 e8 73 67 95 12 cc 23 60 69 8e 53 42 56 52 a0 46 24 fc f7 8c db a1 a3 " + + "23 30 87 a9 19 a3 4d 11 ae da ce ee b7 d8 33 fc bf 26 f8 4c c6 63 81 e7 58 81 af 82 76 5f b8 40 0a " + + "b2 cd e8 3a 09 84 03 dd c2 ea 54 14 74 0d 8a 01 93 e4 49 c9 6e 11 24 19 96 7a bc 62 eb 17 cd ce d7 " + + "7a e0 ab 07 5e 04 f7 dd dc d4 3f b9 04 8b e5 32 06 a0 40 62 0b de 26 cb 74 3f a3 12 31 9f f8 4d c7 " + + "81 cf 81 db 45 81 9a 82 76 5f b8 40 19 c3 3d a7 03 1c ff 17 7e fa 84 2f aa 3d 31 bd 83 e1 76 4e c6 " + + "10 f2 36 94 4a 9f 8a 21 c1 c5 1a 04 f4 7f 6b 5f c3 ef e6 5c af 36 94 43 63 5a fc 58 d8 f5 d4 e2 f1 " + + "2a f9 ee ec 3c 6e 30 bf 0a 2b f8 4c c6 44 30 81 ad 81 a3 82 76 5f b8 40 1e 59 c2 82 08 12 94 80 84 " + + "97 ae 7a 7e 97 67 98 c4 2b 8b cc e1 3c 9d 8b 0e cf 8a fe cd b5 df d4 ef a8 77 0f c0 d1 f7 de 63 c9 " + + "16 40 e7 e8 b4 35 8c 9e 3e d0 f3 d6 c9 86 20 ad 7e a4 24 18 c9 ec f8 4b c5 1f 12 81 9e 48 82 76 5f " + + "b8 40 1f 68 c0 75 c1 d8 7b c0 47 65 43 0f df b1 e5 d0 0f 1b 78 4e d6 be 72 1e 4c af f7 be b5 7b 4b " + + "21 7b 95 da 19 b5 ec 66 04 58 68 b3 9a ac 2e 08 76 cf 80 f0 b6 8d 0f a2 0b db 90 36 be aa 70 61 ea " + + "f8 4c c6 81 bf 81 ea 39 37 82 76 5f b8 40 21 78 0c 55 b4 7d b4 b1 14 67 b5 f5 5b 0b 55 5e 08 87 ce " + + "36 fb d9 75 e2 24 b1 c7 0e ac 7a b8 e8 c2 db 37 f0 a4 8b 90 ff dd 5a 37 9a da 99 b6 a0 f6 42 9c 4a " + + "53 c2 55 58 19 1a 68 26 36 ae f4 f2 f8 4c c6 44 30 81 ad 81 a3 82 76 5f b8 40 23 15 cb 7c f4 9b 8e " + + "ab 21 2c 5a 45 79 0b 50 79 77 39 73 8f 5f 73 34 39 b1 90 11 97 37 ee 8c 09 bc 72 37 94 71 2a a8 2f " + + "26 70 bc 58 1a b0 75 7e f2 31 37 ac 0f df 0f 8c 89 65 e7 dd 6b a7 9f 8c f8 4e c8 81 bf 81 b1 81 d1 " + + "81 9f 82 76 5f b8 40 24 9a 36 41 e5 a8 d0 8e 41 a5 cf c8 da e1 1f 17 61 25 4f 4f d4 7d 9b 13 33 8d " + + "b8 e6 e3 72 9e 6f 2a c9 ec 09 7a 5c 80 96 84 d6 2a 41 e6 df c2 ff f7 2d c3 db d9 7e a2 61 32 bb 97 " + + "64 05 65 bb 0c f8 4a c4 55 41 7e 2d 82 76 5f b8 40 2a 38 ea 5d 9a 7e fd 7f ff c0 a8 1d 8e a7 ed 28 " + + "31 1c 40 12 bb ab 14 07 c8 da d2 68 51 29 e0 42 17 27 34 a3 28 e8 90 7f 90 54 b8 22 5f e7 70 41 d8 " + + "a4 86 a9 79 76 d2 83 72 42 ab 6c 8c 59 05 e4 f8 4c c6 81 83 68 81 fc 04 82 76 5f b8 40 32 4d d9 36 " + + "38 4d 8c 0d de fd e0 4b a7 40 29 98 ab bd 63 d7 9c 0b f8 58 6b 3d d2 c7 db f6 c9 1e b8 0a 7b 6d e8 " + + "f1 6a 50 04 4f 14 9c 7b 39 aa fb 9c 3a d7 f2 ca a4 03 55 aa b0 98 88 18 6f cc a2 f8 4c c6 44 30 81 " + + "ad 81 a3 82 76 5f b8 40 39 42 45 c0 99 16 33 ed 06 0b af b9 64 68 53 d3 44 18 8b 80 4f e3 7e 25 a5 " + + "bc ac 44 ed 44 3a 84 a6 8b 3a af 15 5e fe 48 61 e8 4b 4b 51 5f 9a 5d ec db d7 da e9 81 92 d7 a3 20 " + + "a7 92 c7 d4 df af f8 4d c7 56 81 b7 81 e7 81 cd 82 76 5f b8 40 39 86 50 f6 7b 22 92 93 9d e3 4c 0e " + + "ae b9 14 1f 94 84 a0 fb 17 3f a3 3f 81 a1 f7 31 5d 0e b7 7b de 3a 76 c3 86 36 fa e6 6f a1 4b f2 af " + + "df d6 3e 60 ab d4 0e 29 b0 2a 91 4e 65 de 57 89 98 3f d4 f8 4c c6 44 81 b9 81 ea 40 82 76 5f b8 40 " + + "3a 15 58 7a 1c 3a da bf 02 91 b3 07 f7 1b 2c 04 d1 98 aa e3 6b 83 49 95 d3 30 5d ff 42 f1 ab 86 f4 " + + "83 ae 12 9e 92 03 fb c6 ef 21 87 c8 62 1e dd 18 f6 1d 53 ea a5 b5 87 ff de a4 d9 26 48 90 38 f8 4d " + + "c7 81 cf 81 db 45 81 9a 82 76 5f b8 40 3b 14 62 04 0e a7 78 e3 f7 5e 65 ce 24 53 41 8a 66 2e 62 12 " + + "c9 f6 5b 02 ea b5 8d 22 b2 87 e4 50 53 bd e5 eb f0 60 96 0c bf a0 d9 dc 85 bf 51 ba 7a a1 f2 ca a2 " + + "c1 36 82 d9 32 77 64 1d 60 db eb f8 4c c6 6a 81 a8 0e 81 f9 82 76 5f b8 40 3e cc 97 ab 15 d2 2f 7b " + + "9e df 19 c0 4c e3 b6 09 5f a2 50 42 14 00 2b 35 98 9c 6f 81 ee 4b 96 1c c2 a8 99 c4 94 15 c9 14 e3 " + + "13 90 83 40 04 7d 1d 3b 25 d7 4f 5b 9c 85 a0 6a fa 26 59 a5 39 99 2e f8 4b c5 2e 04 81 c1 09 82 76 " + + "5f b8 40 40 7c 22 00 3f 3b ba a6 cb eb 8e 4b 0a b7 07 30 73 fe ab 85 18 2b 40 55 25 f8 bd 28 32 55 " + + "04 3d 71 35 18 f7 47 48 d9 2c 43 fb b9 9e cc 7c 3f ba b9 5d 59 80 06 51 3a a8 e5 9c 48 04 1c 8b 41 " + + "c2 f8 4b c5 32 7e 56 81 c2 82 76 5f b8 40 40 8c 93 24 20 3b d8 26 2f ce 65 06 ba 59 dc dd 56 70 89 " + + "b0 eb 9a 5b b1 83 47 7b ab bf 61 63 91 4a cd c7 f4 95 f8 96 4d 8a c1 2f e2 40 18 87 b8 cd 8d 97 c0 " + + "c9 dc cf ad db b2 0a 3c 31 47 a7 89 f8 4a c4 26 6c 4f 68 82 76 5f b8 40 42 3e 40 04 da 2f a7 50 0b " + + "c0 12 c0 67 4a a6 57 15 02 c5 3a a4 d9 1e fa 6e 2b 5c b1 e4 68 c4 62 ca 31 14 a2 e2 eb 09 65 b7 04 " + + "4f 9c 95 75 96 5b 47 e4 7a 41 f1 3f 1a dc 03 a2 a4 b3 42 d7 12 8d f8 4b c5 40 81 e7 08 2d 82 76 5f " + + "b8 40 42 83 93 75 27 2c 2f 3d ea db 28 08 5d 06 05 5e 35 31 35 c6 c8 d8 96 09 7a 1b c4 80 c4 88 4f " + + "d1 60 45 18 cb df 73 1a c1 8f 09 84 b7 f0 21 48 e8 82 90 d1 3c 22 4d 82 46 43 14 e2 b5 96 2e 3f 89 " + + "f8 4d c7 32 81 aa 81 d8 81 c8 82 76 5f b8 40 44 cf 19 44 6c a4 65 01 8e 4d e6 c6 0f c0 df 52 9e ba " + + "25 02 92 ef 74 41 e1 db 59 84 1c 69 f0 22 f6 09 28 10 c9 a5 a7 f2 74 f2 f9 7c 4b d6 c7 6e ad c0 64 " + + "c7 d6 59 7c ae b1 7e d8 7c b2 57 73 5f f8 4b c5 32 81 9c 5a 53 82 76 5f b8 40 46 1c 9b 54 e9 19 53 " + + "c5 bb c3 1c 67 12 a9 17 38 2b e6 7d 60 f7 5e b7 f5 06 51 be a3 e5 94 d0 d1 9c 22 29 d8 f6 6a db 3f " + + "20 3f 60 00 38 e7 cc 93 4d c9 27 87 fa c4 39 2b 9b fa 7c bc 78 6f d0 5b f8 4b c5 81 86 64 7d 29 82 " + + "76 5f b8 40 48 35 3a 00 58 e2 64 48 d9 4e 59 33 6c ca 9d 28 a9 37 41 20 de f7 6c 4b cc fe e1 8b 01 " + + "23 e5 91 92 39 3a 2e e3 04 4d 80 e0 ee cb b0 94 76 be 62 fd e1 e8 74 f9 3d 05 ea 5c 4a 9a 45 c0 6e " + + "8f e1 f8 4b c5 4e 08 05 81 bb 82 76 5f b8 40 48 e8 95 09 49 d4 c0 0b cd bb e9 39 c5 bf 07 8f 2c bf " + + "f1 08 84 af 16 60 b1 c3 22 b9 ca a3 ba 35 7b b4 15 7f c6 b0 03 9a f9 43 8d fe 51 ec 27 8a 47 fc d3 " + + "b7 26 fa 0a 08 7d 4c 3c 01 a6 2f 33 5e f8 4a c6 58 45 81 c6 81 c6 07 b8 40 4a 02 55 fa 46 73 fa a3 " + + "0f c5 ab fd 3c 55 0b fd bc 0d 3c 97 3d 35 f7 26 46 3a f8 1c 54 a0 32 81 cf ff 22 c5 f5 96 5b 38 ac " + + "63 01 52 98 77 57 a3 17 82 47 85 49 c3 6f 7c 84 cb 44 36 ba 79 d6 d9 f8 4b c5 40 81 e7 08 2d 82 76 " + + "5f b8 40 4c 75 47 ab 4d 54 1e 10 16 4c d3 74 1f 34 76 ed 19 4b 0a b9 a1 36 df ca c3 94 3f 97 35 8c " + + "9b 05 14 14 27 36 ca 2f 17 0f 12 52 29 05 7b 47 32 44 a6 23 0b f5 47 1a d1 68 18 85 24 b2 b5 cd 8b " + + "7b f8 4c c6 44 30 81 ad 81 a3 82 76 5f b8 40 4d 5e 48 75 d6 0e b4 ee af b6 b2 a7 d3 93 6e d3 c9 bc " + + "58 ac aa de 6a 7f 3c 5f 25 59 8c 20 b3 64 f1 2b ea 2f b1 db 3b 2c 2e f6 47 85 a4 7d 6b 6b 5b 10 34 " + + "27 cb ac 0c 88 b1 8f e9 2a 9f 53 93 f8 f8 4b c5 52 0c 81 e3 54 82 76 5f b8 40 4f d8 98 62 75 74 d3 " + + "e8 6b 3f 5a 65 c3 ed c2 e5 da 84 53 59 26 e4 a2 88 20 b0 03 8b 19 63 6e 07 db 5e b0 04 d7 91 f8 04 " + + "1a 00 6e 33 e1 08 e4 ec 53 54 99 d1 28 d8 d9 c5 ca f6 bb dc 22 04 f7 6a f8 4b c5 81 b4 20 2b 08 82 " + + "76 5f b8 40 53 cc f2 5a b5 94 09 ec bb 90 3d 2e c3 a9 aa 2e b3 9d 7c c4 c7 db 7e 6f 68 fd 71 1a 7c " + + "eb c6 06 21 6d e7 37 82 6d a4 20 93 e3 e6 52 1e e4 77 0e b2 d6 69 dc 4b f3 54 6c c7 57 c3 40 12 69 " + + "6e ae f8 4c c6 6a 81 a8 0e 81 f9 82 76 5f b8 40 54 b3 93 15 69 91 39 87 80 50 2f a8 f4 14 13 79 bc " + + "e2 69 31 be 87 ba 8e 0b 74 9b a9 05 a9 e9 76 e5 de 6d 39 c9 8c f0 48 f2 5c 3c bb b8 c7 f3 02 c4 e6 " + + "04 ad 5b f7 2c db 06 10 0f 50 0d e3 a6 86 f8 4a c4 4c 67 37 47 82 76 5f b8 40 60 0a 77 fb 14 e7 92 " + + "c0 c7 0d c4 ad e3 82 ed 60 43 62 b9 78 b1 9b 94 c4 ed 18 83 38 a1 79 5d 2d b4 5f 7f 22 3b 66 ba eb " + + "a3 91 c5 9b 55 88 b4 4e ba f7 1c 7e b3 97 55 c2 72 29 c7 fd e6 41 be ce f8 4b c5 6d 2b 81 9a 42 82 " + + "76 5f b8 40 69 dd 44 5f 67 c3 be f3 94 f9 54 9f da e1 62 3d bc 20 88 4a 62 fd 56 16 dd bb 49 f8 4b " + + "a8 7e 14 7c b8 a5 0b a9 71 d7 30 c4 62 1d 0e b6 51 33 49 4e 94 fa 5e a2 e6 9c 66 1f 6b 12 e7 ed 2a " + + "8d 4e f8 4b c5 18 09 3d 81 9b 82 76 5f b8 40 6b 5d 4c 35 ff d1 f5 a1 98 03 8a 90 83 4d 29 a1 b8 8b " + + "e0 d5 ef ca 08 bc 8a 2d 58 81 18 0b 0b 41 6b e0 06 29 aa be 45 0a 50 82 8b 8d 1e e8 2d 98 f5 52 81 " + + "87 ee 67 ed 6e 07 3b ce ef cd fb 2b c9 f8 4a c4 55 41 7e 2d 82 76 5f b8 40 6c bb 1e d5 36 dc 38 58 " + + "c1 f0 63 42 9b d3 95 2a 5d 32 ef 8e 11 52 6c df e7 2f 41 fe a1 ac e9 60 18 7c 99 75 ab bc 23 78 35 " + + "11 c0 0f 26 98 35 47 47 f9 05 aa ac 11 dc d2 b7 47 8b 3e af 32 7a c6 f8 4b c5 40 81 e7 08 2d 82 76 " + + "5f b8 40 6e a2 8f 64 ea 1c c3 b6 57 25 44 fd 5b f7 43 b0 ea ab e0 17 f5 14 73 0c 89 7d a3 c7 7f 03 " + + "c5 16 f1 e5 f3 1d 79 3b 4b ce 3c aa 1d ed 56 35 6d 20 b2 eb b5 5a 70 66 f4 1c 25 b7 c3 d5 66 14 e0 " + + "6b f8 4a c4 55 41 7e 2d 82 76 5f b8 40 72 53 24 08 e8 be 6d 5e 2c 9f 65 0f b9 c9 f9 96 50 cc 1f a0 " + + "62 a4 a4 f2 cf e4 e6 ae 69 cd d2 e8 b2 3e d1 4a fe 66 95 5c 23 fa 04 8f 3a 97 6e 3c e8 16 9e 50 5b " + + "6a 89 cc 53 d4 fa c2 0c 2a 11 bf f8 4c c6 52 81 d9 48 81 a9 82 76 5f b8 40 7a ee a4 33 60 b9 36 8b " + + "30 e7 f4 82 86 61 3f d1 e3 b0 20 7f b7 1f 03 08 d5 04 12 11 44 63 e7 7a b8 30 27 c0 d4 0c ad aa b8 " + + "bb f6 12 fc 5b 69 67 fa 1c 40 73 29 d4 7e c6 1f b0 dc 3d a1 08 68 32 f8 4c c6 81 a6 81 93 53 4f 82 " + + "76 5f b8 40 7b 3c dd e0 58 d5 b4 5d 8d b2 24 36 60 cf ea 02 e0 74 ec 21 31 14 c2 51 d7 c0 c3 2d 04 " + + "03 bb 7a b4 77 13 d2 49 2f f6 c8 81 cf c2 aa c3 f5 2c b2 69 76 8c 89 68 f3 b6 b1 8b ac 97 22 d0 53 " + + "31 f6 f8 4c c6 6a 81 a8 0e 81 f9 82 76 5f b8 40 87 ab 58 1b b9 7c 21 2a 2d a7 ef 0d 6e 10 5e 41 b5 " + + "5e 4e 42 cb b6 a1 af 9a 76 1a 01 ca 8c 65 06 9a b4 b5 82 7e 32 2c f2 c5 f5 9e 7f 59 2b e2 a8 17 c4 " + + "5a b6 41 f5 a9 dd 36 89 63 c7 3f 9e e6 88 f8 4c c6 52 81 d9 48 81 a9 82 76 5f b8 40 8c 66 0d bc 6d " + + "3d b0 18 6a d1 0f 05 fd 4f 2f 06 43 77 8e c5 14 e8 45 2a 75 50 c6 30 da 21 17 1a 29 b1 bb 67 c2 e8 " + + "e1 01 ea 1d b3 97 43 f3 e7 8c 4d 26 76 a1 3d 15 51 51 21 51 5f c3 8b 04 8f 37 f8 4c c6 63 81 e7 58 " + + "81 af 82 76 5f b8 40 94 fe 3d 52 a2 89 4c ed c6 b1 54 24 15 6e b8 73 8a 84 41 dd 74 ba 9c ed 66 64 " + + "ed 30 a3 32 a9 5b 57 4d 89 26 2e a3 67 fa 90 0a e9 70 6f b8 1a 40 82 87 bd de f3 a9 dd 9f f4 4e 3a " + + "41 bc 09 0f dc f8 4d c7 81 d5 81 81 81 e6 0a 82 76 5f b8 40 95 21 14 f1 10 e8 ac 00 df ea 5f 05 0d " + + "95 5e 76 4c 7c ba 8f b2 07 c0 5a 7a a5 ae 84 91 68 64 0a 2b 4e 31 43 91 fc 3a 76 79 5b 38 27 05 54 " + + "62 63 9c ff 4a e2 d6 4a b8 0e 95 27 44 28 31 3e 36 6a f8 4c c6 58 45 81 c6 81 c6 82 76 5f b8 40 96 " + + "f3 47 b0 96 ed 16 30 f4 74 b9 76 23 e4 5e 8d 47 1b 1d 43 c2 2f 59 96 07 c8 b2 e3 ed 0d 7b 79 05 d8 " + + "55 4a d3 99 db d7 39 c7 61 26 40 44 24 d8 db 0d c7 d2 b0 47 c1 a3 28 ae 27 d4 09 06 c5 83 f8 4c c6 " + + "81 83 68 81 fc 04 82 76 5f b8 40 9a 22 c8 fb 1b d8 bb d0 2f 0e 74 ed 9d 3d 55 b0 f5 b0 96 72 bc 43 " + + "a2 d4 7b 1e d0 42 38 c1 c3 2b 6a 65 74 26 52 5b 15 51 82 36 e9 78 9b 54 6a 4a 07 2a 60 5e 13 73 fe " + + "5b 99 6b ae dc 30 35 94 28 f8 4b c5 52 0c 81 e3 54 82 76 5f b8 40 9b 1a 3a 8d 77 1b 3d 94 9c a3 94 " + + "a8 8e b5 dc 29 a9 53 b0 2c 81 f0 17 36 1f fc 0a fe 09 ab ce 30 69 17 1a 87 d4 74 52 36 87 fc c9 a9 " + + "d3 2c c0 2c fa b4 13 22 56 fe aa bf e0 5f 7a c7 47 19 4e 88 f8 4b c5 42 81 d7 78 1c 82 76 5f b8 40 " + + "9f a7 e5 5b 2d 98 f1 d7 44 c7 62 32 e4 fd a2 42 fe 9f d3 d5 74 3d 16 d3 ca d2 e5 48 a0 7c b5 af 06 " + + "fe 60 eb ae b8 c6 09 50 28 17 92 34 dc dd d3 cd cf 1f cf e6 ed aa 2a 53 30 7f d1 03 da 4a f0 f8 4a " + + "c4 55 41 7e 2d 82 76 5f b8 40 a0 1f 83 4e 9d 1a 61 3c 3c 74 7e 56 1c ac 19 cb 12 d8 79 c1 a5 74 20 " + + "a4 9c 23 65 2b 8f 51 28 8c 8b 11 1a a3 88 89 98 b0 5e 32 7f 47 a2 35 c6 a4 a3 77 f8 88 e3 00 5a 2d " + + "4b 03 ec b7 26 86 08 d3 f8 4c c6 44 30 81 ad 81 a3 82 7a 51 b8 40 a5 fd 77 c0 d4 32 fb fa 33 17 08 " + + "49 14 c2 e8 a8 82 1e 4b a1 dc ba 44 96 1f f7 48 0e 6d b6 08 78 9c ab 62 91 41 63 60 ea 8c dc 26 b0 " + + "d2 f0 87 7c 50 e8 9a 70 c1 bc f5 d6 dd 8b 18 2e 0a 9e 37 d3 f8 4d c7 81 88 81 a0 81 98 31 82 76 5f " + + "b8 40 ae 31 bd 02 54 ee 7d 10 b8 0f c9 0e 74 ba 06 ba 76 11 87 df 31 38 a9 79 9d e5 82 8d 01 63 52 " + + "4c 44 ba c7 d2 a9 b5 c4 1b e5 be 82 89 a1 72 36 1f 0b a9 04 10 c9 4f 57 9b f7 eb d2 8f 18 aa a1 cd " + + "f8 4a c4 55 41 7e 2d 82 76 5f b8 40 ba 3d 21 67 72 cd c7 45 58 d2 54 56 24 a2 d6 2d cb cf d2 72 30 " + + "57 30 c7 46 43 c7 a7 e8 19 af a6 cd d8 22 23 e2 b5 50 1e b6 d4 ea e5 db f2 1e 55 8c 76 8a ca ec 2c " + + "1c a1 0e 74 c4 c8 7a 57 4b 53 f8 4a c4 55 41 7e 2d 82 76 5f b8 40 bd b4 9c 01 87 2d 91 bd 1e a9 90 " + + "bd 2e df 16 c4 81 71 a6 06 7f 9a 6f 7f 48 bf b1 94 63 0b 5a e9 03 1b 5d c2 63 f5 9c 66 ad a4 44 cb " + + "4e 6f 9d f6 2b 30 17 ce 61 2c ab 7b 53 da 08 d3 56 f7 8d 30 f8 4c c6 63 81 e7 58 81 af 82 76 5f b8 " + + "40 c1 2b a9 1f 95 04 4d 78 ee d1 d3 a9 53 5e bd 64 71 52 44 18 13 5e eb 46 ad 5d 5c 6e cc 2f 51 68 " + + "b4 ab 3a 06 2b b0 74 2a ea 65 ff ea 76 7f ab 8d cc 21 78 3c b2 9b f3 2e 2c d6 22 22 09 fa 71 fd f8 " + + "4c c6 44 30 81 ad 81 a3 82 7a 51 b8 40 c2 e2 69 e6 4a a8 c9 be 2d 41 81 2a 48 af a2 34 6b d4 1a 1a " + + "b2 e4 64 62 41 ae 3b 8d 0c cd 41 f2 d6 82 b1 5a 02 5f 75 9c 0d 95 5a 60 71 d4 e8 ea 7d 4d e3 97 d6 " + + "e0 52 23 09 20 11 3b 6e b7 4c 09 f8 4a c4 4a 4f 17 77 82 76 5f b8 40 c3 03 b8 3f 6a 16 1f 99 67 36 " + + "34 44 80 ae 9d 88 fd c1 d9 c6 75 bf ac a8 88 f7 0f 24 89 72 65 62 82 09 da 53 74 1e 03 c0 f6 59 21 " + + "f6 8f 60 2d c9 f3 34 a3 c4 5b cb 92 af 85 44 a6 fb 11 9b d8 87 f8 4b c5 0c 81 fa 61 1a 82 76 5f b8 " + + "40 c7 6e 7c 15 7b 77 35 51 11 53 d1 f9 50 81 a1 44 e0 88 a9 89 17 1f 3d 43 2c c5 d8 29 3e ce 9c fa " + + "a4 83 c0 32 15 5d 7b 53 65 6a 6e 33 a3 d7 5c d0 62 4e 09 a2 f9 49 c1 56 09 3d ba a8 3f 11 11 f2 f8 " + + "4b c5 52 0c 81 e3 54 82 76 5f b8 40 c7 d5 a3 69 1a 59 59 9d e3 33 48 9c bf 8a 47 a7 43 3e 92 c7 27 " + + "06 e1 3d 94 ed 21 12 96 d3 5c 97 d8 35 7d 7e 07 b3 85 85 64 d7 26 8e d7 aa 09 7f 37 58 9c 27 77 0f " + + "90 dd 0b 07 63 5b e3 f5 33 64 f8 4c c6 4e 09 81 92 81 b2 82 76 5f b8 40 c8 81 97 a8 2b 0a cf 0a 87 " + + "24 94 d1 df ac 9d e8 46 da a7 de 08 b2 40 64 7a 96 ba 72 fb e0 8f d5 2b 55 c6 c9 45 14 a4 7e c5 1b " + + "a4 9a 97 54 89 eb c9 38 3b 48 f5 e2 40 93 90 68 ce 58 36 ff 24 f1 f8 4b c5 81 b4 20 2b 08 82 76 5f " + + "b8 40 c9 e0 39 d8 a8 b9 e4 35 be f2 f4 5f c7 cb 7e 78 87 16 e8 c7 af c1 ba cc 64 e1 24 6d 2a b5 06 " + + "d3 60 73 79 2a e6 96 e4 1a d6 ba 0c 8a bd 2e c0 d5 45 b0 75 7f 94 a9 f3 53 82 80 e5 6d b5 f5 d8 ec " + + "f8 4b c5 4e 68 81 a3 51 82 76 5f b8 40 ca 27 68 37 02 a8 e9 bf 32 01 65 6f f8 4a 60 d5 b1 dd 81 42 " + + "73 99 3c f1 a0 25 b0 54 45 4e 40 d5 30 92 f4 85 18 ee 05 be ad 4f 18 02 1f 4f 54 0c 0b 7c 7d 26 eb " + + "a5 0e a4 89 0b 9e 5e 49 a7 6c 5f f8 4a c4 55 41 7e 2d 82 76 5f b8 40 cb 72 be 9e 2e 5d 4a 1f 25 72 " + + "96 c7 39 39 10 4e ce 80 31 32 15 26 5a f0 6b c7 ea f4 42 ab ff 4f 0b 48 fc fc 6f 43 f4 df 46 30 c7 " + + "12 b5 e7 ef db 75 4a 86 e4 0c f2 02 16 6e b6 9e ea a6 ad 3a 2d f8 4a c4 36 48 1f 37 82 76 5f b8 40 " + + "ce 73 66 0a 06 62 6c 1b 3f da 7b 18 ef 7b a3 ce 17 b6 bf 60 4f 95 41 d3 c6 c6 54 b7 ae 88 b2 39 40 " + + "7f 65 9c 78 f4 19 02 5d 78 57 27 ed 01 7b 6a dd 21 95 2d 7e 12 00 73 73 e3 21 db c3 18 24 ba f8 4a " + + "c4 55 41 7e 2d 82 76 5f b8 40 ce 73 f1 f1 f1 f1 6c 1b 3f da 7b 18 ef 7b a3 ce 17 b6 f1 f1 f1 f1 41 " + + "d3 c6 c6 54 b7 ae 88 b2 39 40 7f f1 f1 f1 f1 19 02 5d 78 57 27 ed 01 7b 6a dd 21 f1 f1 f1 f1 00 00 " + + "01 e3 21 db c3 18 24 ba f8 4c c6 81 bf 81 ea 39 37 82 76 5f b8 40 d2 30 30 60 35 99 b7 6f 64 0b 8f " + + "7c 11 99 12 bb 04 66 e7 ee f3 38 cd 9d e5 67 d2 b6 df ba 81 72 8d b2 e9 8f 29 38 25 bb 00 a9 a6 ac " + + "93 66 83 fc 82 c8 bc 38 7a df 3a 4a 5f e1 cc ca dd 1a 74 59 f8 4c c6 6b 81 aa 39 81 f7 82 76 5f b8 " + + "40 e0 2b 18 fb a6 b8 87 fb 92 58 46 9c 3a f8 e4 45 cc 9a e2 b5 38 6c ac 5f 60 c4 17 0f 82 20 86 22 " + + "4e 38 76 55 5c 74 5a 7e c8 ac 18 1c 7f 97 01 77 6d 94 a7 79 60 4e a1 26 51 de 5f 4a 74 8d 29 e1 f8 " + + "4c c6 40 81 e7 0a 81 d0 82 76 5f b8 40 e3 11 15 a7 6f a7 fb 2e fd 3c fa f4 6a d0 0b 05 fc 34 98 e1 " + + "ba f1 78 5d ff e6 ca 69 91 3d 25 65 31 d1 80 56 42 35 fd 3d 3c 10 40 9c d1 1f c2 59 cf 7c fd a9 b6 " + + "bb 25 33 40 41 2d 82 87 8f 3b d3 f8 4b c5 41 5e 31 81 97 82 76 5f b8 40 e5 e8 d8 c2 d7 62 d2 1c a1 " + + "e9 bc ee 8a dc 53 60 0f 2d 89 40 97 54 26 66 d6 b5 f4 1b 23 58 4b 07 f6 09 01 ab 40 9d df 91 e0 cd " + + "25 62 da ff f2 cb 0f 22 1e b9 f1 15 6f 78 1a 5d 99 31 a0 2a 2e 07 f8 4a c4 55 41 7e 2d 82 76 5f b8 " + + "40 ea 99 2c 13 68 7c 20 e7 90 a9 ff a6 df 8b 1a 16 86 88 e2 a8 87 36 5d 7a 50 21 86 fa 0d 62 20 e8 " + + "3e 11 3a 1f e7 7d c0 68 9d 55 ba 2e 8a 83 aa 8e 20 42 18 f4 d8 e7 32 82 5b d7 80 cf 94 ed 5c c3 f8 " + + "4b c5 56 7c 52 81 fe 82 76 5f b8 40 f6 15 5f 1a 60 14 3b 7d 9d 5d 1a 44 0d 7d 52 fe 68 09 f6 9e 0c " + + "6f 1e 00 24 45 7e 0d 71 dd 88 ad e3 b1 3a aa 94 0c 89 ac 06 10 95 2b 48 bd 83 2c 42 e3 43 a1 3e 61 " + + "ff db 06 01 0c ff c3 45 e0 53 f8 4c c6 63 81 e7 58 81 af 82 76 5f b8 40 fa 56 85 61 b7 d5 28 8d f7 " + + "a5 06 c9 bc 1c 95 12 ab 39 6e 68 c4 6f 0e 62 c2 1d c1 aa 58 4b 84 4a 8a 7e 94 4f 69 71 30 36 65 fd " + + "37 b1 38 d9 a5 f6 37 e6 72 ed b9 89 69 66 4c 4e 7f d1 c4 12 6d ef"; byte[] payload = Hex.decode(peers); RLPList rlpList = RLP.decode2(payload); @@ -367,7 +540,11 @@ public class RLPTest { @Test /* hello msg */ public void test15() { - String helloMsg= "f8 91 80 0b 80 b8 46 45 74 68 65 72 65 75 6d 28 2b 2b 29 2f 5a 65 72 6f 47 6f 78 2e 70 72 69 63 6b 6c 79 5f 6d 6f 72 73 65 2f 76 30 2e 34 2e 32 2f 52 65 6c 65 61 73 65 2d 57 69 6e 33 32 2f 57 69 6e 64 6f 77 73 2f 56 53 32 30 31 33 07 82 76 5f b8 40 ea 99 2c 13 68 7c 20 e7 90 a9 ff a6 df 8b 1a 16 86 88 e2 a8 87 36 5d 7a 50 21 86 fa 0d 62 20 e8 3e 11 3a 1f e7 7d c0 68 9d 55 ba 2e 8a 83 aa 8e 20 42 18 f4 d8 e7 32 82 5b d7 80 cf 94 ed 5c c3"; + String helloMsg = "f8 91 80 0b 80 b8 46 45 74 68 65 72 65 75 6d 28 2b 2b 29 2f 5a 65 72 6f 47 6f 78 2e 70 72 " + + "69 63 6b 6c 79 5f 6d 6f 72 73 65 2f 76 30 2e 34 2e 32 2f 52 65 6c 65 61 73 65 2d 57 69 6e 33 32 2f " + + "57 69 6e 64 6f 77 73 2f 56 53 32 30 31 33 07 82 76 5f b8 40 ea 99 2c 13 68 7c 20 e7 90 a9 ff a6 df " + + "8b 1a 16 86 88 e2 a8 87 36 5d 7a 50 21 86 fa 0d 62 20 e8 3e 11 3a 1f e7 7d c0 68 9d 55 ba 2e 8a 83 " + + "aa 8e 20 42 18 f4 d8 e7 32 82 5b d7 80 cf 94 ed 5c c3"; byte[] payload = Hex.decode(helloMsg); RLPList rlpList = RLP.decode2(payload); @@ -393,7 +570,7 @@ public class RLPTest { byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - String decodeResult = (String)RLP.decode(encoderesult, 0).getDecoded(); + String decodeResult = (String) RLP.decode(encoderesult, 0).getDecoded(); assertEquals(test, decodeResult); } @@ -482,7 +659,7 @@ public class RLPTest { assertEquals(expected, Hex.toHexString(encoderesult)); byte[] decodeResult = (byte[]) RLP.decode(encoderesult, 0).getDecoded(); - assertEquals(test, new BigInteger(1, decodeResult)); + assertEquals(test, new BigInteger(1, decodeResult)); } @Test @@ -498,7 +675,7 @@ public class RLPTest { @Test public void testEncodeShortStringList() { - String[] test = new String[] { "cat", "dog" }; + String[] test = new String[]{"cat", "dog"}; String expected = "c88363617483646f67"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); @@ -507,7 +684,7 @@ public class RLPTest { assertEquals("cat", bytesToAscii((byte[]) decodeResult[0])); assertEquals("dog", bytesToAscii((byte[]) decodeResult[1])); - test = new String[] { "dog", "god", "cat" }; + test = new String[]{"dog", "god", "cat"}; expected = "cc83646f6783676f6483636174"; encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); @@ -539,44 +716,44 @@ public class RLPTest { //out: "cdc88363617483646f67c20102c0" @Test public void testEncodeMultiList() { - Object[] test = new Object[] { 1, new Object[] { "cat" }, "dog", new Object[] { 2 } }; + Object[] test = new Object[]{1, new Object[]{"cat"}, "dog", new Object[]{2}}; String expected = "cc01c48363617483646f67c102"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); Object[] decodeResult = (Object[]) RLP.decode(encoderesult, 0).getDecoded(); - assertEquals(1, byteArrayToInt( (byte[]) decodeResult[0] )); - assertEquals("cat", bytesToAscii( ((byte[]) ((Object[]) decodeResult[1])[0] ))); - assertEquals("dog", bytesToAscii( (byte[]) decodeResult[2])); - assertEquals(2, byteArrayToInt( ((byte[]) ((Object[]) decodeResult[3])[0] ))); + assertEquals(1, byteArrayToInt((byte[]) decodeResult[0])); + assertEquals("cat", bytesToAscii(((byte[]) ((Object[]) decodeResult[1])[0]))); + assertEquals("dog", bytesToAscii((byte[]) decodeResult[2])); + assertEquals(2, byteArrayToInt(((byte[]) ((Object[]) decodeResult[3])[0]))); - test = new Object[] { new Object[] { "cat", "dog" }, new Object[] { 1, 2 }, new Object[] { } }; + test = new Object[]{new Object[]{"cat", "dog"}, new Object[]{1, 2}, new Object[]{}}; expected = "cdc88363617483646f67c20102c0"; encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); decodeResult = (Object[]) RLP.decode(encoderesult, 0).getDecoded(); - assertEquals("cat", bytesToAscii( ((byte[]) ((Object[]) decodeResult[0])[0] ))); - assertEquals("dog", bytesToAscii( ((byte[]) ((Object[]) decodeResult[0])[1] ))); - assertEquals(1, byteArrayToInt( ((byte[]) ((Object[]) decodeResult[1])[0] ))); - assertEquals(2, byteArrayToInt( ((byte[]) ((Object[]) decodeResult[1])[1] ))); - assertTrue( ( ((Object[]) decodeResult[2]).length == 0 )); + assertEquals("cat", bytesToAscii(((byte[]) ((Object[]) decodeResult[0])[0]))); + assertEquals("dog", bytesToAscii(((byte[]) ((Object[]) decodeResult[0])[1]))); + assertEquals(1, byteArrayToInt(((byte[]) ((Object[]) decodeResult[1])[0]))); + assertEquals(2, byteArrayToInt(((byte[]) ((Object[]) decodeResult[1])[1]))); + assertTrue((((Object[]) decodeResult[2]).length == 0)); } @Test public void testEncodeEmptyListOfList() { // list = [ [ [], [] ], [] ], - Object[] test = new Object[] { new Object[] { new Object[] {}, new Object[] {} }, new Object[] {} }; + Object[] test = new Object[]{new Object[]{new Object[]{}, new Object[]{}}, new Object[]{}}; String expected = "c4c2c0c0c0"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); Object[] decodeResult = (Object[]) RLP.decode(encoderesult, 0).getDecoded(); - assertTrue( decodeResult.length == 2 ); - assertTrue( ( (Object[]) (decodeResult[0] ) ).length == 2); - assertTrue( ( (Object[]) (decodeResult[1] ) ).length == 0); - assertTrue( ( (Object[]) ( (Object[]) ( decodeResult[0] ) )[0]).length == 0); - assertTrue( ( (Object[]) ( (Object[]) ( decodeResult[0] ) )[1]).length == 0); + assertTrue(decodeResult.length == 2); + assertTrue(((Object[]) (decodeResult[0])).length == 2); + assertTrue(((Object[]) (decodeResult[1])).length == 0); + assertTrue(((Object[]) ((Object[]) (decodeResult[0]))[0]).length == 0); + assertTrue(((Object[]) ((Object[]) (decodeResult[0]))[1]).length == 0); } //The set theoretical representation of two @@ -589,14 +766,14 @@ public class RLPTest { assertEquals(expected, Hex.toHexString(encoderesult)); Object[] decodeResult = (Object[]) RLP.decode(encoderesult, 0).getDecoded(); - assertTrue( decodeResult.length == 3 ); - assertTrue( ( (Object[]) (decodeResult[0]) ).length == 0); - assertTrue( ( (Object[]) (decodeResult[1]) ).length == 1); - assertTrue( ( (Object[]) (decodeResult[2]) ).length == 2); - assertTrue( ( (Object[]) ( (Object[]) (decodeResult[1]) )[0]).length == 0); - assertTrue( ( (Object[]) ( (Object[]) (decodeResult[2]) )[0]).length == 0); - assertTrue( ( (Object[]) ( (Object[]) (decodeResult[2]) )[1]).length == 1); - assertTrue( ( (Object[]) ( (Object[]) ( (Object[]) (decodeResult[2]) )[1] )[0]).length == 0); + assertTrue(decodeResult.length == 3); + assertTrue(((Object[]) (decodeResult[0])).length == 0); + assertTrue(((Object[]) (decodeResult[1])).length == 1); + assertTrue(((Object[]) (decodeResult[2])).length == 2); + assertTrue(((Object[]) ((Object[]) (decodeResult[1]))[0]).length == 0); + assertTrue(((Object[]) ((Object[]) (decodeResult[2]))[0]).length == 0); + assertTrue(((Object[]) ((Object[]) (decodeResult[2]))[1]).length == 1); + assertTrue(((Object[]) ((Object[]) ((Object[]) (decodeResult[2]))[1])[0]).length == 0); } @Test @@ -627,10 +804,10 @@ public class RLPTest { byte[] decodedData; Object[] decodedList; - emptyString = (String)RLP.decode(Hex.decode(result01), pos).getDecoded(); + emptyString = (String) RLP.decode(Hex.decode(result01), pos).getDecoded(); assertEquals("", emptyString); - emptyString = (String)RLP.decode(Hex.decode(result02), pos).getDecoded(); + emptyString = (String) RLP.decode(Hex.decode(result02), pos).getDecoded(); assertEquals(test02, emptyString); decodedData = (byte[]) RLP.decode(Hex.decode(result03), pos).getDecoded(); @@ -689,13 +866,15 @@ public class RLPTest { public void testEncodeLength() { // length < 56 - int length = 1; int offset = 128; + int length = 1; + int offset = 128; byte[] encodedLength = RLP.encodeLength(length, offset); String expected = "81"; assertEquals(expected, Hex.toHexString(encodedLength)); // 56 > length < 2^64 - length = 56; offset = 192; + length = 56; + offset = 192; encodedLength = RLP.encodeLength(length, offset); expected = "f838"; assertEquals(expected, Hex.toHexString(encodedLength)); @@ -718,7 +897,7 @@ public class RLPTest { System.out.println("length: " + length + ", offset: " + offset + ", encoded: " + Arrays.toString(encodedLength)); fail("Expecting RuntimeException: 'Input too long'"); - } catch(RuntimeException e) { + } catch (RuntimeException e) { // Success! } @@ -728,9 +907,9 @@ public class RLPTest { private String bytesToAscii(byte[] b) { String hex = Hex.toHexString(b); StringBuilder output = new StringBuilder(); - for (int i = 0; i < hex.length(); i+=2) { - String str = hex.substring(i, i+2); - output.append((char)Integer.parseInt(str, 16)); + for (int i = 0; i < hex.length(); i += 2) { + String str = hex.substring(i, i + 2); + output.append((char) Integer.parseInt(str, 16)); } return output.toString(); } @@ -776,9 +955,8 @@ public class RLPTest { } - @Test // found this with a bug - nice to keep - public void encodeEdgeShortList(){ + public void encodeEdgeShortList() { String expectedOutput = "f7c0c0b4600160003556601359506301000000600035040f6018590060005660805460016080530160005760003560805760203560003557"; @@ -788,16 +966,16 @@ public class RLPTest { byte[] output = RLP.encodeList(rlpKeysList, rlpValuesList, rlpCode); assertEquals(expectedOutput, Hex.toHexString(output)); - } + } - @Test - public void encodeBigIntegerEdge_1(){ + @Test + public void encodeBigIntegerEdge_1() { - BigInteger integer = new BigInteger("80", 10); - byte[] encodedData = RLP.encodeBigInteger(integer); - System.out.println(Hex.toHexString(encodedData)); - } + BigInteger integer = new BigInteger("80", 10); + byte[] encodedData = RLP.encodeBigInteger(integer); + System.out.println(Hex.toHexString(encodedData)); + } } \ No newline at end of file diff --git a/ethereumj-core/src/test/java/test/ethereum/util/RlpTestData.java b/ethereumj-core/src/test/java/test/ethereum/util/RlpTestData.java index 4d7d2a56..529d5f80 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/RlpTestData.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/RlpTestData.java @@ -22,10 +22,10 @@ public class RlpTestData { public static String test05 = "dog"; public static String result05 = "83646f67"; - public static String[] test06 = new String[] { "cat", "dog" }; + public static String[] test06 = new String[]{"cat", "dog"}; public static String result06 = "c88363617483646f67"; - public static String[] test07 = new String[] { "dog", "god", "cat" }; + public static String[] test07 = new String[]{"dog", "god", "cat"}; public static String result07 = "cc83646f6783676f6483636174"; public static int test08 = 1; @@ -46,14 +46,14 @@ public class RlpTestData { public static BigInteger test13 = new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639936"); public static String result13 = "a1010000000000000000000000000000000000000000000000000000000000000000"; - public static Object[] test14 = new Object[] { 1, 2, new Object[] {} }; + public static Object[] test14 = new Object[]{1, 2, new Object[]{}}; public static String result14 = "c30102c0"; - public static Object[] expected14 = new Object[] { new byte[] { 1 }, new byte[] { 2 }, new Object[] {} }; + public static Object[] expected14 = new Object[]{new byte[]{1}, new byte[]{2}, new Object[]{}}; - public static Object[] test15 = new Object[] { new Object[] { new Object[] {}, new Object[] {} }, new Object[] {} }; + public static Object[] test15 = new Object[]{new Object[]{new Object[]{}, new Object[]{}}, new Object[]{}}; public static String result15 = "c4c2c0c0c0"; - public static Object[] test16 = new Object[] { "zw", new Object[] { 4 }, "wz" }; + public static Object[] test16 = new Object[]{"zw", new Object[]{4}, "wz"}; public static String result16 = "c8827a77c10482777a"; public static Object[] expected16 = new Object[] { new byte[] { 122, 119 }, new Object[] { new byte[] { 4 } }, new byte[] { 119, 122 } }; } diff --git a/ethereumj-core/src/test/java/test/ethereum/util/UtilsTest.java b/ethereumj-core/src/test/java/test/ethereum/util/UtilsTest.java index 28b6cdc7..fe9df2dc 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/UtilsTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/UtilsTest.java @@ -11,6 +11,7 @@ import static org.junit.Assert.assertEquals; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 17/05/14 15:38 */ diff --git a/ethereumj-core/src/test/java/test/ethereum/util/ValueTest.java b/ethereumj-core/src/test/java/test/ethereum/util/ValueTest.java index b65f3069..35dcd270 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/ValueTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/ValueTest.java @@ -47,7 +47,7 @@ public class ValueTest { @Test - public void longListRLPBug_1(){ + public void longListRLPBug_1() { String testRlp = "f7808080d387206f72726563748a626574656c676575736580d387207870726573738a70726564696361626c658080808080808080808080"; @@ -57,5 +57,4 @@ public class ValueTest { } - } diff --git a/ethereumj-core/src/test/java/test/ethereum/vm/DataWordTest.java b/ethereumj-core/src/test/java/test/ethereum/vm/DataWordTest.java index 30c051b3..346d41b1 100644 --- a/ethereumj-core/src/test/java/test/ethereum/vm/DataWordTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/vm/DataWordTest.java @@ -14,11 +14,11 @@ public class DataWordTest { public void testAddPerformance() { boolean enabled = false; - if(enabled) { - byte[] one = new byte[] { 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, + if (enabled) { + byte[] one = new byte[]{0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, - 0x41, 0x01, 0x31, 0x54, 0x41 }; // Random value + 0x41, 0x01, 0x31, 0x54, 0x41}; // Random value int ITERATIONS = 10000000; @@ -230,7 +230,7 @@ public class DataWordTest { assertEquals(expected, x.toString()); } - @Test(expected=IndexOutOfBoundsException.class) + @Test(expected = IndexOutOfBoundsException.class) public void testSignExtendException1() { byte k = -1; @@ -239,7 +239,7 @@ public class DataWordTest { x.signExtend(k); // should throw an exception } - @Test(expected=IndexOutOfBoundsException.class) + @Test(expected = IndexOutOfBoundsException.class) public void testSignExtendException2() { byte k = 32; diff --git a/ethereumj-core/src/test/java/test/ethereum/vm/ProgramMemoryTest.java b/ethereumj-core/src/test/java/test/ethereum/vm/ProgramMemoryTest.java index 044984a1..6d319165 100644 --- a/ethereumj-core/src/test/java/test/ethereum/vm/ProgramMemoryTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/vm/ProgramMemoryTest.java @@ -287,7 +287,7 @@ public class ProgramMemoryTest { int offset = 16; int size = 32; program.allocateMemory(offset, size); - assertEquals(64 , program.getMemSize()); + assertEquals(64, program.getMemSize()); } @Test @@ -320,7 +320,7 @@ public class ProgramMemoryTest { int offset = 16; int size = 16; program.allocateMemory(offset, size); - assertEquals(32,program.getMemSize()); + assertEquals(32, program.getMemSize()); } @Test @@ -331,6 +331,6 @@ public class ProgramMemoryTest { int offset = 32; int size = 00; program.memorySave(32, 0, new byte[0]); - assertEquals(32,program.getMemSize()); + assertEquals(32, program.getMemSize()); } } \ No newline at end of file diff --git a/ethereumj-core/src/test/java/test/ethereum/vm/VMComplexTest.java b/ethereumj-core/src/test/java/test/ethereum/vm/VMComplexTest.java index 27d0f4e6..f42cedc1 100644 --- a/ethereumj-core/src/test/java/test/ethereum/vm/VMComplexTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/vm/VMComplexTest.java @@ -49,9 +49,10 @@ public class VMComplexTest { DataWord value1 = new DataWord(3); // Set contract into Database - String callerAddr = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826"; + String callerAddr = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826"; String contractAddr = "77045e71a7a2c50903d88e564cd72fab11e82051"; - String code = "6103e75460005260006000511115630000004c576001600051036103e755600060006000600060007377045e71a7a2c50903d88e564cd72fab11e820516008600a5a0402f1630000004c565b00"; + String code = + "6103e75460005260006000511115630000004c576001600051036103e755600060006000600060007377045e71a7a2c50903d88e564cd72fab11e820516008600a5a0402f1630000004c565b00"; byte[] contractAddrB = Hex.decode(contractAddr); byte[] callerAddrB = Hex.decode(callerAddr); @@ -61,7 +62,7 @@ public class VMComplexTest { AccountState accountState = new AccountState(); accountState.setCodeHash(codeKey); - ProgramInvokeMockImpl pi = new ProgramInvokeMockImpl(); + ProgramInvokeMockImpl pi = new ProgramInvokeMockImpl(); pi.setOwnerAddress(contractAddrB); Repository repository = pi.getRepository(); @@ -77,7 +78,7 @@ public class VMComplexTest { Program program = new Program(codeB, pi); try { - while(!program.isStopped()) + while (!program.isStopped()) vm.step(program); } catch (RuntimeException e) { program.setRuntimeFailure(e); @@ -123,7 +124,7 @@ public class VMComplexTest { long expectedVal_2 = 22; // Set contract into Database - String callerAddr = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826"; + String callerAddr = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826"; String contractA_addr = "77045e71a7a2c50903d88e564cd72fab11e82051"; String contractB_addr = "83c5541a6c8d2dbad642f385d8d06ca9b6c731ee"; @@ -139,7 +140,7 @@ public class VMComplexTest { byte[] contractB_addr_bytes = Hex.decode(contractB_addr); byte[] codeB = Hex.decode(code_b); - ProgramInvokeMockImpl pi = new ProgramInvokeMockImpl(); + ProgramInvokeMockImpl pi = new ProgramInvokeMockImpl(); pi.setOwnerAddress(contractB_addr_bytes); Repository repository = pi.getRepository(); @@ -160,7 +161,7 @@ public class VMComplexTest { Program program = new Program(codeB, pi); try { - while(!program.isStopped()) + while (!program.isStopped()) vm.step(program); } catch (RuntimeException e) { program.setRuntimeFailure(e); @@ -228,9 +229,9 @@ public class VMComplexTest { byte[] codeA = Hex.decode("600b60005260166020526021604052602c6060526037608052604260a05260c06000f2"); byte[] codeB = Hex.decode("6000601f5360e05960e05952600060c05901536060596020015980602001600b9052806040016016905280606001602190526080905260007377045e71a7a2c50903d88e564cd72fab11e820516103e8f1602060000260a00160200151600052"); - ProgramInvokeMockImpl pi = new ProgramInvokeMockImpl(); + ProgramInvokeMockImpl pi = new ProgramInvokeMockImpl(); pi.setOwnerAddress(contractB_addr_bytes); - Repository repository = pi.getRepository(); + Repository repository = pi.getRepository(); repository.createAccount(contractA_addr_bytes); repository.saveCode(contractA_addr_bytes, codeA); @@ -247,7 +248,7 @@ public class VMComplexTest { Program program = new Program(codeB, pi); try { - while(!program.isStopped()) + while (!program.isStopped()) vm.step(program); } catch (RuntimeException e) { program.setRuntimeFailure(e); @@ -304,11 +305,11 @@ public class VMComplexTest { byte[] contractA_addr_bytes = Hex.decode("77045e71a7a2c50903d88e564cd72fab11e82051"); byte[] codeA = Hex.decode("7f7f60c860005461012c602054000000000000" + - "00000000000000000000000000006000547e60" + - "005460206000f2000000000000000000000000" + - "0000000000000000000000602054602960006064f0"); + "00000000000000000000000000006000547e60" + + "005460206000f2000000000000000000000000" + + "0000000000000000000000602054602960006064f0"); - ProgramInvokeMockImpl pi = new ProgramInvokeMockImpl(); + ProgramInvokeMockImpl pi = new ProgramInvokeMockImpl(); pi.setOwnerAddress(contractA_addr_bytes); Repository repository = pi.getRepository(); @@ -374,11 +375,11 @@ public class VMComplexTest { byte[] codeA = Hex.decode("60003554156009570060203560003555"); byte[] codeB = Hex.decode("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6000527faaffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffaa6020526000604060406000601773945304eb96065b2a98b57a48a06ae28d285a71b5620f4240f3600055"); - ProgramInvokeMockImpl pi = new ProgramInvokeMockImpl(); + ProgramInvokeMockImpl pi = new ProgramInvokeMockImpl(); pi.setOwnerAddress(contractB_addr_bytes); pi.setGasLimit(10000000000000l); - Repository repository = pi.getRepository(); + Repository repository = pi.getRepository(); repository.createAccount(contractA_addr_bytes); repository.saveCode(contractA_addr_bytes, codeA); repository.addBalance(contractA_addr_bytes, BigInteger.valueOf(23)); @@ -397,7 +398,7 @@ public class VMComplexTest { Program program = new Program(codeB, pi); try { - while(!program.isStopped()) + while (!program.isStopped()) vm.step(program); } catch (RuntimeException e) { program.setRuntimeFailure(e); diff --git a/ethereumj-core/src/test/java/test/ethereum/vm/VMCustomTest.java b/ethereumj-core/src/test/java/test/ethereum/vm/VMCustomTest.java index c58908df..0cf576de 100644 --- a/ethereumj-core/src/test/java/test/ethereum/vm/VMCustomTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/vm/VMCustomTest.java @@ -19,6 +19,7 @@ import static org.junit.Assert.*; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 01/06/2014 11:05 */ @@ -33,7 +34,7 @@ public class VMCustomTest { public void setup() { byte[] ownerAddress = Hex.decode("77045E71A7A2C50903D88E564CD72FAB11E82051"); byte[] msgData = Hex.decode("00000000000000000000000000000000000000000000000000000000000000A1" + - "00000000000000000000000000000000000000000000000000000000000000B1"); + "00000000000000000000000000000000000000000000000000000000000000B1"); invoke = new ProgramInvokeMockImpl(msgData); invoke.setOwnerAddress(ownerAddress); @@ -138,7 +139,7 @@ public class VMCustomTest { assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - @Test(expected=RuntimeException.class) // CALLDATALOAD OP mal + @Test(expected = RuntimeException.class) // CALLDATALOAD OP mal public void testCALLDATALOAD_6() { VM vm = new VM(); @@ -174,7 +175,7 @@ public class VMCustomTest { program = new Program(Hex.decode("60406000600037"), invoke); String m_expected = "00000000000000000000000000000000000000000000000000000000000000A1" + - "00000000000000000000000000000000000000000000000000000000000000B1"; + "00000000000000000000000000000000000000000000000000000000000000B1"; vm.step(program); vm.step(program); @@ -192,7 +193,7 @@ public class VMCustomTest { program = new Program(Hex.decode("60406004600037"), invoke); String m_expected = "000000000000000000000000000000000000000000000000000000A100000000" + - "000000000000000000000000000000000000000000000000000000B100000000"; + "000000000000000000000000000000000000000000000000000000B100000000"; vm.step(program); vm.step(program); @@ -210,8 +211,8 @@ public class VMCustomTest { program = new Program(Hex.decode("60406000600437"), invoke); String m_expected = "0000000000000000000000000000000000000000000000000000000000000000" + - "000000A100000000000000000000000000000000000000000000000000000000" + - "000000B100000000000000000000000000000000000000000000000000000000"; + "000000A100000000000000000000000000000000000000000000000000000000" + + "000000B100000000000000000000000000000000000000000000000000000000"; vm.step(program); vm.step(program); @@ -228,8 +229,8 @@ public class VMCustomTest { program = new Program(Hex.decode("60406000600437"), invoke); String m_expected = "0000000000000000000000000000000000000000000000000000000000000000" + - "000000A100000000000000000000000000000000000000000000000000000000" + - "000000B100000000000000000000000000000000000000000000000000000000"; + "000000A100000000000000000000000000000000000000000000000000000000" + + "000000B100000000000000000000000000000000000000000000000000000000"; vm.step(program); vm.step(program); @@ -240,7 +241,7 @@ public class VMCustomTest { } - @Test(expected=StackTooSmallException.class) // CALLDATACOPY OP mal + @Test(expected = StackTooSmallException.class) // CALLDATACOPY OP mal public void testCALLDATACOPY_6() { VM vm = new VM(); @@ -256,7 +257,7 @@ public class VMCustomTest { } } - @Test(expected=OutOfGasException.class) // CALLDATACOPY OP mal + @Test(expected = OutOfGasException.class) // CALLDATACOPY OP mal public void testCALLDATACOPY_7() { VM vm = new VM(); @@ -382,7 +383,7 @@ public class VMCustomTest { assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // SHA3 OP mal + @Test(expected = StackTooSmallException.class) // SHA3 OP mal public void testSHA3_3() { VM vm = new VM(); @@ -511,7 +512,7 @@ public class VMCustomTest { assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - @Test(expected=Program.IllegalOperationException.class) // INVALID OP + @Test(expected = Program.IllegalOperationException.class) // INVALID OP public void testINVALID_1() { VM vm = new VM(); @@ -562,4 +563,4 @@ public class VMCustomTest { RETURN f2 (1) 61778e600054 -*/ + */ diff --git a/ethereumj-core/src/test/java/test/ethereum/vm/VMTest.java b/ethereumj-core/src/test/java/test/ethereum/vm/VMTest.java index daa5ed62..d0be43c5 100644 --- a/ethereumj-core/src/test/java/test/ethereum/vm/VMTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/vm/VMTest.java @@ -19,6 +19,7 @@ import static org.junit.Assert.*; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 01/06/2014 11:05 */ @@ -49,7 +50,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH2 OP @@ -62,7 +63,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH3 OP @@ -75,7 +76,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH4 OP @@ -88,7 +89,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH5 OP @@ -101,7 +102,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH6 OP @@ -114,7 +115,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH7 OP @@ -127,7 +128,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH8 OP @@ -140,7 +141,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH9 OP @@ -153,7 +154,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @@ -167,7 +168,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH11 OP @@ -180,7 +181,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH12 OP @@ -193,7 +194,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH13 OP @@ -206,7 +207,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH14 OP @@ -219,7 +220,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH15 OP @@ -232,7 +233,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH16 OP @@ -245,7 +246,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH17 OP @@ -258,7 +259,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH18 OP @@ -271,7 +272,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH19 OP @@ -284,7 +285,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH20 OP @@ -297,7 +298,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH21 OP @@ -310,7 +311,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH22 OP @@ -323,7 +324,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH23 OP @@ -336,7 +337,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH24 OP @@ -349,7 +350,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH25 OP @@ -362,7 +363,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH26 OP @@ -375,7 +376,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH27 OP @@ -388,7 +389,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH28 OP @@ -401,7 +402,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH29 OP @@ -414,7 +415,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH30 OP @@ -427,7 +428,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH31 OP @@ -440,7 +441,7 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSH32 OP @@ -453,14 +454,14 @@ public class VMTest { program.fullTrace(); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // PUSHN OP not enough data public void testPUSHN_1() { VM vm = new VM(); - program = new Program(Hex.decode("61AA"), invoke); + program = new Program(Hex.decode("61AA"), invoke); String expected = "000000000000000000000000000000000000000000000000000000000000AA00"; program.fullTrace(); @@ -474,7 +475,7 @@ public class VMTest { public void testPUSHN_2() { VM vm = new VM(); - program = new Program(Hex.decode("7fAABB"), invoke); + program = new Program(Hex.decode("7fAABB"), invoke); String expected = "AABB000000000000000000000000000000000000000000000000000000000000"; program.fullTrace(); @@ -488,7 +489,7 @@ public class VMTest { public void testAND_1() { VM vm = new VM(); - program = new Program(Hex.decode("600A600A16"), invoke); + program = new Program(Hex.decode("600A600A16"), invoke); String expected = "000000000000000000000000000000000000000000000000000000000000000A"; vm.step(program); @@ -502,21 +503,21 @@ public class VMTest { public void testAND_2() { VM vm = new VM(); - program = new Program(Hex.decode("60C0600A16"), invoke); + program = new Program(Hex.decode("60C0600A16"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); vm.step(program); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=RuntimeException.class) // AND OP mal data + @Test(expected = RuntimeException.class) // AND OP mal data public void testAND_3() { VM vm = new VM(); - program = new Program(Hex.decode("60C016"), invoke); + program = new Program(Hex.decode("60C016"), invoke); try { vm.step(program); vm.step(program); @@ -530,35 +531,35 @@ public class VMTest { public void testOR_1() { VM vm = new VM(); - program = new Program(Hex.decode("60F0600F17"), invoke); + program = new Program(Hex.decode("60F0600F17"), invoke); String expected = "00000000000000000000000000000000000000000000000000000000000000FF"; vm.step(program); vm.step(program); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // OR OP public void testOR_2() { VM vm = new VM(); - program = new Program(Hex.decode("60C3603C17"), invoke); + program = new Program(Hex.decode("60C3603C17"), invoke); String expected = "00000000000000000000000000000000000000000000000000000000000000FF"; vm.step(program); vm.step(program); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=RuntimeException.class) // OR OP mal data + @Test(expected = RuntimeException.class) // OR OP mal data public void testOR_3() { VM vm = new VM(); - program = new Program(Hex.decode("60C017"), invoke); + program = new Program(Hex.decode("60C017"), invoke); try { vm.step(program); vm.step(program); @@ -572,36 +573,36 @@ public class VMTest { public void testXOR_1() { VM vm = new VM(); - program = new Program(Hex.decode("60FF60FF18"), invoke); + program = new Program(Hex.decode("60FF60FF18"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); vm.step(program); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // XOR OP public void testXOR_2() { VM vm = new VM(); - program = new Program(Hex.decode("600F60F018"), invoke); + program = new Program(Hex.decode("600F60F018"), invoke); String expected = "00000000000000000000000000000000000000000000000000000000000000FF"; vm.step(program); vm.step(program); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=RuntimeException.class) // XOR OP mal data + @Test(expected = RuntimeException.class) // XOR OP mal data public void testXOR_3() { VM vm = new VM(); - program = new Program(Hex.decode("60C018"), invoke); + program = new Program(Hex.decode("60C018"), invoke); try { vm.step(program); vm.step(program); @@ -615,50 +616,50 @@ public class VMTest { public void testBYTE_1() { VM vm = new VM(); - program = new Program(Hex.decode("65AABBCCDDEEFF601E1A"), invoke); + program = new Program(Hex.decode("65AABBCCDDEEFF601E1A"), invoke); String expected = "00000000000000000000000000000000000000000000000000000000000000EE"; vm.step(program); vm.step(program); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // BYTE OP public void testBYTE_2() { VM vm = new VM(); - program = new Program(Hex.decode("65AABBCCDDEEFF60201A"), invoke); + program = new Program(Hex.decode("65AABBCCDDEEFF60201A"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); vm.step(program); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // BYTE OP public void testBYTE_3() { VM vm = new VM(); - program = new Program(Hex.decode("65AABBCCDDEE3A601F1A"), invoke); + program = new Program(Hex.decode("65AABBCCDDEE3A601F1A"), invoke); String expected = "000000000000000000000000000000000000000000000000000000000000003A"; vm.step(program); vm.step(program); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // BYTE OP mal data + @Test(expected = StackTooSmallException.class) // BYTE OP mal data public void testBYTE_4() { VM vm = new VM(); - program = new Program(Hex.decode("65AABBCCDDEE3A1A"), invoke); + program = new Program(Hex.decode("65AABBCCDDEE3A1A"), invoke); try { vm.step(program); vm.step(program); @@ -672,33 +673,33 @@ public class VMTest { public void testISZERO_1() { VM vm = new VM(); - program = new Program(Hex.decode("600015"), invoke); + program = new Program(Hex.decode("600015"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // ISZERO OP public void testISZERO_2() { VM vm = new VM(); - program = new Program(Hex.decode("602A15"), invoke); + program = new Program(Hex.decode("602A15"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // ISZERO OP mal data + @Test(expected = StackTooSmallException.class) // ISZERO OP mal data public void testISZERO_3() { VM vm = new VM(); - program = new Program(Hex.decode("15"), invoke); + program = new Program(Hex.decode("15"), invoke); try { vm.step(program); vm.step(program); @@ -712,35 +713,35 @@ public class VMTest { public void testEQ_1() { VM vm = new VM(); - program = new Program(Hex.decode("602A602A14"), invoke); + program = new Program(Hex.decode("602A602A14"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); vm.step(program); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // EQ OP public void testEQ_2() { VM vm = new VM(); - program = new Program(Hex.decode("622A3B4C622A3B4C14"), invoke); + program = new Program(Hex.decode("622A3B4C622A3B4C14"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); vm.step(program); vm.step(program); - assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase() ); + assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } @Test // EQ OP public void testEQ_3() { VM vm = new VM(); - program = new Program(Hex.decode("622A3B5C622A3B4C14"), invoke); + program = new Program(Hex.decode("622A3B5C622A3B4C14"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -750,11 +751,11 @@ public class VMTest { assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // EQ OP mal data + @Test(expected = StackTooSmallException.class) // EQ OP mal data public void testEQ_4() { VM vm = new VM(); - program = new Program(Hex.decode("622A3B4C14"), invoke); + program = new Program(Hex.decode("622A3B4C14"), invoke); try { vm.step(program); vm.step(program); @@ -768,7 +769,7 @@ public class VMTest { public void testGT_1() { VM vm = new VM(); - program = new Program(Hex.decode("6001600211"), invoke); + program = new Program(Hex.decode("6001600211"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); @@ -782,7 +783,7 @@ public class VMTest { public void testGT_2() { VM vm = new VM(); - program = new Program(Hex.decode("6001610F0011"), invoke); + program = new Program(Hex.decode("6001610F0011"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); @@ -796,7 +797,7 @@ public class VMTest { public void testGT_3() { VM vm = new VM(); - program = new Program(Hex.decode("6301020304610F0011"), invoke); + program = new Program(Hex.decode("6301020304610F0011"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -806,11 +807,11 @@ public class VMTest { assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // GT OP mal data + @Test(expected = StackTooSmallException.class) // GT OP mal data public void testGT_4() { VM vm = new VM(); - program = new Program(Hex.decode("622A3B4C11"), invoke); + program = new Program(Hex.decode("622A3B4C11"), invoke); try { vm.step(program); vm.step(program); @@ -824,7 +825,7 @@ public class VMTest { public void testSGT_1() { VM vm = new VM(); - program = new Program(Hex.decode("6001600213"), invoke); + program = new Program(Hex.decode("6001600213"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); @@ -838,9 +839,9 @@ public class VMTest { public void testSGT_2() { VM vm = new VM(); - program = new Program(Hex.decode("7F000000000000000000000000000000000000000000000000000000000000001E" + // 30 - "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 - "13"), invoke); + program = new Program(Hex.decode("7F000000000000000000000000000000000000000000000000000000000000001E" + // 30 + "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 + "13"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; @@ -855,9 +856,9 @@ public class VMTest { public void testSGT_3() { VM vm = new VM(); - program = new Program(Hex.decode("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 - "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF57" + // -169 - "13"), invoke); + program = new Program(Hex.decode("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 + "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF57" + // -169 + "13"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000001"; @@ -868,12 +869,12 @@ public class VMTest { assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // SGT OP mal + @Test(expected = StackTooSmallException.class) // SGT OP mal public void testSGT_4() { VM vm = new VM(); - program = new Program(Hex.decode("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 - "13"), invoke); + program = new Program(Hex.decode("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 + "13"), invoke); try { vm.step(program); vm.step(program); @@ -887,7 +888,7 @@ public class VMTest { public void testLT_1() { VM vm = new VM(); - program = new Program(Hex.decode("6001600210"), invoke); + program = new Program(Hex.decode("6001600210"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -901,7 +902,7 @@ public class VMTest { public void testLT_2() { VM vm = new VM(); - program = new Program(Hex.decode("6001610F0010"), invoke); + program = new Program(Hex.decode("6001610F0010"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -915,7 +916,7 @@ public class VMTest { public void testLT_3() { VM vm = new VM(); - program = new Program(Hex.decode("6301020304610F0010"), invoke); + program = new Program(Hex.decode("6301020304610F0010"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); @@ -925,11 +926,11 @@ public class VMTest { assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // LT OP mal data + @Test(expected = StackTooSmallException.class) // LT OP mal data public void testLT_4() { VM vm = new VM(); - program = new Program(Hex.decode("622A3B4C10"), invoke); + program = new Program(Hex.decode("622A3B4C10"), invoke); try { vm.step(program); vm.step(program); @@ -943,7 +944,7 @@ public class VMTest { public void testSLT_1() { VM vm = new VM(); - program = new Program(Hex.decode("6001600212"), invoke); + program = new Program(Hex.decode("6001600212"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -957,9 +958,9 @@ public class VMTest { public void testSLT_2() { VM vm = new VM(); - program = new Program(Hex.decode("7F000000000000000000000000000000000000000000000000000000000000001E" + // 30 - "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 - "12"), invoke); + program = new Program(Hex.decode("7F000000000000000000000000000000000000000000000000000000000000001E" + // 30 + "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 + "12"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000001"; @@ -974,9 +975,9 @@ public class VMTest { public void testSLT_3() { VM vm = new VM(); - program = new Program(Hex.decode("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 - "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF57" + // -169 - "12"), invoke); + program = new Program(Hex.decode("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 + "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF57" + // -169 + "12"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; @@ -987,11 +988,11 @@ public class VMTest { assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // SLT OP mal + @Test(expected = StackTooSmallException.class) // SLT OP mal public void testSLT_4() { VM vm = new VM(); - program = new Program(Hex.decode("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 + program = new Program(Hex.decode("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 "12"), invoke); try { vm.step(program); @@ -1006,7 +1007,7 @@ public class VMTest { public void testNOT_1() { VM vm = new VM(); - program = new Program(Hex.decode("600119"), invoke); + program = new Program(Hex.decode("600119"), invoke); String expected = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE"; vm.step(program); @@ -1019,7 +1020,7 @@ public class VMTest { public void testNOT_2() { VM vm = new VM(); - program = new Program(Hex.decode("61A00319"), invoke); + program = new Program(Hex.decode("61A00319"), invoke); String expected = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5FFC"; vm.step(program); @@ -1032,7 +1033,7 @@ public class VMTest { public void testNOT_3() { VM vm = new VM(); - program = new Program(Hex.decode("61000019"), invoke); + program = new Program(Hex.decode("61000019"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -1041,11 +1042,11 @@ public class VMTest { assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // BNOT OP + @Test(expected = StackTooSmallException.class) // BNOT OP public void testBNOT_4() { VM vm = new VM(); - program = new Program(Hex.decode("1a"), invoke); + program = new Program(Hex.decode("1a"), invoke); try { vm.step(program); vm.step(program); @@ -1058,7 +1059,7 @@ public class VMTest { public void testPOP_1() { VM vm = new VM(); - program = new Program(Hex.decode("61000060016200000250"), invoke); + program = new Program(Hex.decode("61000060016200000250"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); @@ -1073,7 +1074,7 @@ public class VMTest { public void testPOP_2() { VM vm = new VM(); - program = new Program(Hex.decode("6100006001620000025050"), invoke); + program = new Program(Hex.decode("6100006001620000025050"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -1085,11 +1086,11 @@ public class VMTest { assertEquals(expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // POP OP mal data + @Test(expected = StackTooSmallException.class) // POP OP mal data public void testPOP_3() { VM vm = new VM(); - program = new Program(Hex.decode("61000060016200000250505050"), invoke); + program = new Program(Hex.decode("61000060016200000250505050"), invoke); try { vm.step(program); vm.step(program); @@ -1123,9 +1124,9 @@ public class VMTest { for (int i = 0; i < n; i++) { programCode += "60" + (12 + i); } - program = new Program(ByteUtil.appendByte(Hex.decode(programCode.getBytes()), operation), invoke); - String expected = "0000000000000000000000000000000000000000000000000000000000000012"; - int expectedLen = n + 1; + program = new Program(ByteUtil.appendByte(Hex.decode(programCode.getBytes()), operation), invoke); + String expected = "0000000000000000000000000000000000000000000000000000000000000012"; + int expectedLen = n + 1; for (int i = 0; i < expectedLen; i++) { vm.step(program); @@ -1133,17 +1134,17 @@ public class VMTest { assertEquals(expectedLen, program.getStack().toArray().length); assertEquals(expected, Hex.toHexString(program.stackPop().getData()).toUpperCase()); - for (int i = 0; i < expectedLen-2; i++) { + for (int i = 0; i < expectedLen - 2; i++) { assertNotEquals(expected, Hex.toHexString(program.stackPop().getData()).toUpperCase()); } assertEquals(expected, Hex.toHexString(program.stackPop().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // DUPN OP mal data + @Test(expected = StackTooSmallException.class) // DUPN OP mal data public void testDUPN_2() { VM vm = new VM(); - program = new Program(Hex.decode("80"), invoke); + program = new Program(Hex.decode("80"), invoke); try { vm.step(program); } finally { @@ -1170,10 +1171,10 @@ public class VMTest { String[] expected = new String[n + 1]; String programCode = ""; for (int i = 0; i < expected.length; i++) { - programCode += "60" + (11+i); - expected[i] = "00000000000000000000000000000000000000000000000000000000000000" + (11+i); + programCode += "60" + (11 + i); + expected[i] = "00000000000000000000000000000000000000000000000000000000000000" + (11 + i); } - program = new Program(ByteUtil.appendByte(Hex.decode(programCode), operation), invoke); + program = new Program(ByteUtil.appendByte(Hex.decode(programCode), operation), invoke); for (int i = 0; i <= expected.length; i++) { vm.step(program); @@ -1181,17 +1182,17 @@ public class VMTest { assertEquals(expected.length, program.getStack().toArray().length); assertEquals(expected[0], Hex.toHexString(program.stackPop().getData()).toUpperCase()); - for (int i = expected.length-2; i > 0; i--) { + for (int i = expected.length - 2; i > 0; i--) { assertEquals(expected[i], Hex.toHexString(program.stackPop().getData()).toUpperCase()); } - assertEquals(expected[expected.length-1], Hex.toHexString(program.stackPop().getData()).toUpperCase()); + assertEquals(expected[expected.length - 1], Hex.toHexString(program.stackPop().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // SWAPN OP mal data + @Test(expected = StackTooSmallException.class) // SWAPN OP mal data public void testSWAPN_2() { VM vm = new VM(); - program = new Program(Hex.decode("90"), invoke); + program = new Program(Hex.decode("90"), invoke); try { vm.step(program); @@ -1204,7 +1205,7 @@ public class VMTest { public void testMSTORE_1() { VM vm = new VM(); - program = new Program(Hex.decode("611234600052"), invoke); + program = new Program(Hex.decode("611234600052"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000001234"; vm.step(program); @@ -1216,10 +1217,10 @@ public class VMTest { @Test // LOG0 OP - public void tesLog0(){ + public void tesLog0() { VM vm = new VM(); - program = new Program(Hex.decode("61123460005260206000A0"), invoke); + program = new Program(Hex.decode("61123460005260206000A0"), invoke); vm.step(program); vm.step(program); @@ -1228,19 +1229,20 @@ public class VMTest { vm.step(program); vm.step(program); - List logInfoList = program.getResult().getLogInfoList(); + List logInfoList = program.getResult().getLogInfoList(); LogInfo logInfo = logInfoList.get(0); assertEquals("cd2a3d9f938e13cd947ec05abc7fe734df8dd826", Hex.toHexString(logInfo.getAddress())); assertEquals(0, logInfo.getTopics().size()); - assertEquals("0000000000000000000000000000000000000000000000000000000000001234", Hex.toHexString(logInfo.getData())); + assertEquals("0000000000000000000000000000000000000000000000000000000000001234", Hex.toHexString(logInfo + .getData())); } @Test // LOG1 OP - public void tesLog1(){ + public void tesLog1() { VM vm = new VM(); - program = new Program(Hex.decode("61123460005261999960206000A1"), invoke); + program = new Program(Hex.decode("61123460005261999960206000A1"), invoke); vm.step(program); vm.step(program); @@ -1250,19 +1252,20 @@ public class VMTest { vm.step(program); vm.step(program); - List logInfoList = program.getResult().getLogInfoList(); + List logInfoList = program.getResult().getLogInfoList(); LogInfo logInfo = logInfoList.get(0); assertEquals("cd2a3d9f938e13cd947ec05abc7fe734df8dd826", Hex.toHexString(logInfo.getAddress())); assertEquals(1, logInfo.getTopics().size()); - assertEquals("0000000000000000000000000000000000000000000000000000000000001234", Hex.toHexString(logInfo.getData())); + assertEquals("0000000000000000000000000000000000000000000000000000000000001234", Hex.toHexString(logInfo + .getData())); } @Test // LOG2 OP - public void tesLog2(){ + public void tesLog2() { VM vm = new VM(); - program = new Program(Hex.decode("61123460005261999961666660206000A2"), invoke); + program = new Program(Hex.decode("61123460005261999961666660206000A2"), invoke); vm.step(program); vm.step(program); @@ -1273,19 +1276,20 @@ public class VMTest { vm.step(program); vm.step(program); - List logInfoList = program.getResult().getLogInfoList(); + List logInfoList = program.getResult().getLogInfoList(); LogInfo logInfo = logInfoList.get(0); assertEquals("cd2a3d9f938e13cd947ec05abc7fe734df8dd826", Hex.toHexString(logInfo.getAddress())); assertEquals(2, logInfo.getTopics().size()); - assertEquals("0000000000000000000000000000000000000000000000000000000000001234", Hex.toHexString(logInfo.getData())); + assertEquals("0000000000000000000000000000000000000000000000000000000000001234", Hex.toHexString(logInfo + .getData())); } @Test // LOG3 OP - public void tesLog3(){ + public void tesLog3() { VM vm = new VM(); - program = new Program(Hex.decode("61123460005261999961666661333360206000A3"), invoke); + program = new Program(Hex.decode("61123460005261999961666661333360206000A3"), invoke); vm.step(program); vm.step(program); @@ -1297,20 +1301,21 @@ public class VMTest { vm.step(program); vm.step(program); - List logInfoList = program.getResult().getLogInfoList(); + List logInfoList = program.getResult().getLogInfoList(); LogInfo logInfo = logInfoList.get(0); assertEquals("cd2a3d9f938e13cd947ec05abc7fe734df8dd826", Hex.toHexString(logInfo.getAddress())); assertEquals(3, logInfo.getTopics().size()); - assertEquals("0000000000000000000000000000000000000000000000000000000000001234", Hex.toHexString(logInfo.getData())); + assertEquals("0000000000000000000000000000000000000000000000000000000000001234", Hex.toHexString(logInfo + .getData())); } @Test // LOG4 OP - public void tesLog4(){ + public void tesLog4() { VM vm = new VM(); - program = new Program(Hex.decode("61123460005261999961666661333361555560206000A4"), invoke); + program = new Program(Hex.decode("61123460005261999961666661333361555560206000A4"), invoke); vm.step(program); vm.step(program); @@ -1323,23 +1328,23 @@ public class VMTest { vm.step(program); vm.step(program); - List logInfoList = program.getResult().getLogInfoList(); + List logInfoList = program.getResult().getLogInfoList(); LogInfo logInfo = logInfoList.get(0); assertEquals("cd2a3d9f938e13cd947ec05abc7fe734df8dd826", Hex.toHexString(logInfo.getAddress())); assertEquals(4, logInfo.getTopics().size()); - assertEquals("0000000000000000000000000000000000000000000000000000000000001234", Hex.toHexString(logInfo.getData())); + assertEquals("0000000000000000000000000000000000000000000000000000000000001234", Hex.toHexString(logInfo + .getData())); } - @Test // MSTORE OP public void testMSTORE_2() { VM vm = new VM(); - program = new Program(Hex.decode("611234600052615566602052"), invoke); + program = new Program(Hex.decode("611234600052615566602052"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000001234" + - "0000000000000000000000000000000000000000000000000000000000005566"; + "0000000000000000000000000000000000000000000000000000000000005566"; vm.step(program); vm.step(program); @@ -1355,9 +1360,9 @@ public class VMTest { public void testMSTORE_3() { VM vm = new VM(); - program = new Program(Hex.decode("611234600052615566602052618888600052"), invoke); + program = new Program(Hex.decode("611234600052615566602052618888600052"), invoke); String expected = "0000000000000000000000000000000000000000000000000000000000008888" + - "0000000000000000000000000000000000000000000000000000000000005566"; + "0000000000000000000000000000000000000000000000000000000000005566"; vm.step(program); vm.step(program); @@ -1376,7 +1381,7 @@ public class VMTest { public void testMSTORE_4() { VM vm = new VM(); - program = new Program(Hex.decode("61123460A052"), invoke); + program = new Program(Hex.decode("61123460A052"), invoke); String expected = "" + "0000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000" + @@ -1392,11 +1397,11 @@ public class VMTest { assertEquals(expected, Hex.toHexString(program.getMemory().array())); } - @Test(expected=StackTooSmallException.class) // MSTORE OP + @Test(expected = StackTooSmallException.class) // MSTORE OP public void testMSTORE_5() { VM vm = new VM(); - program = new Program(Hex.decode("61123452"), invoke); + program = new Program(Hex.decode("61123452"), invoke); try { vm.step(program); vm.step(program); @@ -1409,7 +1414,7 @@ public class VMTest { public void testMLOAD_1() { VM vm = new VM(); - program = new Program(Hex.decode("600051"), invoke); + program = new Program(Hex.decode("600051"), invoke); String m_expected = "0000000000000000000000000000000000000000000000000000000000000000"; String s_expected = "0000000000000000000000000000000000000000000000000000000000000000"; @@ -1424,10 +1429,10 @@ public class VMTest { public void testMLOAD_2() { VM vm = new VM(); - program = new Program(Hex.decode("602251"), invoke); + program = new Program(Hex.decode("602251"), invoke); String m_expected = "0000000000000000000000000000000000000000000000000000000000000000" + - "0000000000000000000000000000000000000000000000000000000000000000" + - "0000000000000000000000000000000000000000000000000000000000000000"; + "0000000000000000000000000000000000000000000000000000000000000000" + + "0000000000000000000000000000000000000000000000000000000000000000"; String s_expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -1442,9 +1447,9 @@ public class VMTest { public void testMLOAD_3() { VM vm = new VM(); - program = new Program(Hex.decode("602051"), invoke); + program = new Program(Hex.decode("602051"), invoke); String m_expected = "0000000000000000000000000000000000000000000000000000000000000000" + - "0000000000000000000000000000000000000000000000000000000000000000"; + "0000000000000000000000000000000000000000000000000000000000000000"; String s_expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -1458,9 +1463,9 @@ public class VMTest { public void testMLOAD_4() { VM vm = new VM(); - program = new Program(Hex.decode("611234602052602051"), invoke); + program = new Program(Hex.decode("611234602052602051"), invoke); String m_expected = "0000000000000000000000000000000000000000000000000000000000000000" + - "0000000000000000000000000000000000000000000000000000000000001234"; + "0000000000000000000000000000000000000000000000000000000000001234"; String s_expected = "0000000000000000000000000000000000000000000000000000000000001234"; vm.step(program); @@ -1477,9 +1482,9 @@ public class VMTest { public void testMLOAD_5() { VM vm = new VM(); - program = new Program(Hex.decode("611234602052601F51"), invoke); + program = new Program(Hex.decode("611234602052601F51"), invoke); String m_expected = "0000000000000000000000000000000000000000000000000000000000000000" + - "0000000000000000000000000000000000000000000000000000000000001234"; + "0000000000000000000000000000000000000000000000000000000000001234"; String s_expected = "0000000000000000000000000000000000000000000000000000000000000012"; vm.step(program); @@ -1492,11 +1497,11 @@ public class VMTest { assertEquals(s_expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // MLOAD OP mal data + @Test(expected = StackTooSmallException.class) // MLOAD OP mal data public void testMLOAD_6() { VM vm = new VM(); - program = new Program(Hex.decode("51"), invoke); + program = new Program(Hex.decode("51"), invoke); try { vm.step(program); } finally { @@ -1508,7 +1513,7 @@ public class VMTest { public void testMSTORE8_1() { VM vm = new VM(); - program = new Program(Hex.decode("6011600053"), invoke); + program = new Program(Hex.decode("6011600053"), invoke); String m_expected = "1100000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -1523,7 +1528,7 @@ public class VMTest { public void testMSTORE8_2() { VM vm = new VM(); - program = new Program(Hex.decode("6022600153"), invoke); + program = new Program(Hex.decode("6022600153"), invoke); String m_expected = "0022000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -1537,9 +1542,9 @@ public class VMTest { public void testMSTORE8_3() { VM vm = new VM(); - program = new Program(Hex.decode("6022602153"), invoke); + program = new Program(Hex.decode("6022602153"), invoke); String m_expected = "0000000000000000000000000000000000000000000000000000000000000000" + - "0022000000000000000000000000000000000000000000000000000000000000"; + "0022000000000000000000000000000000000000000000000000000000000000"; vm.step(program); vm.step(program); @@ -1548,11 +1553,11 @@ public class VMTest { assertEquals(m_expected, Hex.toHexString(program.getMemory().array())); } - @Test(expected=StackTooSmallException.class) // MSTORE8 OP mal + @Test(expected = StackTooSmallException.class) // MSTORE8 OP mal public void testMSTORE8_4() { VM vm = new VM(); - program = new Program(Hex.decode("602253"), invoke); + program = new Program(Hex.decode("602253"), invoke); try { vm.step(program); vm.step(program); @@ -1566,7 +1571,7 @@ public class VMTest { VM vm = new VM(); - program = new Program(Hex.decode("602260AA55"), invoke); + program = new Program(Hex.decode("602260AA55"), invoke); String s_expected_key = "00000000000000000000000000000000000000000000000000000000000000AA"; String s_expected_val = "0000000000000000000000000000000000000000000000000000000000000022"; @@ -1575,7 +1580,8 @@ public class VMTest { vm.step(program); DataWord key = new DataWord(Hex.decode(s_expected_key)); - DataWord val = program.getResult().getRepository().getStorageValue(invoke.getOwnerAddress().getNoLeadZeroesData(), key); + DataWord val = program.getResult().getRepository().getStorageValue(invoke.getOwnerAddress() + .getNoLeadZeroesData(), key); assertEquals(s_expected_val, Hex.toHexString(val.getData()).toUpperCase()); } @@ -1585,7 +1591,7 @@ public class VMTest { VM vm = new VM(); - program = new Program(Hex.decode("602260AA55602260BB55"), invoke); + program = new Program(Hex.decode("602260AA55602260BB55"), invoke); String s_expected_key = "00000000000000000000000000000000000000000000000000000000000000BB"; String s_expected_val = "0000000000000000000000000000000000000000000000000000000000000022"; @@ -1598,16 +1604,16 @@ public class VMTest { Repository repository = program.getResult().getRepository(); DataWord key = new DataWord(Hex.decode(s_expected_key)); - DataWord val = repository.getStorageValue(invoke.getOwnerAddress().getNoLeadZeroesData(), key); + DataWord val = repository.getStorageValue(invoke.getOwnerAddress().getNoLeadZeroesData(), key); assertEquals(s_expected_val, Hex.toHexString(val.getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // SSTORE OP + @Test(expected = StackTooSmallException.class) // SSTORE OP public void testSSTORE_3() { VM vm = new VM(); - program = new Program(Hex.decode("602255"), invoke); + program = new Program(Hex.decode("602255"), invoke); try { vm.step(program); vm.step(program); @@ -1620,7 +1626,7 @@ public class VMTest { public void testSLOAD_1() { VM vm = new VM(); - program = new Program(Hex.decode("60AA54"), invoke); + program = new Program(Hex.decode("60AA54"), invoke); String s_expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -1633,7 +1639,7 @@ public class VMTest { public void testSLOAD_2() { VM vm = new VM(); - program = new Program(Hex.decode("602260AA5560AA54"), invoke); + program = new Program(Hex.decode("602260AA5560AA54"), invoke); String s_expected = "0000000000000000000000000000000000000000000000000000000000000022"; vm.step(program); @@ -1649,7 +1655,7 @@ public class VMTest { public void testSLOAD_3() { VM vm = new VM(); - program = new Program(Hex.decode("602260AA55603360CC5560CC54"), invoke); + program = new Program(Hex.decode("602260AA55603360CC5560CC54"), invoke); String s_expected = "0000000000000000000000000000000000000000000000000000000000000033"; vm.step(program); @@ -1664,11 +1670,11 @@ public class VMTest { assertEquals(s_expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // SLOAD OP + @Test(expected = StackTooSmallException.class) // SLOAD OP public void testSLOAD_4() { VM vm = new VM(); - program = new Program(Hex.decode("56"), invoke); + program = new Program(Hex.decode("56"), invoke); try { vm.step(program); } finally { @@ -1680,7 +1686,7 @@ public class VMTest { public void testPC_1() { VM vm = new VM(); - program = new Program(Hex.decode("58"), invoke); + program = new Program(Hex.decode("58"), invoke); String s_expected = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -1693,7 +1699,7 @@ public class VMTest { public void testPC_2() { VM vm = new VM(); - program = new Program(Hex.decode("602260AA5260AA5458"), invoke); + program = new Program(Hex.decode("602260AA5260AA5458"), invoke); String s_expected = "0000000000000000000000000000000000000000000000000000000000000008"; vm.step(program); @@ -1710,7 +1716,7 @@ public class VMTest { public void testJUMP_1() { VM vm = new VM(); - program = new Program(Hex.decode("60AA60BB600E5660CC60DD60EE5B60FF"), invoke); + program = new Program(Hex.decode("60AA60BB600E5660CC60DD60EE5B60FF"), invoke); String s_expected = "00000000000000000000000000000000000000000000000000000000000000FF"; vm.step(program); @@ -1722,11 +1728,11 @@ public class VMTest { assertEquals(s_expected, Hex.toHexString(program.getStack().peek().getData()).toUpperCase()); } - @Test(expected=BadJumpDestinationException.class) // JUMP OP mal data + @Test(expected = BadJumpDestinationException.class) // JUMP OP mal data public void testJUMP_2() { VM vm = new VM(); - program = new Program(Hex.decode("600C600C905660CC60DD60EE60FF"), invoke); + program = new Program(Hex.decode("600C600C905660CC60DD60EE60FF"), invoke); try { vm.step(program); vm.step(program); @@ -1741,7 +1747,7 @@ public class VMTest { public void testJUMPI_1() { VM vm = new VM(); - program = new Program(Hex.decode("60016005575B60CC"), invoke); + program = new Program(Hex.decode("60016005575B60CC"), invoke); String s_expected = "00000000000000000000000000000000000000000000000000000000000000CC"; vm.step(program); @@ -1758,7 +1764,7 @@ public class VMTest { public void testJUMPI_2() { VM vm = new VM(); - program = new Program(Hex.decode("630000000060445760CC60DD"), invoke); + program = new Program(Hex.decode("630000000060445760CC60DD"), invoke); String s_expected_1 = "00000000000000000000000000000000000000000000000000000000000000DD"; String s_expected_2 = "00000000000000000000000000000000000000000000000000000000000000CC"; @@ -1775,11 +1781,11 @@ public class VMTest { assertEquals(s_expected_2, Hex.toHexString(item2.getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // JUMPI OP mal + @Test(expected = StackTooSmallException.class) // JUMPI OP mal public void testJUMPI_3() { VM vm = new VM(); - program = new Program(Hex.decode("600157"), invoke); + program = new Program(Hex.decode("600157"), invoke); try { vm.step(program); vm.step(program); @@ -1788,11 +1794,11 @@ public class VMTest { } } - @Test(expected=BadJumpDestinationException.class) // JUMPI OP mal + @Test(expected = BadJumpDestinationException.class) // JUMPI OP mal public void testJUMPI_4() { VM vm = new VM(); - program = new Program(Hex.decode("60016022909057"), invoke); + program = new Program(Hex.decode("60016022909057"), invoke); try { vm.step(program); vm.step(program); @@ -1808,7 +1814,7 @@ public class VMTest { public void testJUMPDEST_1() { VM vm = new VM(); - program = new Program(Hex.decode("602360085660015b600255"), invoke); + program = new Program(Hex.decode("602360085660015b600255"), invoke); String s_expected_key = "0000000000000000000000000000000000000000000000000000000000000002"; String s_expected_val = "0000000000000000000000000000000000000000000000000000000000000023"; @@ -1820,7 +1826,8 @@ public class VMTest { vm.step(program); DataWord key = new DataWord(Hex.decode(s_expected_key)); - DataWord val = program.getResult().getRepository().getStorageValue(invoke.getOwnerAddress().getNoLeadZeroesData(), key); + DataWord val = program.getResult().getRepository().getStorageValue(invoke.getOwnerAddress() + .getNoLeadZeroesData(), key); assertTrue(program.isStopped()); assertEquals(s_expected_val, Hex.toHexString(val.getData()).toUpperCase()); @@ -1830,7 +1837,7 @@ public class VMTest { public void testJUMPDEST_2() { VM vm = new VM(); - program = new Program(Hex.decode("6023600160095760015b600255"), invoke); + program = new Program(Hex.decode("6023600160095760015b600255"), invoke); String s_expected_key = "0000000000000000000000000000000000000000000000000000000000000002"; String s_expected_val = "0000000000000000000000000000000000000000000000000000000000000023"; @@ -1844,7 +1851,8 @@ public class VMTest { vm.step(program); DataWord key = new DataWord(Hex.decode(s_expected_key)); - DataWord val = program.getResult().getRepository().getStorageValue(invoke.getOwnerAddress().getNoLeadZeroesData(), key); + DataWord val = program.getResult().getRepository().getStorageValue(invoke.getOwnerAddress() + .getNoLeadZeroesData(), key); assertTrue(program.isStopped()); assertEquals(s_expected_val, Hex.toHexString(val.getData()).toUpperCase()); @@ -1854,7 +1862,7 @@ public class VMTest { public void testADD_1() { VM vm = new VM(); - program = new Program(Hex.decode("6002600201"), invoke); + program = new Program(Hex.decode("6002600201"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000004"; vm.step(program); @@ -1869,7 +1877,7 @@ public class VMTest { public void testADD_2() { VM vm = new VM(); - program = new Program(Hex.decode("611002600201"), invoke); + program = new Program(Hex.decode("611002600201"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000001004"; vm.step(program); @@ -1884,7 +1892,7 @@ public class VMTest { public void testADD_3() { VM vm = new VM(); - program = new Program(Hex.decode("6110026512345678900901"), invoke); + program = new Program(Hex.decode("6110026512345678900901"), invoke); String s_expected_1 = "000000000000000000000000000000000000000000000000000012345678A00B"; vm.step(program); @@ -1895,11 +1903,11 @@ public class VMTest { assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // ADD OP mal + @Test(expected = StackTooSmallException.class) // ADD OP mal public void testADD_4() { VM vm = new VM(); - program = new Program(Hex.decode("61123401"), invoke); + program = new Program(Hex.decode("61123401"), invoke); try { vm.step(program); vm.step(program); @@ -1911,7 +1919,7 @@ public class VMTest { @Test // ADDMOD OP mal public void testADDMOD_1() { VM vm = new VM(); - program = new Program(Hex.decode("60026002600308"), invoke); + program = new Program(Hex.decode("60026002600308"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); @@ -1927,7 +1935,7 @@ public class VMTest { @Test // ADDMOD OP public void testADDMOD_2() { VM vm = new VM(); - program = new Program(Hex.decode("6110006002611002086000"), invoke); + program = new Program(Hex.decode("6110006002611002086000"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000004"; vm.step(program); @@ -1943,7 +1951,7 @@ public class VMTest { @Test // ADDMOD OP public void testADDMOD_3() { VM vm = new VM(); - program = new Program(Hex.decode("61100265123456789009600208"), invoke); + program = new Program(Hex.decode("61100265123456789009600208"), invoke); String s_expected_1 = "000000000000000000000000000000000000000000000000000000000000093B"; vm.step(program); @@ -1956,10 +1964,10 @@ public class VMTest { assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // ADDMOD OP mal + @Test(expected = StackTooSmallException.class) // ADDMOD OP mal public void testADDMOD_4() { VM vm = new VM(); - program = new Program(Hex.decode("61123408"), invoke); + program = new Program(Hex.decode("61123408"), invoke); try { vm.step(program); vm.step(program); @@ -1972,7 +1980,7 @@ public class VMTest { public void testMUL_1() { VM vm = new VM(); - program = new Program(Hex.decode("6003600202"), invoke); + program = new Program(Hex.decode("6003600202"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000006"; vm.step(program); @@ -1987,7 +1995,7 @@ public class VMTest { public void testMUL_2() { VM vm = new VM(); - program = new Program(Hex.decode("62222222600302"), invoke); + program = new Program(Hex.decode("62222222600302"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000666666"; vm.step(program); @@ -2002,7 +2010,7 @@ public class VMTest { public void testMUL_3() { VM vm = new VM(); - program = new Program(Hex.decode("622222226233333302"), invoke); + program = new Program(Hex.decode("622222226233333302"), invoke); String s_expected_1 = "000000000000000000000000000000000000000000000000000006D3A05F92C6"; vm.step(program); @@ -2013,11 +2021,11 @@ public class VMTest { assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // MUL OP mal + @Test(expected = StackTooSmallException.class) // MUL OP mal public void testMUL_4() { VM vm = new VM(); - program = new Program(Hex.decode("600102"), invoke); + program = new Program(Hex.decode("600102"), invoke); try { vm.step(program); vm.step(program); @@ -2029,7 +2037,7 @@ public class VMTest { @Test // MULMOD OP public void testMULMOD_1() { VM vm = new VM(); - program = new Program(Hex.decode("60036002600409"), invoke); + program = new Program(Hex.decode("60036002600409"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000002"; vm.step(program); @@ -2044,7 +2052,7 @@ public class VMTest { @Test // MULMOD OP public void testMULMOD_2() { VM vm = new VM(); - program = new Program(Hex.decode("622222226003600409"), invoke); + program = new Program(Hex.decode("622222226003600409"), invoke); String s_expected_1 = "000000000000000000000000000000000000000000000000000000000000000C"; vm.step(program); @@ -2059,7 +2067,7 @@ public class VMTest { @Test // MULMOD OP public void testMULMOD_3() { VM vm = new VM(); - program = new Program(Hex.decode("62222222623333336244444409"), invoke); + program = new Program(Hex.decode("62222222623333336244444409"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -2071,10 +2079,10 @@ public class VMTest { assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // MULMOD OP mal + @Test(expected = StackTooSmallException.class) // MULMOD OP mal public void testMULMOD_4() { VM vm = new VM(); - program = new Program(Hex.decode("600109"), invoke); + program = new Program(Hex.decode("600109"), invoke); try { vm.step(program); vm.step(program); @@ -2087,7 +2095,7 @@ public class VMTest { public void testDIV_1() { VM vm = new VM(); - program = new Program(Hex.decode("6002600404"), invoke); + program = new Program(Hex.decode("6002600404"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000002"; vm.step(program); @@ -2102,7 +2110,7 @@ public class VMTest { public void testDIV_2() { VM vm = new VM(); - program = new Program(Hex.decode("6033609904"), invoke); + program = new Program(Hex.decode("6033609904"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000003"; vm.step(program); @@ -2118,7 +2126,7 @@ public class VMTest { public void testDIV_3() { VM vm = new VM(); - program = new Program(Hex.decode("6022609904"), invoke); + program = new Program(Hex.decode("6022609904"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000004"; vm.step(program); @@ -2133,7 +2141,7 @@ public class VMTest { public void testDIV_4() { VM vm = new VM(); - program = new Program(Hex.decode("6015609904"), invoke); + program = new Program(Hex.decode("6015609904"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000007"; vm.step(program); @@ -2149,7 +2157,7 @@ public class VMTest { public void testDIV_5() { VM vm = new VM(); - program = new Program(Hex.decode("6004600704"), invoke); + program = new Program(Hex.decode("6004600704"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); @@ -2160,11 +2168,11 @@ public class VMTest { assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // DIV OP + @Test(expected = StackTooSmallException.class) // DIV OP public void testDIV_6() { VM vm = new VM(); - program = new Program(Hex.decode("600704"), invoke); + program = new Program(Hex.decode("600704"), invoke); try { vm.step(program); vm.step(program); @@ -2177,7 +2185,8 @@ public class VMTest { public void testSDIV_1() { VM vm = new VM(); - program = new Program(Hex.decode("6103E87FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC1805"), invoke); + program = new Program(Hex.decode("6103E87FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC1805" + + ""), invoke); String s_expected_1 = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; vm.step(program); @@ -2192,7 +2201,7 @@ public class VMTest { public void testSDIV_2() { VM vm = new VM(); - program = new Program(Hex.decode("60FF60FF05"), invoke); + program = new Program(Hex.decode("60FF60FF05"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); @@ -2207,7 +2216,7 @@ public class VMTest { public void testSDIV_3() { VM vm = new VM(); - program = new Program(Hex.decode("600060FF05"), invoke); + program = new Program(Hex.decode("600060FF05"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -2218,11 +2227,11 @@ public class VMTest { assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // SDIV OP mal + @Test(expected = StackTooSmallException.class) // SDIV OP mal public void testSDIV_4() { VM vm = new VM(); - program = new Program(Hex.decode("60FF05"), invoke); + program = new Program(Hex.decode("60FF05"), invoke); try { vm.step(program); @@ -2236,7 +2245,7 @@ public class VMTest { public void testSUB_1() { VM vm = new VM(); - program = new Program(Hex.decode("6004600603"), invoke); + program = new Program(Hex.decode("6004600603"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000002"; vm.step(program); @@ -2251,7 +2260,7 @@ public class VMTest { public void testSUB_2() { VM vm = new VM(); - program = new Program(Hex.decode("61444461666603"), invoke); + program = new Program(Hex.decode("61444461666603"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000002222"; vm.step(program); @@ -2266,7 +2275,7 @@ public class VMTest { public void testSUB_3() { VM vm = new VM(); - program = new Program(Hex.decode("614444639999666603"), invoke); + program = new Program(Hex.decode("614444639999666603"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000099992222"; vm.step(program); @@ -2277,11 +2286,11 @@ public class VMTest { assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // SUB OP mal + @Test(expected = StackTooSmallException.class) // SUB OP mal public void testSUB_4() { VM vm = new VM(); - program = new Program(Hex.decode("639999666603"), invoke); + program = new Program(Hex.decode("639999666603"), invoke); try { vm.step(program); vm.step(program); @@ -2294,7 +2303,7 @@ public class VMTest { public void testMSIZE_1() { VM vm = new VM(); - program = new Program(Hex.decode("59"), invoke); + program = new Program(Hex.decode("59"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -2307,7 +2316,7 @@ public class VMTest { public void testMSIZE_2() { VM vm = new VM(); - program = new Program(Hex.decode("602060305259"), invoke); + program = new Program(Hex.decode("602060305259"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000060"; vm.step(program); @@ -2324,7 +2333,7 @@ public class VMTest { public void testSTOP_1() { VM vm = new VM(); - program = new Program(Hex.decode("60206030601060306011602300"), invoke); + program = new Program(Hex.decode("60206030601060306011602300"), invoke); int expectedSteps = 7; int i = 0; @@ -2341,7 +2350,7 @@ public class VMTest { public void testEXP_1() { VM vm = new VM(); - program = new Program(Hex.decode("600360020a"), invoke); + program = new Program(Hex.decode("600360020a"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000008"; vm.step(program); @@ -2359,7 +2368,7 @@ public class VMTest { public void testEXP_2() { VM vm = new VM(); - program = new Program(Hex.decode("6000621234560a"), invoke); + program = new Program(Hex.decode("6000621234560a"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); @@ -2377,7 +2386,7 @@ public class VMTest { public void testEXP_3() { VM vm = new VM(); - program = new Program(Hex.decode("61112260010a"), invoke); + program = new Program(Hex.decode("61112260010a"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); @@ -2392,11 +2401,11 @@ public class VMTest { } - @Test(expected=StackTooSmallException.class) // EXP OP mal + @Test(expected = StackTooSmallException.class) // EXP OP mal public void testEXP_4() { VM vm = new VM(); - program = new Program(Hex.decode("621234560a"), invoke); + program = new Program(Hex.decode("621234560a"), invoke); try { vm.step(program); vm.step(program); @@ -2409,7 +2418,7 @@ public class VMTest { public void testRETURN_1() { VM vm = new VM(); - program = new Program(Hex.decode("61123460005260206000F3"), invoke); + program = new Program(Hex.decode("61123460005260206000F3"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000001234"; vm.step(program); @@ -2428,7 +2437,7 @@ public class VMTest { public void testRETURN_2() { VM vm = new VM(); - program = new Program(Hex.decode("6112346000526020601FF3"), invoke); + program = new Program(Hex.decode("6112346000526020601FF3"), invoke); String s_expected_1 = "3400000000000000000000000000000000000000000000000000000000000000"; vm.step(program); @@ -2447,7 +2456,8 @@ public class VMTest { VM vm = new VM(); program = - new Program(Hex.decode("7FA0B0C0D0E0F0A1B1C1D1E1F1A2B2C2D2E2F2A3B3C3D3E3F3A4B4C4D4E4F4A1B160005260206000F3"), + new Program(Hex.decode + ("7FA0B0C0D0E0F0A1B1C1D1E1F1A2B2C2D2E2F2A3B3C3D3E3F3A4B4C4D4E4F4A1B160005260206000F3"), invoke); String s_expected_1 = "A0B0C0D0E0F0A1B1C1D1E1F1A2B2C2D2E2F2A3B3C3D3E3F3A4B4C4D4E4F4A1B1"; @@ -2468,7 +2478,8 @@ public class VMTest { VM vm = new VM(); program = - new Program(Hex.decode("7FA0B0C0D0E0F0A1B1C1D1E1F1A2B2C2D2E2F2A3B3C3D3E3F3A4B4C4D4E4F4A1B160005260206010F3"), + new Program(Hex.decode + ("7FA0B0C0D0E0F0A1B1C1D1E1F1A2B2C2D2E2F2A3B3C3D3E3F3A4B4C4D4E4F4A1B160005260206010F3"), invoke); String s_expected_1 = "E2F2A3B3C3D3E3F3A4B4C4D4E4F4A1B100000000000000000000000000000000"; @@ -2507,9 +2518,11 @@ public class VMTest { VM vm = new VM(); program = - new Program(Hex.decode("605E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235602054"), + new Program(Hex.decode + ("605E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235602054"), invoke); - String m_expected_1 = "6000605F556014600054601E60205463ABCDDCBA6040545B51602001600A5254516040016014525451606001601E5254516080016028525460A052546016604860003960166000F26000603F556103E756600054600053602002356020540000"; + String m_expected_1 = + "6000605F556014600054601E60205463ABCDDCBA6040545B51602001600A5254516040016014525451606001601E5254516080016028525460A052546016604860003960166000F26000603F556103E756600054600053602002356020540000"; vm.step(program); vm.step(program); @@ -2518,7 +2531,7 @@ public class VMTest { long gas = program.getResult().getGasUsed(); assertEquals(m_expected_1, Hex.toHexString(program.getMemory().array()).toUpperCase()); - assertEquals(10 , gas); + assertEquals(10, gas); } @Test // CODECOPY OP @@ -2530,7 +2543,8 @@ public class VMTest { VM vm = new VM(); program = - new Program(Hex.decode("605E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235"), + new Program(Hex.decode + ("605E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235"), invoke); vm.step(program); @@ -2538,7 +2552,7 @@ public class VMTest { vm.step(program); vm.step(program); - assertEquals( 10, program.getResult().getGasUsed() ); + assertEquals(10, program.getResult().getGasUsed()); } @Test // CODECOPY OP @@ -2546,7 +2560,8 @@ public class VMTest { VM vm = new VM(); program = - new Program(Hex.decode("605E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e756600054600053602002351234"), + new Program(Hex.decode + ("605E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e756600054600053602002351234"), invoke); vm.step(program); @@ -2554,7 +2569,7 @@ public class VMTest { vm.step(program); vm.step(program); - assertEquals( 10, program.getResult().getGasUsed() ); + assertEquals(10, program.getResult().getGasUsed()); } @@ -2563,7 +2578,8 @@ public class VMTest { VM vm = new VM(); program = - new Program(Hex.decode("611234600054615566602054607060006020396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e756600054600053602002351234"), + new Program(Hex.decode + ("611234600054615566602054607060006020396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e756600054600053602002351234"), invoke); vm.step(program); @@ -2581,12 +2597,13 @@ public class VMTest { } - @Test(expected=StackTooSmallException.class) // CODECOPY OP mal + @Test(expected = StackTooSmallException.class) // CODECOPY OP mal public void testCODECOPY_6() { VM vm = new VM(); program = - new Program(Hex.decode("605E6007396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e756600054600053602002351234"), + new Program(Hex.decode + ("605E6007396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e756600054600053602002351234"), invoke); try { vm.step(program); @@ -2619,9 +2636,11 @@ public class VMTest { VM vm = new VM(); program = - new Program(Hex.decode("603E6007600073471FD3AD3E9EEADEEC4608B92D16CE6B500704CC3C6000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235602054"), + new Program(Hex.decode + ("603E6007600073471FD3AD3E9EEADEEC4608B92D16CE6B500704CC3C6000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235602054"), invoke); - String m_expected_1 = "6000605F556014600054601E60205463ABCDDCBA6040545B51602001600A5254516040016014525451606001601E5254516080016028525460A0525460160000"; + String m_expected_1 = + "6000605F556014600054601E60205463ABCDDCBA6040545B51602001600A5254516040016014525451606001601E5254516080016028525460A0525460160000"; vm.step(program); vm.step(program); @@ -2636,10 +2655,12 @@ public class VMTest { public void testEXTCODECOPY_3() { VM vm = new VM(); program = - new Program(Hex.decode("605E6007600073471FD3AD3E9EEADEEC4608B92D16CE6B500704CC3C6000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235"), + new Program(Hex.decode + ("605E6007600073471FD3AD3E9EEADEEC4608B92D16CE6B500704CC3C6000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235"), invoke); - String m_expected_1 = "6000605F556014600054601E60205463ABCDDCBA6040545B51602001600A5254516040016014525451606001601E5254516080016028525460A052546016604860003960166000F26000603F556103E756600054600053602002350000000000"; + String m_expected_1 = + "6000605F556014600054601E60205463ABCDDCBA6040545B51602001600A5254516040016014525451606001601E5254516080016028525460A052546016604860003960166000F26000603F556103E756600054600053602002350000000000"; vm.step(program); vm.step(program); @@ -2654,7 +2675,8 @@ public class VMTest { public void testEXTCODECOPY_4() { VM vm = new VM(); program = - new Program(Hex.decode("611234600054615566602054603E6000602073471FD3AD3E9EEADEEC4608B92D16CE6B500704CC3C6000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e756600054600053602002351234"), + new Program(Hex.decode + ("611234600054615566602054603E6000602073471FD3AD3E9EEADEEC4608B92D16CE6B500704CC3C6000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e756600054600053602002351234"), invoke); vm.step(program); @@ -2673,7 +2695,7 @@ public class VMTest { } - @Test(expected=StackTooSmallException.class) // EXTCODECOPY OP mal + @Test(expected = StackTooSmallException.class) // EXTCODECOPY OP mal public void testEXTCODECOPY_5() { VM vm = new VM(); program = @@ -2695,7 +2717,8 @@ public class VMTest { VM vm = new VM(); program = - new Program(Hex.decode("385E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235"), + new Program(Hex.decode + ("385E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000062"; @@ -2709,7 +2732,8 @@ public class VMTest { public void testEXTCODESIZE_1() { VM vm = new VM(); program = - new Program(Hex.decode("73471FD3AD3E9EEADEEC4608B92D16CE6B500704CC395E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235"), + new Program(Hex.decode + ("73471FD3AD3E9EEADEEC4608B92D16CE6B500704CC395E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235"), invoke); // Push address on the stack and perform EXTCODECOPY String s_expected_1 = "000000000000000000000000471FD3AD3E9EEADEEC4608B92D16CE6B500704CC"; @@ -2722,7 +2746,7 @@ public class VMTest { @Test // MOD OP public void testMOD_1() { VM vm = new VM(); - program = new Program(Hex.decode("6003600406"), invoke); + program = new Program(Hex.decode("6003600406"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); @@ -2736,7 +2760,7 @@ public class VMTest { @Test // MOD OP public void testMOD_2() { VM vm = new VM(); - program = new Program(Hex.decode("61012C6101F406"), invoke); + program = new Program(Hex.decode("61012C6101F406"), invoke); String s_expected_1 = "00000000000000000000000000000000000000000000000000000000000000C8"; vm.step(program); @@ -2750,7 +2774,7 @@ public class VMTest { @Test // MOD OP public void testMOD_3() { VM vm = new VM(); - program = new Program(Hex.decode("6004600206"), invoke); + program = new Program(Hex.decode("6004600206"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000002"; vm.step(program); @@ -2761,11 +2785,11 @@ public class VMTest { assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // MOD OP mal + @Test(expected = StackTooSmallException.class) // MOD OP mal public void testMOD_4() { VM vm = new VM(); - program = new Program(Hex.decode("600406"), invoke); + program = new Program(Hex.decode("600406"), invoke); try { vm.step(program); @@ -2779,7 +2803,7 @@ public class VMTest { @Test // SMOD OP public void testSMOD_1() { VM vm = new VM(); - program = new Program(Hex.decode("6003600407"), invoke); + program = new Program(Hex.decode("6003600407"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000001"; vm.step(program); @@ -2793,9 +2817,9 @@ public class VMTest { @Test // SMOD OP public void testSMOD_2() { VM vm = new VM(); - program = new Program(Hex.decode("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE2" + // -30 - "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 - "07"), invoke); + program = new Program(Hex.decode("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE2" + // -30 + "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 + "07"), invoke); String s_expected_1 = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEC"; vm.step(program); @@ -2809,9 +2833,9 @@ public class VMTest { @Test // SMOD OP public void testSMOD_3() { VM vm = new VM(); - program = new Program(Hex.decode("7F000000000000000000000000000000000000000000000000000000000000001E" + // 30 - "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 - "07"), invoke); + program = new Program(Hex.decode("7F000000000000000000000000000000000000000000000000000000000000001E" + // 30 + "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF56" + // -170 + "07"), invoke); String s_expected_1 = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEC"; vm.step(program); @@ -2822,11 +2846,11 @@ public class VMTest { assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - @Test(expected=StackTooSmallException.class) // SMOD OP mal + @Test(expected = StackTooSmallException.class) // SMOD OP mal public void testSMOD_4() { VM vm = new VM(); - program = new Program(Hex.decode("7F000000000000000000000000000000000000000000000000000000000000001E" + // 30 - "07"), invoke); + program = new Program(Hex.decode("7F000000000000000000000000000000000000000000000000000000000000001E" + // 30 + "07"), invoke); try { vm.step(program); vm.step(program); @@ -2866,4 +2890,4 @@ public class VMTest { RETURN f2 (1) 61778e600054 -*/ + */ diff --git a/ethereumj-core/src/test/resources/dbdump/dbdump.json b/ethereumj-core/src/test/resources/dbdump/dbdump.json index 39d740d3..8f4d7ff3 100644 --- a/ethereumj-core/src/test/resources/dbdump/dbdump.json +++ b/ethereumj-core/src/test/resources/dbdump/dbdump.json @@ -1,4 +1,3 @@ - [ { "key": "58fc9b6b07e1df2a625baa76f8329f216ae4c939ec3f5b459deb92f9421d7e90", "val": "f90191a068cdfc3c33a1de359acf0f4ab1af8f77b17fe84ac8d1530c54effc09932fb5b0a03e98c4564b0ad04a81be44e23aaef419cf6a4c49146f0902cfd58c92a44f8463a0b6a66a8762408311b6611ab56ea68d2f4fb907b2492f1424753afeddeb5c16bea0e3714f983f653235ddab914e738a4074c1e48e6466451d9feb343c95462b1dfb80a0389c53a125b38550b342e1cfbd444679918c3cc9a00da01b5b009b896ff213e5a08f9c65f65cac4d30822813d5b86f58be087c79d7029baf42d8ffadecf43800e5a0e018a2a6e1f5f1af59ded7374461ae9025fcee3aee2f34fe52de286433df2ebca0d5b76e9819dd8ade09d6def13575e32e61717edb95d337d1820bbd3d9fa9d375a0d5b044d6c61572bc678e5f51757c61f7ba4ab638f4650e87adf64e04c7d7cac580a04b0267bd17edbe144db968ff88adbee12b17edd564387f2aa331efcb2c2e24faa04a6ea931b831ba0b74fc9b69bb40d5206ba15348c4042bcfda3c8324d1b6e9cc80a0c1fd3e0a1d074ad970ef2d6864924f6d9810ff5119e80310e1eda6b0a627ae688080"}, diff --git a/ethereumj-studio/build-post-package.xml b/ethereumj-studio/build-post-package.xml index d3916079..675515e7 100644 --- a/ethereumj-studio/build-post-package.xml +++ b/ethereumj-studio/build-post-package.xml @@ -6,23 +6,23 @@ - + - - - + + + - + @@ -37,12 +37,11 @@ - + - @@ -52,5 +51,4 @@ - diff --git a/ethereumj-studio/pom.xml b/ethereumj-studio/pom.xml index 685d019b..72e3c869 100644 --- a/ethereumj-studio/pom.xml +++ b/ethereumj-studio/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 org.ethereum ethereumj-studio @@ -49,7 +49,7 @@ mvn-central maven - http://repo1.maven.org/maven2 + http://repo1.maven.org/maven2 @@ -146,7 +146,6 @@ - org.apache.maven.plugins maven-dependency-plugin @@ -269,9 +268,8 @@ - - + diff --git a/ethereumj-studio/src/main/java/org/ethereum/geo/IpGeoDB.java b/ethereumj-studio/src/main/java/org/ethereum/geo/IpGeoDB.java index 3215c974..19086d82 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/geo/IpGeoDB.java +++ b/ethereumj-studio/src/main/java/org/ethereum/geo/IpGeoDB.java @@ -11,6 +11,7 @@ import java.net.URL; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 24/04/14 20:11 */ diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/AccountsListWindow.java b/ethereumj-studio/src/main/java/org/ethereum/gui/AccountsListWindow.java index 878a9b91..c37b7d41 100755 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/AccountsListWindow.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/AccountsListWindow.java @@ -21,7 +21,7 @@ import org.iq80.leveldb.DBIterator; import org.spongycastle.util.Arrays; import org.spongycastle.util.encoders.Hex; -public class AccountsListWindow extends JFrame { +public class AccountsListWindow extends JFrame { private JTable tblAccountsDataTable; private AccountsDataAdapter adapter; @@ -45,20 +45,20 @@ public class AccountsListWindow extends JFrame { tblAccountsDataTable.setModel(adapter); JScrollPane scrollPane = new JScrollPane(tblAccountsDataTable); - scrollPane.setPreferredSize(new Dimension(680,490)); + scrollPane.setPreferredSize(new Dimension(680, 490)); panel.add(scrollPane); loadAccounts(); } private void loadAccounts() { - new Thread(){ + new Thread() { @Override - public void run(){ + public void run() { Repository repository = UIEthereumManager.ethereum.getRepository(); DBIterator i = repository.getAccountsIterator(); - while(i.hasNext()) { + while (i.hasNext()) { DataClass dc = new DataClass(); dc.address = i.next().getKey(); @@ -74,7 +74,7 @@ public class AccountsListWindow extends JFrame { private class AccountsDataAdapter extends AbstractTableModel { List data; - final String[] columns = new String[]{ "Account", "Balance", "Is Contract"}; + final String[] columns = new String[]{"Account", "Balance", "Is Contract"}; public AccountsDataAdapter(List data) { this.data = data; @@ -102,23 +102,21 @@ public class AccountsListWindow extends JFrame { @Override public boolean isCellEditable(int row, int column) { // custom isCellEditable function - return column == 0? true:false; + return column == 0 ? true : false; } @Override public Object getValueAt(int rowIndex, int columnIndex) { - if(columnIndex == 0) { + if (columnIndex == 0) { return Hex.toHexString(data.get(rowIndex).address); - } - else if(columnIndex == 1 ){ - if(data.get(rowIndex).accountState != null) { + } else if (columnIndex == 1) { + if (data.get(rowIndex).accountState != null) { return Denomination.toFriendlyString(data.get(rowIndex).accountState.getBalance()); } return "---"; - } - else { - if(data.get(rowIndex).accountState != null) { - if(!Arrays.areEqual(data.get(rowIndex).accountState.getCodeHash(), HashUtil.EMPTY_DATA_HASH)) + } else { + if (data.get(rowIndex).accountState != null) { + if (!Arrays.areEqual(data.get(rowIndex).accountState.getCodeHash(), HashUtil.EMPTY_DATA_HASH)) return "Yes"; } return "No"; diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/BlockChainTable.java b/ethereumj-studio/src/main/java/org/ethereum/gui/BlockChainTable.java index b714b33a..97e23d38 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/BlockChainTable.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/BlockChainTable.java @@ -786,7 +786,8 @@ public class BlockChainTable extends JFrame implements ActionListener { c.insets = new Insets(0, 10, 0, 0); transactionPanel.add(valueLabel, c); - JTextField value = new JTextField(transaction.getValue() != null ? ByteUtil.toHexString(transaction.getValue()) : ""); + JTextField value = new JTextField(transaction.getValue() != null ? ByteUtil.toHexString(transaction.getValue + ()) : ""); highlightText(value); value.setEditable(false); value.setBorder(null); @@ -826,7 +827,8 @@ public class BlockChainTable extends JFrame implements ActionListener { }); data.setFont(plain); - if (findText.getText().length() > 0 && ByteUtil.toHexString(transaction.getData()).contains(findText.getText())) { + if (findText.getText().length() > 0 && ByteUtil.toHexString(transaction.getData()).contains(findText.getText + ())) { data.setBackground(HILIT_COLOR); } c.gridx = 3; diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/ConnectionConsoleWindow.java b/ethereumj-studio/src/main/java/org/ethereum/gui/ConnectionConsoleWindow.java index b3bac01c..0ac83edd 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/ConnectionConsoleWindow.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/ConnectionConsoleWindow.java @@ -82,7 +82,7 @@ public class ConnectionConsoleWindow extends JFrame { } }; - UIEthereumManager.ethereum.addListener(new EthereumListenerAdapter(){ + UIEthereumManager.ethereum.addListener(new EthereumListenerAdapter() { @Override public void trace(final String output) { SwingUtilities.invokeLater(new Runnable() { diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/ConsoleTokenMaker.java b/ethereumj-studio/src/main/java/org/ethereum/gui/ConsoleTokenMaker.java index b9b1ff9c..cc3a4ffd 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/ConsoleTokenMaker.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/ConsoleTokenMaker.java @@ -1,4 +1,3 @@ - package org.ethereum.gui; import javax.swing.text.Segment; @@ -10,6 +9,7 @@ import org.slf4j.LoggerFactory; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 24/04/14 11:52 */ @@ -56,8 +56,8 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { // into here as "identifiers," we have to see what the token // really is... case Token.IDENTIFIER: - int value = wordsToHighlight.get(segment, start,end); - if (value!=-1) + int value = wordsToHighlight.get(segment, start, end); + if (value != -1) tokenType = value; break; case Token.WHITESPACE: @@ -95,10 +95,10 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { * line to "comment" it in a this programming language. * * @return The start and end strings to add to a line to "comment" - * it out. + * it out. */ public String[] getLineCommentStartAndEnd() { - return new String[] { "//", null }; + return new String[]{"//", null}; } @@ -106,7 +106,7 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { * Returns the words to highlight for the JavaScript programming language. * * @return A TokenMap containing the words to highlight for - * the JavaScript programming language. + * the JavaScript programming language. * @see org.fife.ui.rsyntaxtextarea.AbstractTokenMaker#getWordsToHighlight */ public TokenMap getWordsToHighlight() { @@ -114,14 +114,14 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { TokenMap tokenMap = new TokenMap(52); int reservedWord = Token.RESERVED_WORD; - tokenMap.put("connecting", reservedWord); + tokenMap.put("connecting", reservedWord); int literalBoolean = Token.LITERAL_BOOLEAN; - tokenMap.put("false", literalBoolean); - tokenMap.put("true", literalBoolean); + tokenMap.put("false", literalBoolean); + tokenMap.put("true", literalBoolean); int dataType = Token.DATA_TYPE; - tokenMap.put("boolean", dataType); + tokenMap.put("boolean", dataType); return tokenMap; @@ -139,7 +139,6 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { } - /** * Returns the first token in the linked list of tokens generated * from text. This method must be implemented by @@ -148,9 +147,9 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { * @param text The text from which to get tokens. * @param initialTokenType The token type we should start with. * @param startOffset The offset into the document at which - * text starts. + * text starts. * @return The first Token in a linked list representing - * the syntax highlighted text. + * the syntax highlighted text. */ public Token getTokenList(Segment text, int initialTokenType, int startOffset) { @@ -171,12 +170,12 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { int newStartOffset = startOffset - offset; currentTokenStart = offset; - currentTokenType = initialTokenType; + currentTokenType = initialTokenType; boolean backslash = false; boolean numContainsExponent = false; boolean numContainsEndCharacter = false; - for (int i=offset; i call '"' an identifier.. - addToken(text, currentTokenStart,i, Token.IDENTIFIER, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i, Token.IDENTIFIER, newStartOffset + + currentTokenStart); backslash = false; - } - else { + } else { currentTokenType = Token.ERROR_STRING_DOUBLE; } break; case '\'': if (backslash) { // Escaped single quote => call '\'' an identifier. - addToken(text, currentTokenStart,i, Token.IDENTIFIER, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i, Token.IDENTIFIER, newStartOffset + + currentTokenStart); backslash = false; - } - else { + } else { currentTokenType = Token.ERROR_CHAR; } break; case '\\': - addToken(text, currentTokenStart,i, Token.IDENTIFIER, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i, Token.IDENTIFIER, newStartOffset + currentTokenStart); currentTokenType = Token.NULL; backslash = !backslash; break; @@ -224,30 +223,30 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { if (RSyntaxUtilities.isDigit(c)) { currentTokenType = Token.LITERAL_NUMBER_DECIMAL_INT; break; - } - else if (RSyntaxUtilities.isLetter(c) || c=='_') { + } else if (RSyntaxUtilities.isLetter(c) || c == '_') { currentTokenType = Token.IDENTIFIER; break; } - int indexOf = operators.indexOf(c,0); - if (indexOf>-1) { + int indexOf = operators.indexOf(c, 0); + if (indexOf > -1) { currentTokenStart = i; currentTokenType = Token.OPERATOR; break; } - indexOf = separators.indexOf(c,0); - if (indexOf>-1) { - addToken(text, currentTokenStart,i, Token.SEPARATOR, newStartOffset+currentTokenStart); + indexOf = separators.indexOf(c, 0); + if (indexOf > -1) { + addToken(text, currentTokenStart, i, Token.SEPARATOR, newStartOffset + + currentTokenStart); currentTokenType = Token.NULL; break; } - indexOf = separators2.indexOf(c,0); - if (indexOf>-1) { - addToken(text, currentTokenStart,i, Token.IDENTIFIER, newStartOffset+currentTokenStart); + indexOf = separators2.indexOf(c, 0); + if (indexOf > -1) { + addToken(text, currentTokenStart, i, Token.IDENTIFIER, newStartOffset + + currentTokenStart); currentTokenType = Token.NULL; break; - } - else { + } else { currentTokenType = Token.ERROR_IDENTIFIER; break; } @@ -265,21 +264,24 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { break; // Still whitespace. case '\\': - addToken(text, currentTokenStart,i-1, Token.WHITESPACE, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.WHITESPACE, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; backslash = true; // Previous char whitespace => this must be first backslash. break; case '"': // Don't need to worry about backslashes as previous char is space. - addToken(text, currentTokenStart,i-1, Token.WHITESPACE, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.WHITESPACE, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_STRING_DOUBLE; backslash = false; break; case '\'': // Don't need to worry about backslashes as previous char is space. - addToken(text, currentTokenStart,i-1, Token.WHITESPACE, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.WHITESPACE, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_CHAR; backslash = false; @@ -287,36 +289,35 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { default: // Add the whitespace token and start anew. - addToken(text, currentTokenStart,i-1, Token.WHITESPACE, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.WHITESPACE, newStartOffset + + currentTokenStart); currentTokenStart = i; if (RSyntaxUtilities.isDigit(c)) { currentTokenType = Token.LITERAL_NUMBER_DECIMAL_INT; break; - } - else if (RSyntaxUtilities.isLetter(c) || c=='_') { + } else if (RSyntaxUtilities.isLetter(c) || c == '_') { currentTokenType = Token.IDENTIFIER; break; } - int indexOf = operators.indexOf(c,0); - if (indexOf>-1) { + int indexOf = operators.indexOf(c, 0); + if (indexOf > -1) { currentTokenStart = i; currentTokenType = Token.OPERATOR; break; } - indexOf = separators.indexOf(c,0); - if (indexOf>-1) { - addToken(text, i,i, Token.SEPARATOR, newStartOffset+i); + indexOf = separators.indexOf(c, 0); + if (indexOf > -1) { + addToken(text, i, i, Token.SEPARATOR, newStartOffset + i); currentTokenType = Token.NULL; break; } - indexOf = separators2.indexOf(c,0); - if (indexOf>-1) { - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + indexOf = separators2.indexOf(c, 0); + if (indexOf > -1) { + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; break; - } - else { + } else { currentTokenType = Token.ERROR_IDENTIFIER; } @@ -333,75 +334,80 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { case ' ': case '\t': - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_HEXADECIMAL, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_HEXADECIMAL, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.WHITESPACE; break; case '"': // Don't need to worry about backslashes as previous char is non-backslash. - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_HEXADECIMAL, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_HEXADECIMAL, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_STRING_DOUBLE; backslash = false; break; case '\'': // Don't need to worry about backslashes as previous char is non-backslash. - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_HEXADECIMAL, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_HEXADECIMAL, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_CHAR; backslash = false; break; case '\\': - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_HEXADECIMAL, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_HEXADECIMAL, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; backslash = true; break; default: - if (c=='e') { // Exponent. - if (numContainsExponent==false) { + if (c == 'e') { // Exponent. + if (numContainsExponent == false) { numContainsExponent = true; - } - else { + } else { currentTokenType = Token.ERROR_NUMBER_FORMAT; } break; } int indexOf = hexCharacters.indexOf(c); - if (indexOf>-1) { + if (indexOf > -1) { break; // Still a hexadecimal number. } indexOf = numberEndChars.indexOf(c); - if (indexOf>-1) { // Numbers can end in 'f','F','l','L', etc. - if (numContainsEndCharacter==true) { + if (indexOf > -1) { // Numbers can end in 'f','F','l','L', etc. + if (numContainsEndCharacter == true) { currentTokenType = Token.ERROR_NUMBER_FORMAT; - } - else { + } else { numContainsEndCharacter = true; } break; } indexOf = operators.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_HEXADECIMAL, newStartOffset+currentTokenStart); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_HEXADECIMAL, + newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = Token.OPERATOR; break; } indexOf = separators.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_HEXADECIMAL, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.SEPARATOR, newStartOffset+i); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_HEXADECIMAL, + newStartOffset + currentTokenStart); + addToken(text, i, i, Token.SEPARATOR, newStartOffset + i); currentTokenType = Token.NULL; break; } indexOf = separators2.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_HEXADECIMAL, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_HEXADECIMAL, + newStartOffset + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; break; } @@ -414,67 +420,70 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { break; - - - case Token.IDENTIFIER: switch (c) { case ' ': case '\t': - addToken(text, currentTokenStart,i-1, Token.IDENTIFIER, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.WHITESPACE; break; case '"': // Don't need to worry about backslashes as previous char is non-backslash. - addToken(text, currentTokenStart,i-1, Token.IDENTIFIER, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_STRING_DOUBLE; backslash = false; break; case '\'': // Don't need to worry about backslashes as previous char is non-backslash. - addToken(text, currentTokenStart,i-1, Token.IDENTIFIER, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_CHAR; backslash = false; break; case '\\': - addToken(text, currentTokenStart,i-1, Token.IDENTIFIER, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; backslash = true; break; default: - if (RSyntaxUtilities.isLetterOrDigit(c) || c=='_') { + if (RSyntaxUtilities.isLetterOrDigit(c) || c == '_') { break; // Still an identifier of some type. } int indexOf = operators.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.IDENTIFIER, newStartOffset+currentTokenStart); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.OPERATOR; break; } - indexOf = separators.indexOf(c,0); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.IDENTIFIER, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.SEPARATOR, newStartOffset+i); + indexOf = separators.indexOf(c, 0); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.SEPARATOR, newStartOffset + i); currentTokenType = Token.NULL; break; } - indexOf = separators2.indexOf(c,0); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.IDENTIFIER, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + indexOf = separators2.indexOf(c, 0); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; break; - } - else { + } else { currentTokenType = Token.ERROR_IDENTIFIER; } @@ -486,7 +495,7 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { // Reset our boolean states if we only have one digit char before // the current one. - if (currentTokenStart==i-1) { + if (currentTokenStart == i - 1) { numContainsExponent = false; numContainsEndCharacter = false; } @@ -495,28 +504,32 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { case ' ': case '\t': - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.WHITESPACE; break; case '"': // Don't need to worry about backslashes as previous char is non-backslash. - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_STRING_DOUBLE; backslash = false; break; case '\'': // Don't need to worry about backslashes as previous char is non-backslash. - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_CHAR; backslash = false; break; case '\\': - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; backslash = true; break; @@ -525,53 +538,51 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { if (RSyntaxUtilities.isDigit(c)) { break; // Still a literal number. - } - else if (c=='e') { // Exponent. - if (numContainsExponent==false) { + } else if (c == 'e') { // Exponent. + if (numContainsExponent == false) { numContainsExponent = true; - } - else { + } else { currentTokenType = Token.ERROR_NUMBER_FORMAT; } break; - } - else if (c=='.') { // Decimal point. - if (numContainsExponent==true) { + } else if (c == '.') { // Decimal point. + if (numContainsExponent == true) { currentTokenType = Token.ERROR_NUMBER_FORMAT; - } - else { + } else { currentTokenType = Token.LITERAL_NUMBER_FLOAT; } break; } int indexOf = numberEndChars.indexOf(c); - if (indexOf>-1) { // Numbers can end in 'f','F','l','L', etc. - if (numContainsEndCharacter==true) { + if (indexOf > -1) { // Numbers can end in 'f','F','l','L', etc. + if (numContainsEndCharacter == true) { currentTokenType = Token.ERROR_NUMBER_FORMAT; - } - else { + } else { numContainsEndCharacter = true; } break; } indexOf = operators.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset+currentTokenStart); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_DECIMAL_INT, + newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = Token.OPERATOR; break; } indexOf = separators.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.SEPARATOR, newStartOffset+i); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_DECIMAL_INT, + newStartOffset + currentTokenStart); + addToken(text, i, i, Token.SEPARATOR, newStartOffset + i); currentTokenType = Token.NULL; break; } indexOf = separators2.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_DECIMAL_INT, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_DECIMAL_INT, + newStartOffset + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; break; } @@ -589,28 +600,32 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { case ' ': case '\t': - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_FLOAT, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_FLOAT, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.WHITESPACE; break; case '"': // Don't need to worry about backslashes as previous char is non-backslash. - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_FLOAT, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_FLOAT, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_STRING_DOUBLE; backslash = false; break; case '\'': // Don't need to worry about backslashes as previous char is non-backslash. - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_FLOAT, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_FLOAT, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_CHAR; backslash = false; break; case '\\': - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_FLOAT, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_FLOAT, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; backslash = true; break; @@ -619,48 +634,48 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { if (RSyntaxUtilities.isDigit(c)) { break; // Still a literal number. - } - else if (c=='e') { // Exponent. - if (numContainsExponent==false) { + } else if (c == 'e') { // Exponent. + if (numContainsExponent == false) { numContainsExponent = true; - } - else { + } else { currentTokenType = Token.ERROR_NUMBER_FORMAT; } break; - } - else if (c=='.') { // Second decimal point; must catch now because it's a "separator" below. + } else if (c == '.') { // Second decimal point; must catch now because it's a "separator" + // below. currentTokenType = Token.ERROR_NUMBER_FORMAT; break; } int indexOf = numberEndChars.indexOf(c); - if (indexOf>-1) { // Numbers can end in 'f','F','l','L', etc. - if (numContainsEndCharacter==true) { + if (indexOf > -1) { // Numbers can end in 'f','F','l','L', etc. + if (numContainsEndCharacter == true) { currentTokenType = Token.ERROR_NUMBER_FORMAT; - } - else { + } else { numContainsEndCharacter = true; } break; } indexOf = operators.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_FLOAT, newStartOffset+currentTokenStart); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_FLOAT, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.OPERATOR; break; } indexOf = separators.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_FLOAT, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.SEPARATOR, newStartOffset+i); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_FLOAT, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.SEPARATOR, newStartOffset + i); currentTokenType = Token.NULL; break; } indexOf = separators2.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.LITERAL_NUMBER_FLOAT, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.LITERAL_NUMBER_FLOAT, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; break; } @@ -676,9 +691,10 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { case Token.COMMENT_MULTILINE: // Find either end of MLC or end of the current line. - while (i < end-1) { - if (array[i]=='*' && array[i+1]=='/') { - addToken(text, currentTokenStart,i+1, Token.COMMENT_MULTILINE, newStartOffset+currentTokenStart); + while (i < end - 1) { + if (array[i] == '*' && array[i + 1] == '/') { + addToken(text, currentTokenStart, i + 1, Token.COMMENT_MULTILINE, newStartOffset + + currentTokenStart); i = i + 1; currentTokenType = Token.NULL; backslash = false; // Backslashes can't accumulate before and after a comment... @@ -691,7 +707,7 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { case Token.COMMENT_EOL: i = end - 1; - addToken(text, currentTokenStart,i, Token.COMMENT_EOL, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i, Token.COMMENT_EOL, newStartOffset + currentTokenStart); // We need to set token type to null so at the bottom we don't add one more token. currentTokenType = Token.NULL; break; @@ -700,32 +716,27 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { // Note that when we enter this state, the PREVIOUS character was an operator. case Token.OPERATOR: - if (array[i-1]=='/') { // Possibility of comments. + if (array[i - 1] == '/') { // Possibility of comments. - if (c=='*') { + if (c == '*') { currentTokenType = Token.COMMENT_MULTILINE; break; - } - - else if (c=='/') { + } else if (c == '/') { currentTokenType = Token.COMMENT_EOL; i = end - 1; // Since we know the rest of the line is in this token. - } - - else { + } else { // We MUST add the token at the previous char now; if we don't and let // operators accumulate before we print them, we will mess up syntax // highlighting if we get an end-of-line comment. - addToken(text, currentTokenStart,i-1, Token.OPERATOR, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.OPERATOR, newStartOffset + + currentTokenStart); currentTokenType = Token.NULL; i = i - 1; } - } + } else { - else { - - addToken(text, currentTokenStart,i-1, Token.OPERATOR, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.OPERATOR, newStartOffset + currentTokenStart); // Hack to keep code size down... i--; @@ -741,55 +752,64 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { case ' ': case '\t': - addToken(text, currentTokenStart,i-1, Token.ERROR_IDENTIFIER, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.ERROR_IDENTIFIER, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.WHITESPACE; break; case '"': // Don't need to worry about backslashes as previous char is non-backslash. - addToken(text, currentTokenStart,i-1, Token.ERROR_IDENTIFIER, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.ERROR_IDENTIFIER, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_STRING_DOUBLE; backslash = false; break; case '\'': // Don't need to worry about backslashes as previous char is non-backslash. - addToken(text, currentTokenStart,i-1, Token.ERROR_IDENTIFIER, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.ERROR_IDENTIFIER, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_CHAR; backslash = false; break; case ';': - addToken(text, currentTokenStart,i-1, Token.ERROR_IDENTIFIER, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.ERROR_IDENTIFIER, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; break; case '\\': - addToken(text, currentTokenStart,i-1, Token.ERROR_IDENTIFIER, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.ERROR_IDENTIFIER, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; - backslash = true; // Must be first backslash in a row since previous character is identifier char. + backslash = true; // Must be first backslash in a row since previous character is + // identifier char. break; default: int indexOf = operators.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.ERROR_IDENTIFIER, newStartOffset+currentTokenStart); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.ERROR_IDENTIFIER, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.OPERATOR; } indexOf = separators.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.ERROR_IDENTIFIER, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.SEPARATOR, newStartOffset+i); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.ERROR_IDENTIFIER, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.SEPARATOR, newStartOffset + i); currentTokenType = Token.NULL; } indexOf = separators2.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.ERROR_IDENTIFIER, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.ERROR_IDENTIFIER, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; } @@ -803,34 +823,39 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { case ' ': case '\t': - addToken(text, currentTokenStart,i-1, Token.ERROR_NUMBER_FORMAT, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.ERROR_NUMBER_FORMAT, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.WHITESPACE; break; case '"': // Don't need to worry about backslashes as previous char is non-backslash. - addToken(text, currentTokenStart,i-1, Token.ERROR_NUMBER_FORMAT, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.ERROR_NUMBER_FORMAT, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_STRING_DOUBLE; backslash = false; break; case '\'': // Don't need to worry about backslashes as previous char is non-backslash. - addToken(text, currentTokenStart,i-1, Token.ERROR_NUMBER_FORMAT, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.ERROR_NUMBER_FORMAT, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_CHAR; backslash = false; break; case ';': - addToken(text, currentTokenStart,i-1, Token.ERROR_NUMBER_FORMAT, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.ERROR_NUMBER_FORMAT, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; break; case '\\': - addToken(text, currentTokenStart,i-1, Token.ERROR_NUMBER_FORMAT, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.ERROR_NUMBER_FORMAT, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; backslash = true; // Must be first backslash in a row since previous char is a number char. break; @@ -839,27 +864,31 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { // Could be going into hexadecimal. int indexOf = hexCharacters.indexOf(c); - if (indexOf>-1 && (i-currentTokenStart==2 && array[i-1]=='x' && array[i-2]=='0')) { + if (indexOf > -1 && (i - currentTokenStart == 2 && array[i - 1] == 'x' && array[i - 2] == + '0')) { currentTokenType = Token.LITERAL_NUMBER_HEXADECIMAL; break; } indexOf = operators.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.ERROR_NUMBER_FORMAT, newStartOffset+currentTokenStart); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.ERROR_NUMBER_FORMAT, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.OPERATOR; } indexOf = separators.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.ERROR_NUMBER_FORMAT, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.SEPARATOR, newStartOffset+i); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.ERROR_NUMBER_FORMAT, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.SEPARATOR, newStartOffset + i); currentTokenType = Token.NULL; } indexOf = separators2.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.ERROR_NUMBER_FORMAT, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.ERROR_NUMBER_FORMAT, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; } @@ -869,13 +898,13 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { case Token.ERROR_CHAR: - if (c=='\\') { + if (c == '\\') { backslash = !backslash; // Okay because if we got in here, backslash was initially false. - } - else { + } else { - if (c=='\'' && !backslash) { - addToken(text, currentTokenStart,i, Token.LITERAL_CHAR, newStartOffset+currentTokenStart); + if (c == '\'' && !backslash) { + addToken(text, currentTokenStart, i, Token.LITERAL_CHAR, newStartOffset + + currentTokenStart); currentTokenType = Token.NULL; // backslash is definitely false when we leave. } @@ -889,12 +918,12 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { case Token.ERROR_STRING_DOUBLE: - if (c=='\\') { + if (c == '\\') { backslash = !backslash; // Okay because if we got in here, backslash was initially false. - } - else { - if (c=='"' && !backslash) { - addToken(text, currentTokenStart,i, Token.LITERAL_STRING_DOUBLE_QUOTE, newStartOffset+currentTokenStart); + } else { + if (c == '"' && !backslash) { + addToken(text, currentTokenStart, i, Token.LITERAL_STRING_DOUBLE_QUOTE, newStartOffset + + currentTokenStart); currentTokenType = Token.NULL; // backslash is definitely false when we leave. } @@ -912,9 +941,9 @@ public class ConsoleTokenMaker extends AbstractTokenMaker { // Deal with the (possibly there) last token. if (currentTokenType != Token.NULL) { - addToken(text, currentTokenStart,end-1, currentTokenType, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, end - 1, currentTokenType, newStartOffset + currentTokenStart); } - if (currentTokenType!=Token.COMMENT_MULTILINE) { + if (currentTokenType != Token.COMMENT_MULTILINE) { addNullToken(); } diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/ContractCallDialog.java b/ethereumj-studio/src/main/java/org/ethereum/gui/ContractCallDialog.java index 41ed0078..7a54e749 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/ContractCallDialog.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/ContractCallDialog.java @@ -25,8 +25,10 @@ import java.math.BigInteger; import java.net.URL; import java.util.Collection; import java.util.Map; + /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 18/05/14 22:21 */ @@ -42,7 +44,7 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { private final JTextField contractAddrInput; private JScrollPane contractDataInput; - private JTextArea msgDataTA; + private JTextArea msgDataTA; private JLabel statusMsg = null; private JLabel playLabel = null; @@ -107,8 +109,9 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { - ContractCallDialog.this.playContractCall(); - }} + ContractCallDialog.this.playContractCall(); + } + } ); playLabel.setBounds(438, 100, 42, 42); @@ -153,6 +156,7 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { JComboBox creatorAddressCombo = new JComboBox() { private static final long serialVersionUID = -3748305421049121671L; + @Override public ComboBoxUI getUI() { return super.getUI(); @@ -167,7 +171,7 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { this.creatorAddressCombo = creatorAddressCombo; final Border line = BorderFactory.createLineBorder(Color.LIGHT_GRAY); - JComponent editor = (JComponent)(creatorAddressCombo.getEditor().getEditorComponent()); + JComponent editor = (JComponent) (creatorAddressCombo.getEditor().getEditorComponent()); editor.setForeground(Color.RED); Wallet wallet = UIEthereumManager.ethereum.getWallet(); @@ -193,7 +197,7 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { creatorAddressCombo.setPopupVisible(false); Object child = creatorAddressCombo.getAccessibleContext().getAccessibleChild(0); - BasicComboPopup popup = (BasicComboPopup)child; + BasicComboPopup popup = (BasicComboPopup) child; JList list = popup.getList(); list.setSelectionBackground(Color.cyan); @@ -219,7 +223,7 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { private void populateContractDetails() { byte[] addr = Utils.addressStringToBytes(contractAddrInput.getText()); - if(addr == null) { + if (addr == null) { alertStatusMsg("Not a valid contract address"); return; } @@ -281,7 +285,7 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { detailPanel.setVisible(false); JTextField contractCode = new JTextField(15); - contractCode.setText(Hex.toHexString( programCode )); + contractCode.setText(Hex.toHexString(programCode)); GUIUtils.addStyle(contractCode, "Code: "); contractCode.setBounds(70, 230, 350, 45); @@ -310,7 +314,7 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { private void playContractCall() { byte[] addr = Utils.addressStringToBytes(contractAddrInput.getText()); - if(addr == null) { + if (addr == null) { alertStatusMsg("Not a valid contract address"); return; } @@ -396,12 +400,12 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { Object[] lexaList = msgDataTA.getText().split(","); data = ByteUtil.encodeDataList(lexaList); } else { - data = new byte[] {}; + data = new byte[]{}; } - byte[] contractAddress = Hex.decode( contractAddrInput.getText()); + byte[] contractAddress = Hex.decode(contractAddrInput.getText()); - Account account = ((AccountWrapper)creatorAddressCombo.getSelectedItem()).getAccount(); + Account account = ((AccountWrapper) creatorAddressCombo.getSelectedItem()).getAccount(); byte[] senderPrivKey = account.getEcKey().getPrivKeyBytes(); @@ -409,16 +413,16 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { BigInteger gasPrice = new BigInteger("10000000000000"); BigInteger gasBI = new BigInteger(gasInput.getText()); - byte[] gasValue = BigIntegers.asUnsignedByteArray(gasBI); + byte[] gasValue = BigIntegers.asUnsignedByteArray(gasBI); BigInteger endowment = new BigInteger("1000"); if (logger.isInfoEnabled()) { logger.info("Contract call:"); logger.info("tx.nonce: {}", nonce == null ? "null" : nonce.toString()); - logger.info("tx.gasPrice: {}", Hex.toHexString(BigIntegers.asUnsignedByteArray( gasPrice ))); + logger.info("tx.gasPrice: {}", Hex.toHexString(BigIntegers.asUnsignedByteArray(gasPrice))); logger.info("tx.gasValue: {}", Hex.toHexString(gasValue)); logger.info("tx.address: {}", Hex.toHexString(contractAddress)); - logger.info("tx.endowment: {}", Hex.toHexString(BigIntegers.asUnsignedByteArray( endowment))); + logger.info("tx.endowment: {}", Hex.toHexString(BigIntegers.asUnsignedByteArray(endowment))); logger.info("tx.data: {}", Hex.toHexString(data)); } diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/ContractSubmitDialog.java b/ethereumj-studio/src/main/java/org/ethereum/gui/ContractSubmitDialog.java index dcebc5d1..8800e763 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/ContractSubmitDialog.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/ContractSubmitDialog.java @@ -19,6 +19,7 @@ import java.util.Collection; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 18/05/14 22:21 */ @@ -31,7 +32,7 @@ class ContractSubmitDialog extends JDialog implements MessageAwareDialog { final JTextField gasInput; final JTextField contractAddrInput; - private byte[] initByteCode; + private byte[] initByteCode; JLabel statusMsg = null; @@ -50,7 +51,7 @@ class ContractSubmitDialog extends JDialog implements MessageAwareDialog { gasInput = new JTextField(5); GUIUtils.addStyle(gasInput, "Gas: "); - JTextArea contractDataTA = new JTextArea(); + JTextArea contractDataTA = new JTextArea(); contractDataTA.setLineWrap(true); JScrollPane contractDataInput = new JScrollPane(contractDataTA); GUIUtils.addStyle(contractDataTA, null, false); @@ -103,7 +104,8 @@ class ContractSubmitDialog extends JDialog implements MessageAwareDialog { Block lastBlock = UIEthereumManager.ethereum.getBlockchain().getBestBlock(); ProgramPlayDialog.createAndShowGUI(tx.getData(), tx, lastBlock); - }} + } + } ); JLabel statusMessage = new JLabel(""); @@ -121,7 +123,8 @@ class ContractSubmitDialog extends JDialog implements MessageAwareDialog { public void mouseClicked(MouseEvent e) { dialog.dispose(); - }} + } + } ); URL approveIconURL = ClassLoader.getSystemResource("buttons/approve.png"); @@ -160,7 +163,7 @@ class ContractSubmitDialog extends JDialog implements MessageAwareDialog { this.creatorAddressCombo = creatorAddressCombo; final Border line = BorderFactory.createLineBorder(Color.LIGHT_GRAY); - JComponent editor = (JComponent)(creatorAddressCombo.getEditor().getEditorComponent()); + JComponent editor = (JComponent) (creatorAddressCombo.getEditor().getEditorComponent()); editor.setForeground(Color.RED); Wallet wallet = UIEthereumManager.ethereum.getWallet(); @@ -186,7 +189,7 @@ class ContractSubmitDialog extends JDialog implements MessageAwareDialog { creatorAddressCombo.setPopupVisible(false); Object child = creatorAddressCombo.getAccessibleContext().getAccessibleChild(0); - BasicComboPopup popup = (BasicComboPopup)child; + BasicComboPopup popup = (BasicComboPopup) child; JList list = popup.getList(); list.setSelectionBackground(Color.cyan); @@ -273,14 +276,14 @@ class ContractSubmitDialog extends JDialog implements MessageAwareDialog { private Transaction createTransaction() { - Account account = ((AccountWrapper)creatorAddressCombo.getSelectedItem()).getAccount(); + Account account = ((AccountWrapper) creatorAddressCombo.getSelectedItem()).getAccount(); byte[] senderPrivKey = account.getEcKey().getPrivKeyBytes(); BigInteger nonce = UIEthereumManager.ethereum.getRepository().getNonce(account.getAddress()); byte[] gasPrice = new BigInteger("10000000000000").toByteArray(); BigInteger gasBI = new BigInteger(gasInput.getText()); - byte[] gasValue = BigIntegers.asUnsignedByteArray(gasBI); + byte[] gasValue = BigIntegers.asUnsignedByteArray(gasBI); byte[] endowment = BigIntegers.asUnsignedByteArray(new BigInteger("1000")); byte[] zeroAddress = null; @@ -298,13 +301,13 @@ class ContractSubmitDialog extends JDialog implements MessageAwareDialog { private boolean validInput() { - Account account = ((AccountWrapper)creatorAddressCombo.getSelectedItem()).getAccount(); + Account account = ((AccountWrapper) creatorAddressCombo.getSelectedItem()).getAccount(); BigInteger currentBalance = UIEthereumManager.ethereum.getRepository().getBalance(account.getAddress()); long currGasPrice = UIEthereumManager.ethereum.getBlockchain().getGasPrice(); BigInteger gasPrice = BigInteger.valueOf(currGasPrice); - BigInteger gasInput = new BigInteger( this.gasInput.getText()); + BigInteger gasInput = new BigInteger(this.gasInput.getText()); boolean canAfford = currentBalance.compareTo(gasPrice.multiply(gasInput)) >= 0; @@ -337,7 +340,7 @@ class ContractSubmitDialog extends JDialog implements MessageAwareDialog { public String toString() { String addressShort = Utils.getAddressShortString(account.getEcKey().getAddress()); - String valueShort = Utils.getValueShortString( + String valueShort = Utils.getValueShortString( UIEthereumManager.ethereum.getRepository().getBalance(account.getAddress()) ); diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/GUIUtils.java b/ethereumj-studio/src/main/java/org/ethereum/gui/GUIUtils.java index 7960dafd..aa70b471 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/GUIUtils.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/GUIUtils.java @@ -12,6 +12,7 @@ import java.awt.*; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 23/05/2014 13:51 */ diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/PayOutDialog.java b/ethereumj-studio/src/main/java/org/ethereum/gui/PayOutDialog.java index b0e3e70d..f14d1f47 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/PayOutDialog.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/PayOutDialog.java @@ -20,6 +20,7 @@ import javax.swing.*; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 18/05/14 22:21 */ @@ -122,7 +123,7 @@ class PayOutDialog extends JDialog implements MessageAwareDialog { Transaction tx = new Transaction( BigIntegers.asUnsignedByteArray(nonce), - gasPrice, + gasPrice, BigIntegers.asUnsignedByteArray(fee), address, BigIntegers.asUnsignedByteArray(value), null); @@ -149,7 +150,7 @@ class PayOutDialog extends JDialog implements MessageAwareDialog { private boolean validInput() { - if (UIEthereumManager.ethereum.isBlockchainLoading()){ + if (UIEthereumManager.ethereum.isBlockchainLoading()) { alertStatusMsg("No transaction is allowed during block chain downloading."); return false; } @@ -236,10 +237,10 @@ class PayOutDialog extends JDialog implements MessageAwareDialog { rootPane.getActionMap().put("ESCAPE", actionListener); SwingUtilities.invokeLater(new Runnable() { - public void run() { - setSize(500, 255); - setVisible(true); - } + public void run() { + setSize(500, 255); + setVisible(true); + } }); diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/PeersTableModel.java b/ethereumj-studio/src/main/java/org/ethereum/gui/PeersTableModel.java index 37350968..55cb9c6d 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/PeersTableModel.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/PeersTableModel.java @@ -20,6 +20,7 @@ import com.maxmind.geoip.Location; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 25/04/14 07:04 */ @@ -71,7 +72,7 @@ public class PeersTableModel extends AbstractTableModel { String countryCode = peerInfo.getLocation().countryCode; ImageIcon flagIcon = null; - if (countryCode != null){ + if (countryCode != null) { URL flagURL = ClassLoader.getSystemResource("flags/" + countryCode.toLowerCase() + ".png"); flagIcon = new ImageIcon(flagURL); } @@ -97,8 +98,7 @@ public class PeersTableModel extends AbstractTableModel { flagIcon = Utils.getImageIcon("disconnected.png"); } return flagIcon; - } - else return ""; + } else return ""; } public int getRowCount() { @@ -115,7 +115,7 @@ public class PeersTableModel extends AbstractTableModel { final Set peers = UIEthereumManager.ethereum.getPeers(); - synchronized (peers){ + synchronized (peers) { for (org.ethereum.net.peerdiscovery.PeerInfo peer : peers) { InetAddress addr = peer.getAddress(); @@ -127,23 +127,24 @@ public class PeersTableModel extends AbstractTableModel { } } - public PeerInfo getPeerInfo(int index){ + public PeerInfo getPeerInfo(int index) { return peerInfoList.get(index); } public class PeerInfo { - Location location; - InetAddress ip; - boolean connected; + Location location; + InetAddress ip; + boolean connected; long lastAccessed = 0; HelloMessage handshakeHelloMessage; StatusMessage handshakeStatusMessage; private PeerInfo(Location location, InetAddress ip, - boolean isConnected, long lastAccessed, HelloMessage helloMessage, StatusMessage statusMessage) { + boolean isConnected, long lastAccessed, HelloMessage helloMessage, StatusMessage + statusMessage) { if (location == null) this.location = new Location(); @@ -181,8 +182,8 @@ public class PeersTableModel extends AbstractTableModel { ", ip=" + ip + ", connected=" + connected + ", lastAccessed=" + lastAccessed + - '}' + "\n -->" + (handshakeHelloMessage == null ?"" : handshakeHelloMessage.toString()) - + "\n -->" + (handshakeStatusMessage == null?"" : handshakeStatusMessage.toString()); + '}' + "\n -->" + (handshakeHelloMessage == null ? "" : handshakeHelloMessage.toString()) + + "\n -->" + (handshakeStatusMessage == null ? "" : handshakeStatusMessage.toString()); } } } diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/PeersTableWindow.java b/ethereumj-studio/src/main/java/org/ethereum/gui/PeersTableWindow.java index 8b32b298..887a2e0c 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/PeersTableWindow.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/PeersTableWindow.java @@ -1,7 +1,6 @@ package org.ethereum.gui; - import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; @@ -18,6 +17,7 @@ import static org.ethereum.config.SystemProperties.CONFIG; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 25/04/14 07:11 */ @@ -25,7 +25,7 @@ public class PeersTableWindow extends JFrame { // Instance attributes used in this example private JPanel topPanel; - private JTable table; + private JTable table; private JScrollPane scrollPane; private Timer updater = new Timer(); @@ -61,7 +61,7 @@ public class PeersTableWindow extends JFrame { table.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { - JTable table =(JTable) me.getSource(); + JTable table = (JTable) me.getSource(); Point p = me.getPoint(); int row = table.rowAtPoint(p); PeersTableModel model = (PeersTableModel) table.getModel(); diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/ProgramPlayDialog.java b/ethereumj-studio/src/main/java/org/ethereum/gui/ProgramPlayDialog.java index 56c311b8..2ab14258 100755 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/ProgramPlayDialog.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/ProgramPlayDialog.java @@ -18,6 +18,7 @@ import java.util.List; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 02/06/2014 16:58 */ @@ -51,7 +52,7 @@ public class ProgramPlayDialog extends JPanel implements ActionListener, program.fullTrace(); vm.play(program); - if(programInvoke.getRepository() != null) + if (programInvoke.getRepository() != null) programInvoke.getRepository().rollback(); doGUI(); @@ -114,8 +115,8 @@ public class ProgramPlayDialog extends JPanel implements ActionListener, @Override public void stateChanged(ChangeEvent e) { - JSlider source = (JSlider)e.getSource(); - int step = (int)source.getValue(); + JSlider source = (JSlider) e.getSource(); + int step = (int) source.getValue(); int i = source.getValue(); String out = outputList.get(i); @@ -134,7 +135,7 @@ public class ProgramPlayDialog extends JPanel implements ActionListener, final ProgramPlayDialog ppd; if (tx != null) ppd = new ProgramPlayDialog(runCode, tx, lastBlock); - else{ + else { ppd = new ProgramPlayDialog(runCode); } @@ -176,7 +177,7 @@ public class ProgramPlayDialog extends JPanel implements ActionListener, outputList.add(out); } - public static void main(String []args) { + public static void main(String[] args) { /* Turn off metal's use of bold fonts */ UIManager.put("swing.boldMetal", Boolean.FALSE); @@ -184,7 +185,7 @@ public class ProgramPlayDialog extends JPanel implements ActionListener, //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. - String asmCode ="11 0 MSTORE 22 32 MSTORE 33 64 MSTORE 44 96 MSTORE 55 128 MSTORE 66 160 MSTORE 192 0 RETURN"; + String asmCode = "11 0 MSTORE 22 32 MSTORE 33 64 MSTORE 44 96 MSTORE 55 128 MSTORE 66 160 MSTORE 192 0 RETURN"; // final byte[] code = SerpentCompiler.compileAssemblyToMachine(asmCode); final byte[] code = Hex.decode("7f4e616d65526567000000000000000000000000000000000000000000000000003057307f4e616d6552656700000000000000000000000000000000000000000000000000573360455760415160566000396000f20036602259604556330e0f600f5933ff33560f601e5960003356576000335700604158600035560f602b590033560f60365960003356573360003557600035335700"); diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/SerpentEditor.java b/ethereumj-studio/src/main/java/org/ethereum/gui/SerpentEditor.java index df725c25..d26bfc91 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/SerpentEditor.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/SerpentEditor.java @@ -20,6 +20,7 @@ import static org.ethereum.config.SystemProperties.CONFIG; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 24/04/14 11:32 */ @@ -28,12 +29,12 @@ public class SerpentEditor extends JFrame { private Logger logger = LoggerFactory.getLogger("gui"); private String codeSample = "\n\n\n" + - "" + - "if !contract.storage[msg.data[0]]:\n" + - " contract.storage[msg.data[0]] = msg.data[1]\n" + - " return(1)\n" + - "else:\n" + - " return(0)\n"; + "" + + "if !contract.storage[msg.data[0]]:\n" + + " contract.storage[msg.data[0]] = msg.data[1]\n" + + " return(1)\n" + + "else:\n" + + " return(0)\n"; private String codeSample2 = "\n\n\n" + "" + @@ -88,7 +89,7 @@ public class SerpentEditor extends JFrame { this.setIconImage(img); this.setLocation(30, 70); - AbstractTokenMakerFactory atmf = (AbstractTokenMakerFactory)TokenMakerFactory.getDefaultInstance(); + AbstractTokenMakerFactory atmf = (AbstractTokenMakerFactory) TokenMakerFactory.getDefaultInstance(); atmf.putMapping("text/serpent", "org.ethereum.gui.SerpentTokenMaker"); codeArea = new RSyntaxTextArea(32, 80); @@ -191,7 +192,7 @@ public class SerpentEditor extends JFrame { result.setVisible(true); result.setText(th.getMessage()); result.setForeground(Color.RED); - return ; + return; } result.setForeground(Color.BLACK.brighter()); result.setVisible(true); @@ -258,7 +259,7 @@ public class SerpentEditor extends JFrame { put(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK), "OpenFileButton"); - mainContentPane.getActionMap().put("OpenFileButton",openFile); + mainContentPane.getActionMap().put("OpenFileButton", openFile); button.addActionListener(new ActionListener() { @Override @@ -299,7 +300,7 @@ public class SerpentEditor extends JFrame { put(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK), "OpenSaveButtonAlways"); - mainContentPane.getActionMap().put("OpenSaveButtonAlways",saveNewFile); + mainContentPane.getActionMap().put("OpenSaveButtonAlways", saveNewFile); Action saveFile = new AbstractAction() { @Override @@ -312,7 +313,7 @@ public class SerpentEditor extends JFrame { put(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK), "OpenSaveButton"); - mainContentPane.getActionMap().put("OpenSaveButton",saveFile); + mainContentPane.getActionMap().put("OpenSaveButton", saveFile); button.addActionListener(new ActionListener() { @Override @@ -365,7 +366,7 @@ public class SerpentEditor extends JFrame { put(KeyStroke.getKeyStroke(KeyEvent.VK_F9, InputEvent.CTRL_DOWN_MASK), "CompileButton"); - mainContentPane.getActionMap().put("CompileButton",compile); + mainContentPane.getActionMap().put("CompileButton", compile); button.addActionListener(new ActionListener() { @Override @@ -396,7 +397,7 @@ public class SerpentEditor extends JFrame { InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK), "DeployButton"); - mainContentPane.getActionMap().put("DeployButton",deploy); + mainContentPane.getActionMap().put("DeployButton", deploy); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { @@ -455,9 +456,9 @@ public class SerpentEditor extends JFrame { } switch (fileChooser.showOpenDialog(SerpentEditor.this)) { - case JFileChooser.APPROVE_OPTION: - file = fileChooser.getSelectedFile(); - break; + case JFileChooser.APPROVE_OPTION: + file = fileChooser.getSelectedFile(); + break; } return file; } diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/SerpentTokenMaker.java b/ethereumj-studio/src/main/java/org/ethereum/gui/SerpentTokenMaker.java index 61965d22..06c449f9 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/SerpentTokenMaker.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/SerpentTokenMaker.java @@ -7,6 +7,7 @@ import org.fife.ui.rsyntaxtextarea.*; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 24/04/14 11:52 */ @@ -46,14 +47,14 @@ public class SerpentTokenMaker extends AbstractTokenMaker { // into here as "identifiers," we have to see what the token // really is... case Token.IDENTIFIER: - int value = wordsToHighlight.get(segment, start,end); - if (value!=-1) + int value = wordsToHighlight.get(segment, start, end); + if (value != -1) tokenType = value; break; case Token.ANNOTATION: - value = wordsToHighlight.get(segment, start,end); - if (value!=-1) + value = wordsToHighlight.get(segment, start, end); + if (value != -1) tokenType = value; break; } @@ -65,11 +66,11 @@ public class SerpentTokenMaker extends AbstractTokenMaker { * line to "comment" it in a this programming language. * * @return The start and end strings to add to a line to "comment" - * it out. + * it out. */ @Override public String[] getLineCommentStartAndEnd() { - return new String[] { "#", null }; + return new String[]{"#", null}; } /** @@ -78,18 +79,18 @@ public class SerpentTokenMaker extends AbstractTokenMaker { * * @param type The token type. * @return Whether tokens of this type should have "mark occurrences" - * enabled. + * enabled. */ @Override public boolean getMarkOccurrencesOfTokenType(int type) { - return type==Token.IDENTIFIER || type==Token.VARIABLE; + return type == Token.IDENTIFIER || type == Token.VARIABLE; } /** * Returns the words to highlight for Windows batch files. * * @return A TokenMap containing the words to highlight for - * Windows batch files. + * Windows batch files. * @see org.fife.ui.rsyntaxtextarea.AbstractTokenMaker#getWordsToHighlight */ @Override @@ -98,40 +99,40 @@ public class SerpentTokenMaker extends AbstractTokenMaker { TokenMap tokenMap = new TokenMap(false); // Ignore case. int reservedWord = Token.RESERVED_WORD; - tokenMap.put("set", reservedWord); - tokenMap.put("if", reservedWord); - tokenMap.put("else", reservedWord); - tokenMap.put("elif", reservedWord); - tokenMap.put("seq", reservedWord); - tokenMap.put("while", reservedWord); - tokenMap.put("byte", reservedWord); - tokenMap.put("access", reservedWord); - tokenMap.put("arrset", reservedWord); - tokenMap.put("set_and_inc", reservedWord); - tokenMap.put("array", reservedWord); - tokenMap.put("getch", reservedWord); - tokenMap.put("setch", reservedWord); - tokenMap.put("string", reservedWord); - tokenMap.put("send", reservedWord); - tokenMap.put("create", reservedWord); - tokenMap.put("sha3", reservedWord); - tokenMap.put("sha3bytes", reservedWord); - tokenMap.put("sload", reservedWord); - tokenMap.put("sstore", reservedWord); - tokenMap.put("calldataload", reservedWord); - tokenMap.put("id", reservedWord); - tokenMap.put("return", reservedWord); - tokenMap.put("suicide", reservedWord); + tokenMap.put("set", reservedWord); + tokenMap.put("if", reservedWord); + tokenMap.put("else", reservedWord); + tokenMap.put("elif", reservedWord); + tokenMap.put("seq", reservedWord); + tokenMap.put("while", reservedWord); + tokenMap.put("byte", reservedWord); + tokenMap.put("access", reservedWord); + tokenMap.put("arrset", reservedWord); + tokenMap.put("set_and_inc", reservedWord); + tokenMap.put("array", reservedWord); + tokenMap.put("getch", reservedWord); + tokenMap.put("setch", reservedWord); + tokenMap.put("string", reservedWord); + tokenMap.put("send", reservedWord); + tokenMap.put("create", reservedWord); + tokenMap.put("sha3", reservedWord); + tokenMap.put("sha3bytes", reservedWord); + tokenMap.put("sload", reservedWord); + tokenMap.put("sstore", reservedWord); + tokenMap.put("calldataload", reservedWord); + tokenMap.put("id", reservedWord); + tokenMap.put("return", reservedWord); + tokenMap.put("suicide", reservedWord); - tokenMap.put("stop", reservedWord); + tokenMap.put("stop", reservedWord); int function = Token.FUNCTION; - tokenMap.put("msg", function); - tokenMap.put("data", function); - tokenMap.put("contract", function); - tokenMap.put("storage", function); - tokenMap.put("block", function); - tokenMap.put("tx", function); + tokenMap.put("msg", function); + tokenMap.put("data", function); + tokenMap.put("contract", function); + tokenMap.put("storage", function); + tokenMap.put("block", function); + tokenMap.put("tx", function); // ALL the assembly tokens int reservedWord2 = Token.RESERVED_WORD_2; @@ -142,8 +143,8 @@ public class SerpentTokenMaker extends AbstractTokenMaker { } int dataType = Token.ANNOTATION; - tokenMap.put("init", dataType); - tokenMap.put("code", dataType); + tokenMap.put("init", dataType); + tokenMap.put("code", dataType); return tokenMap; } @@ -173,10 +174,10 @@ public class SerpentTokenMaker extends AbstractTokenMaker { int newStartOffset = startOffset - offset; currentTokenStart = offset; - currentTokenType = startTokenType; + currentTokenType = startTokenType; //beginning: - for (int i=offset; i -1) { - addToken(text, currentTokenStart,i, Token.OPERATOR, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i, Token.OPERATOR, newStartOffset + + currentTokenStart); currentTokenType = Token.NULL; break; - } - else { + } else { currentTokenType = Token.IDENTIFIER; break; } @@ -259,8 +258,8 @@ public class SerpentTokenMaker extends AbstractTokenMaker { switch (c) { case '/': - addToken(text, currentTokenStart,i-1, - Token.COMMENT_EOL, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, + Token.COMMENT_EOL, newStartOffset + currentTokenStart); currentTokenStart = i; currentTokenType = Token.COMMENT_EOL; break; @@ -269,7 +268,8 @@ public class SerpentTokenMaker extends AbstractTokenMaker { break; // Still whitespace. case '"': - addToken(text, currentTokenStart,i-1, Token.WHITESPACE, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.WHITESPACE, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_STRING_DOUBLE; break; @@ -278,55 +278,57 @@ public class SerpentTokenMaker extends AbstractTokenMaker { // The "separators". case '(': case ')': - addToken(text, currentTokenStart,i-1, Token.WHITESPACE, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.SEPARATOR, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.WHITESPACE, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.SEPARATOR, newStartOffset + i); currentTokenType = Token.NULL; break; // The "separators2". case ',': case ';': - addToken(text, currentTokenStart,i-1, Token.WHITESPACE, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.WHITESPACE, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; break; // Newer version of EOL comments, or a label case ':': - addToken(text, currentTokenStart,i-1, Token.WHITESPACE, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.WHITESPACE, newStartOffset + + currentTokenStart); currentTokenStart = i; // If the previous (whitespace) token was the first token // added, this is a new-style comment or a label if (firstToken.getNextToken() == null) { if (i < end - 1 && array[i + 1] == ':') { // new-style comment currentTokenType = Token.COMMENT_EOL; - } - else { // Label + } else { // Label currentTokenType = Token.PREPROCESSOR; } - } - else { // Just a colon + } else { // Just a colon currentTokenType = Token.IDENTIFIER; } break; default: // Add the whitespace token and start anew. - addToken(text, currentTokenStart,i-1, Token.WHITESPACE, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.WHITESPACE, newStartOffset + + currentTokenStart); currentTokenStart = i; // Just to speed things up a tad, as this will usually be the case (if spaces above failed). - if (RSyntaxUtilities.isLetterOrDigit(c) || c=='\\') { + if (RSyntaxUtilities.isLetterOrDigit(c) || c == '\\') { currentTokenType = Token.IDENTIFIER; break; } - int indexOf = operators.indexOf(c,0); + int indexOf = operators.indexOf(c, 0); if (indexOf > -1) { - addToken(text, currentTokenStart,i, Token.OPERATOR, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i, Token.OPERATOR, newStartOffset + + currentTokenStart); currentTokenType = Token.NULL; break; - } - else { + } else { currentTokenType = Token.IDENTIFIER; } } // End of switch (c). @@ -340,20 +342,22 @@ public class SerpentTokenMaker extends AbstractTokenMaker { case ' ': case '\t': // Check for REM comments. - if (i-currentTokenStart==3 && - (array[i-3]=='r' || array[i-3]=='R') && - (array[i-2]=='e' || array[i-2]=='E') && - (array[i-1]=='m' || array[i-1]=='M')) { + if (i - currentTokenStart == 3 && + (array[i - 3] == 'r' || array[i - 3] == 'R') && + (array[i - 2] == 'e' || array[i - 2] == 'E') && + (array[i - 1] == 'm' || array[i - 1] == 'M')) { currentTokenType = Token.COMMENT_EOL; break; } - addToken(text, currentTokenStart,i-1, Token.IDENTIFIER, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.WHITESPACE; break; case '"': - addToken(text, currentTokenStart,i-1, Token.IDENTIFIER, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + + currentTokenStart); currentTokenStart = i; currentTokenType = Token.ERROR_STRING_DOUBLE; break; @@ -362,10 +366,10 @@ public class SerpentTokenMaker extends AbstractTokenMaker { // Should be part of identifiers, but not at end of "REM". case '\\': // Check for REM comments. - if (i-currentTokenStart==3 && - (array[i-3]=='r' || array[i-3]=='R') && - (array[i-2]=='e' || array[i-2]=='E') && - (array[i-1]=='m' || array[i-1]=='M')) { + if (i - currentTokenStart == 3 && + (array[i - 3] == 'r' || array[i - 3] == 'R') && + (array[i - 2] == 'e' || array[i - 2] == 'E') && + (array[i - 1] == 'm' || array[i - 1] == 'M')) { currentTokenType = Token.COMMENT_EOL; } break; @@ -377,30 +381,33 @@ public class SerpentTokenMaker extends AbstractTokenMaker { // The "separators". case '(': case ')': - addToken(text, currentTokenStart,i-1, Token.IDENTIFIER, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.SEPARATOR, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.SEPARATOR, newStartOffset + i); currentTokenType = Token.NULL; break; // The "separators2". case ',': case ';': - addToken(text, currentTokenStart,i-1, Token.IDENTIFIER, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.IDENTIFIER, newStartOffset+i); + addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.IDENTIFIER, newStartOffset + i); currentTokenType = Token.NULL; break; default: // Just to speed things up a tad, as this will usually be the case. - if (RSyntaxUtilities.isLetterOrDigit(c) || c=='\\') { + if (RSyntaxUtilities.isLetterOrDigit(c) || c == '\\') { break; } int indexOf = operators.indexOf(c); - if (indexOf>-1) { - addToken(text, currentTokenStart,i-1, Token.IDENTIFIER, newStartOffset+currentTokenStart); - addToken(text, i,i, Token.OPERATOR, newStartOffset+i); + if (indexOf > -1) { + addToken(text, currentTokenStart, i - 1, Token.IDENTIFIER, newStartOffset + + currentTokenStart); + addToken(text, i, i, Token.OPERATOR, newStartOffset + i); currentTokenType = Token.NULL; break; } @@ -413,11 +420,11 @@ public class SerpentTokenMaker extends AbstractTokenMaker { if (i + 1 >= array.length) break; - char nextC = array[i+1]; + char nextC = array[i + 1]; if (nextC == '/') { i = end - 1; - addToken(text, currentTokenStart,i, Token.COMMENT_EOL, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i, Token.COMMENT_EOL, newStartOffset + currentTokenStart); // We need to set token type to null so at the bottom we don't add one more token. currentTokenType = Token.NULL; } @@ -425,7 +432,7 @@ public class SerpentTokenMaker extends AbstractTokenMaker { case Token.PREPROCESSOR: // Used for labels i = end - 1; - addToken(text, currentTokenStart,i, Token.PREPROCESSOR, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, i, Token.PREPROCESSOR, newStartOffset + currentTokenStart); // We need to set token type to null so at the bottom we don't add one more token. currentTokenType = Token.NULL; break; @@ -464,8 +471,7 @@ public class SerpentTokenMaker extends AbstractTokenMaker { break; } } // End of switch (c). - } - else { // Character other than first after the '%'. + } else { // Character other than first after the '%'. if (bracketVariable == true) { if (c == '}') { addToken(text, currentTokenStart, i, Token.VARIABLE, newStartOffset + currentTokenStart); @@ -483,13 +489,13 @@ public class SerpentTokenMaker extends AbstractTokenMaker { // Deal with the (possibly there) last token. if (currentTokenType != Token.NULL) { // Check for REM comments. - if (end-currentTokenStart==3 && - (array[end-3]=='r' || array[end-3]=='R') && - (array[end-2]=='e' || array[end-2]=='E') && - (array[end-1]=='m' || array[end-1]=='M')) { + if (end - currentTokenStart == 3 && + (array[end - 3] == 'r' || array[end - 3] == 'R') && + (array[end - 2] == 'e' || array[end - 2] == 'E') && + (array[end - 1] == 'm' || array[end - 1] == 'M')) { currentTokenType = Token.COMMENT_EOL; } - addToken(text, currentTokenStart,end-1, currentTokenType, newStartOffset+currentTokenStart); + addToken(text, currentTokenStart, end - 1, currentTokenType, newStartOffset + currentTokenStart); } addNullToken(); // Return the first token in our linked peerInfoList. diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/StateExplorerWindow.java b/ethereumj-studio/src/main/java/org/ethereum/gui/StateExplorerWindow.java index ef1e8713..c8d0022e 100755 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/StateExplorerWindow.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/StateExplorerWindow.java @@ -93,9 +93,9 @@ public class StateExplorerWindow extends JFrame { public void itemStateChanged(ItemEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { - if(accountsListWindow == null) - accountsListWindow = new AccountsListWindow(); - accountsListWindow.setVisible(true); + if (accountsListWindow == null) + accountsListWindow = new AccountsListWindow(); + accountsListWindow.setVisible(true); } }); } @@ -109,25 +109,25 @@ public class StateExplorerWindow extends JFrame { JButton btnSearch = new JButton("Search"); horizontalBox.add(btnSearch); - btnSearch.addMouseListener(new MouseAdapter(){ + btnSearch.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { byte[] addr = Utils.addressStringToBytes(txfAccountAddress.getText()); - if(addr != null) + if (addr != null) searchAccount(addr); } }); btnPlayCode = new JButton("Play Code"); horizontalBox.add(btnPlayCode); - btnPlayCode.addMouseListener(new MouseAdapter(){ + btnPlayCode.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { byte[] addr = Utils.addressStringToBytes(txfAccountAddress.getText()); - if(addr != null) { + if (addr != null) { Repository repository = UIEthereumManager.ethereum.getRepository(); byte[] code = repository.getCode(addr); - if(code != null) + if (code != null) ProgramPlayDialog.createAndShowGUI(code, null, null); } } @@ -195,16 +195,16 @@ public class StateExplorerWindow extends JFrame { JScrollPane scrollPane = new JScrollPane(tblStateDataTable); - scrollPane.setPreferredSize(new Dimension(600,200)); + scrollPane.setPreferredSize(new Dimension(600, 200)); panel.add(scrollPane); } - private void searchAccount(byte[] add){ + private void searchAccount(byte[] add) { txaPrinter.clean(); txaPrinter.println(accountDetailsString(add, dataModel)); } - private String accountDetailsString(byte[] account, StateDataTableModel dataModel){ + private String accountDetailsString(byte[] account, StateDataTableModel dataModel) { String ret = ""; // 1) print account address ret = "Account: " + Hex.toHexString(account) + "\n"; @@ -212,19 +212,19 @@ public class StateExplorerWindow extends JFrame { //2) print state Repository repository = UIEthereumManager.ethereum.getRepository(); AccountState state = repository.getAccountState(account); - if(state != null) + if (state != null) ret += state.toString() + "\n"; //3) print storage ContractDetails contractDetails = repository.getContractDetails(account); - if(contractDetails != null) { + if (contractDetails != null) { Map accountStorage = contractDetails.getStorage(); dataModel.setData(accountStorage); } //4) code print byte[] code = repository.getCode(account); - if(code != null) { + if (code != null) { ret += "\n\nCode:\n"; ret += Program.stringify(code, 0, ""); } @@ -237,9 +237,10 @@ public class StateExplorerWindow extends JFrame { Map data; DataEncodingType keyEncodingType = DataEncodingType.HEX; DataEncodingType valueEncodingType = DataEncodingType.HEX; - String[] columns = new String[]{ "Key", "Value"}; + String[] columns = new String[]{"Key", "Value"}; - public StateDataTableModel() { } + public StateDataTableModel() { + } public StateDataTableModel(Map initData) { setData(initData); @@ -251,12 +252,12 @@ public class StateExplorerWindow extends JFrame { } public void setKeyEncoding(DataEncodingType type) { - keyEncodingType = type; + keyEncodingType = type; fireTableDataChanged(); } public void setValueEncoding(DataEncodingType type) { - valueEncodingType = type; + valueEncodingType = type; fireTableDataChanged(); } @@ -267,7 +268,7 @@ public class StateExplorerWindow extends JFrame { @Override public int getRowCount() { - return data == null? 0:data.size(); + return data == null ? 0 : data.size(); } @Override @@ -279,42 +280,41 @@ public class StateExplorerWindow extends JFrame { public Object getValueAt(int rowIndex, int columnIndex) { DataWord key = (DataWord) this.data.keySet().toArray()[rowIndex]; - if(columnIndex == 0) { + if (columnIndex == 0) { return getDataWithEncoding(key.getData(), keyEncodingType); - } - else { + } else { DataWord value = this.data.get(key); return getDataWithEncoding(value.getData(), valueEncodingType); } } private String getDataWithEncoding(byte[] data, DataEncodingType enc) { - switch(enc) { - case STRING: - return new String(data); - case HEX: - return Hex.toHexString(data); - case NUMBER: - return new BigInteger(data).toString(); + switch (enc) { + case STRING: + return new String(data); + case HEX: + return Hex.toHexString(data); + case NUMBER: + return new BigInteger(data).toString(); } return data.toString(); } } - private enum DataEncodingType{ + private enum DataEncodingType { STRING, HEX, NUMBER; static public DataEncodingType getTypeFromString(String value) { - switch(value){ - case "String": - return STRING; - case "Hex": - return HEX; - case "Number": - return NUMBER; + switch (value) { + case "String": + return STRING; + case "Hex": + return HEX; + case "Number": + return NUMBER; } return STRING; } diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/ToolBar.java b/ethereumj-studio/src/main/java/org/ethereum/gui/ToolBar.java index 2e9c6091..f29c547d 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/ToolBar.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/ToolBar.java @@ -16,6 +16,7 @@ import java.awt.event.WindowEvent; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 30/04/14 06:29 */ @@ -24,7 +25,7 @@ public class ToolBar extends JFrame { private Logger introLogger = LoggerFactory.getLogger("Intro"); private ConnectionConsoleWindow connectionConsoleWindow = null; - private PeersTableWindow mainFrame = null; + private PeersTableWindow mainFrame = null; private BlockChainTable blockchainWindow = null; private WalletWindow walletWindow = null; private SerpentEditor serpentEditor = null; @@ -139,13 +140,13 @@ public class ToolBar extends JFrame { if (e.getStateChange() == ItemEvent.SELECTED) { SwingUtilities.invokeLater(new Runnable() { public void run() { - if (connectionConsoleWindow == null) - connectionConsoleWindow = new ConnectionConsoleWindow(ToolBar.this); - connectionConsoleWindow.setVisible(true); + if (connectionConsoleWindow == null) + connectionConsoleWindow = new ConnectionConsoleWindow(ToolBar.this); + connectionConsoleWindow.setVisible(true); } }); } else if (e.getStateChange() == ItemEvent.DESELECTED) { - connectionConsoleWindow.setVisible(false); + connectionConsoleWindow.setVisible(false); } } }); @@ -165,12 +166,12 @@ public class ToolBar extends JFrame { SwingUtilities.invokeLater(new Runnable() { public void run() { if (mainFrame == null) - mainFrame = new PeersTableWindow(ToolBar.this); - mainFrame.setVisible( true ); + mainFrame = new PeersTableWindow(ToolBar.this); + mainFrame.setVisible(true); } }); } else if (e.getStateChange() == ItemEvent.DESELECTED) { - mainFrame.setVisible( false ); + mainFrame.setVisible(false); } } }); diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/WalletAddressPanel.java b/ethereumj-studio/src/main/java/org/ethereum/gui/WalletAddressPanel.java index 9ba1044d..3c8dfabf 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/WalletAddressPanel.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/WalletAddressPanel.java @@ -18,10 +18,11 @@ import java.net.URL; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 17/05/14 12:32 */ -public class WalletAddressPanel extends JPanel{ +public class WalletAddressPanel extends JPanel { public WalletAddressPanel(final Account account) { @@ -68,7 +69,7 @@ public class WalletAddressPanel extends JPanel{ public void mouseClicked(MouseEvent e) { PayOutDialog payOutDialog = - new PayOutDialog((Frame)SwingUtilities.getAncestorOfClass(JFrame.class, + new PayOutDialog((Frame) SwingUtilities.getAncestorOfClass(JFrame.class, walletAddressPanel), account); } }); diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/WalletSumPanel.java b/ethereumj-studio/src/main/java/org/ethereum/gui/WalletSumPanel.java index dbcac010..9d843d12 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/WalletSumPanel.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/WalletSumPanel.java @@ -14,10 +14,11 @@ import java.net.URL; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 17/05/14 12:32 */ -public class WalletSumPanel extends JPanel{ +public class WalletSumPanel extends JPanel { public WalletSumPanel(BigInteger balance) { diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/WalletWindow.java b/ethereumj-studio/src/main/java/org/ethereum/gui/WalletWindow.java index dc5b734a..c6bb569d 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/WalletWindow.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/WalletWindow.java @@ -13,10 +13,11 @@ import java.net.URL; /** * www.ethereumJ.com + * * @author: Roman Mandeleil * Created on: 17/05/14 12:00 */ -public class WalletWindow extends JFrame implements Wallet.WalletListener{ +public class WalletWindow extends JFrame implements Wallet.WalletListener { WalletWindow walletWindow; ToolBar toolBar;