From e5fcf5b48e76c79a00a476440ae0eeae953fbf75 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 26 Dec 2014 09:36:37 +0100 Subject: [PATCH] Strip trailing whitespace --- README.md | 12 +- TODO.md | 28 ++-- ethereumj-core/README.md | 20 +-- ethereumj-core/pom.xml | 2 +- .../org/ethereum/config/SystemProperties.java | 12 +- .../java/org/ethereum/core/AccountState.java | 40 ++--- .../main/java/org/ethereum/core/Block.java | 46 +++--- .../java/org/ethereum/core/BlockHeader.java | 50 +++--- .../org/ethereum/core/BlockchainImpl.java | 40 ++--- .../java/org/ethereum/core/Denomination.java | 10 +- .../main/java/org/ethereum/core/Genesis.java | 34 ++-- .../java/org/ethereum/core/Transaction.java | 16 +- .../org/ethereum/core/TransactionReceipt.java | 6 +- .../main/java/org/ethereum/core/Wallet.java | 10 +- .../main/java/org/ethereum/crypto/ECKey.java | 46 +++--- .../java/org/ethereum/crypto/HashUtil.java | 10 +- .../java/org/ethereum/crypto/SHA3Helper.java | 16 +- .../org/ethereum/db/ByteArrayWrapper.java | 6 +- .../java/org/ethereum/db/ContractDetails.java | 2 +- .../main/java/org/ethereum/db/Database.java | 16 +- .../java/org/ethereum/db/DatabaseImpl.java | 20 +-- .../java/org/ethereum/facade/Repository.java | 66 ++++---- .../org/ethereum/json/EtherObjectMapper.java | 16 +- .../java/org/ethereum/json/JSONHelper.java | 50 +++--- .../ethereum/jsontestsuite/JSONReader.java | 4 +- .../java/org/ethereum/jsontestsuite/Logs.java | 2 +- .../org/ethereum/jsontestsuite/TestCase.java | 8 +- .../ethereum/jsontestsuite/TestRunner.java | 2 +- .../org/ethereum/manager/WorldManager.java | 16 +- .../main/java/org/ethereum/mine/Miner.java | 36 ++--- .../java/org/ethereum/net/BlockQueue.java | 40 ++--- .../org/ethereum/net/MessageRoundtrip.java | 2 +- .../org/ethereum/net/client/Capability.java | 8 +- .../org/ethereum/net/client/PeerClient.java | 4 +- .../ethereum/net/eth/BlockHashesMessage.java | 2 +- .../java/org/ethereum/net/eth/EthMessage.java | 2 +- .../org/ethereum/net/eth/EthMessageCodes.java | 6 +- .../net/eth/GetBlockHashesMessage.java | 10 +- .../ethereum/net/eth/GetBlocksMessage.java | 2 +- .../net/eth/GetTransactionsMessage.java | 4 +- .../org/ethereum/net/eth/NewBlockMessage.java | 4 +- .../org/ethereum/net/eth/StatusMessage.java | 4 +- .../ethereum/net/eth/TransactionsMessage.java | 14 +- .../org/ethereum/net/message/Message.java | 12 +- .../org/ethereum/net/message/ReasonCode.java | 32 ++-- .../ethereum/net/message/StaticMessages.java | 6 +- .../org/ethereum/net/p2p/GetPeersMessage.java | 2 +- .../org/ethereum/net/p2p/HelloMessage.java | 8 +- .../java/org/ethereum/net/p2p/P2pHandler.java | 12 +- .../main/java/org/ethereum/net/p2p/Peer.java | 2 +- .../org/ethereum/net/p2p/PeersMessage.java | 2 +- .../org/ethereum/net/p2p/PingMessage.java | 2 +- .../org/ethereum/net/p2p/PongMessage.java | 2 +- .../net/peerdiscovery/DiscoveryChannel.java | 2 +- .../net/peerdiscovery/PeerDiscovery.java | 6 +- .../net/peerdiscovery/RejectionLogger.java | 4 +- .../net/peerdiscovery/WorkerThread.java | 2 +- .../org/ethereum/net/server/PeerServer.java | 2 +- .../java/org/ethereum/net/shh/ShhHandler.java | 4 +- .../org/ethereum/net/shh/ShhMessageCodes.java | 2 +- .../org/ethereum/net/wire/MessageDecoder.java | 4 +- .../org/ethereum/net/wire/MessageEncoder.java | 4 +- .../org/ethereum/serpent/SerpentCompiler.java | 2 +- .../main/java/org/ethereum/trie/Cache.java | 6 +- .../src/main/java/org/ethereum/trie/Node.java | 46 +++--- .../src/main/java/org/ethereum/trie/Trie.java | 28 ++-- .../main/java/org/ethereum/trie/TrieImpl.java | 32 ++-- .../java/org/ethereum/trie/TrieIterator.java | 6 +- .../main/java/org/ethereum/util/ByteUtil.java | 48 +++--- .../org/ethereum/util/CompactEncoder.java | 46 +++--- .../java/org/ethereum/util/DecodeResult.java | 10 +- .../ethereum/util/FastByteComparisons.java | 6 +- .../main/java/org/ethereum/util/LRUMap.java | 2 +- .../src/main/java/org/ethereum/util/RLP.java | 72 ++++----- .../main/java/org/ethereum/util/RLPItem.java | 6 +- .../main/java/org/ethereum/util/RLPList.java | 2 +- .../main/java/org/ethereum/util/Utils.java | 18 +-- .../main/java/org/ethereum/util/Value.java | 6 +- .../main/java/org/ethereum/vm/DataWord.java | 36 ++--- .../main/java/org/ethereum/vm/GasCost.java | 6 +- .../java/org/ethereum/vm/MessageCall.java | 12 +- .../src/main/java/org/ethereum/vm/OpCode.java | 42 ++--- .../main/java/org/ethereum/vm/Program.java | 92 +++++------ .../ethereum/vm/ProgramInvokeFactoryImpl.java | 10 +- .../org/ethereum/vm/ProgramInvokeImpl.java | 4 +- .../ethereum/vm/ProgramInvokeMockImpl.java | 12 +- .../src/main/java/org/ethereum/vm/VM.java | 146 +++++++++--------- .../src/main/resources/system.properties | 6 +- .../java/test/ethereum/core/BlockTest.java | 14 +- .../java/test/ethereum/core/MinerTest.java | 10 +- .../java/test/ethereum/core/StateTest.java | 4 +- .../test/ethereum/core/TransactionTest.java | 38 ++--- .../java/test/ethereum/crypto/ECKeyTest.java | 36 ++--- .../ethereum/db/ByteArrayWrapperTest.java | 20 +-- .../test/ethereum/db/TrackDatabaseTest.java | 4 +- .../jsontestsuite/GitHubJSONTestSuite.java | 8 +- .../jsontestsuite/GitHubStateTest.java | 2 +- .../ethereum/jsontestsuite/GitHubVMTest.java | 16 +- .../java/test/ethereum/mine/MinerThread.java | 2 +- .../ethereum/net/BlockHashesMessageTest.java | 14 +- .../test/ethereum/net/BlocksMessageTest.java | 2 +- .../ethereum/net/DisconnectMessageTest.java | 4 +- .../net/GetBlockHashesMessageTest.java | 18 +-- .../ethereum/net/GetBlocksMessageTest.java | 14 +- .../test/ethereum/net/HelloMessageTest.java | 4 +- .../test/ethereum/net/PeersMessageTest.java | 2 +- .../ethereum/net/PingPongMessageTest.java | 4 +- .../ethereum/net/TransactionsMessageTest.java | 18 +-- .../ethereum/serpent/SerpentCompileTest.java | 8 +- .../java/test/ethereum/trie/TrieTest.java | 56 +++---- .../java/test/ethereum/util/ByteUtilTest.java | 34 ++-- .../ethereum/util/CompactEncoderTest.java | 6 +- .../java/test/ethereum/util/HashUtilTest.java | 16 +- .../test/java/test/ethereum/util/RLPTest.java | 134 ++++++++-------- .../java/test/ethereum/util/RlpTestData.java | 30 ++-- .../java/test/ethereum/util/UtilsTest.java | 8 +- .../java/test/ethereum/util/ValueTest.java | 4 +- .../java/test/ethereum/vm/DataWordTest.java | 44 +++--- .../test/ethereum/vm/ProgramMemoryTest.java | 62 ++++---- .../java/test/ethereum/vm/VMComplexTest.java | 16 +- .../java/test/ethereum/vm/VMCustomTest.java | 70 ++++----- .../test/java/test/ethereum/vm/VMTest.java | 82 +++++----- .../src/test/resources/system.properties | 8 +- ethereumj-core/track-untrack-local.bat | 4 +- ethereumj-studio/README.md | 14 +- ethereumj-studio/pom.xml | 2 +- ethereumj-studio/samples/call-me-more.se | 10 +- .../main/java/org/ethereum/geo/IpGeoDB.java | 2 +- .../org/ethereum/gui/AccountsListWindow.java | 36 ++--- .../org/ethereum/gui/ConsoleTokenMaker.java | 2 +- .../org/ethereum/gui/ContractCallDialog.java | 12 +- .../ethereum/gui/ContractSubmitDialog.java | 6 +- .../org/ethereum/gui/MessageAwareDialog.java | 2 +- .../java/org/ethereum/gui/PayOutDialog.java | 2 +- .../java/org/ethereum/gui/PeerInfoWindow.java | 4 +- .../org/ethereum/gui/PeersTableModel.java | 2 +- .../org/ethereum/gui/ProgramPlayDialog.java | 18 +-- .../java/org/ethereum/gui/SerpentEditor.java | 2 +- .../org/ethereum/gui/StateExplorerWindow.java | 102 ++++++------ .../main/java/org/ethereum/gui/ToolBar.java | 4 +- .../src/main/resources/system.properties | 6 +- ethereumj-studio/track-untrack-local.bat | 4 +- 142 files changed, 1301 insertions(+), 1301 deletions(-) diff --git a/README.md b/README.md index 40f8e1d7..4cfd8190 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ [![ScreenShot](http://i.imgur.com/lJw1Tui.jpg)] -# Welcome to ethereumj +# Welcome to ethereumj [![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/ethereum/ethereumj?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://travis-ci.org/ethereum/ethereumj.svg?branch=master)](https://travis-ci.org/ethereum/ethereumj) [![Coverage Status](https://coveralls.io/repos/ethereum/ethereumj/badge.png?branch=master)](https://coveralls.io/r/ethereum/ethereumj?branch=master) [![Stories in Progress](https://badge.waffle.io/ethereum/ethereumj.png?title=In%20Progress&label=in_progress)](https://waffle.io/ethereum/ethereumj) @@ -10,18 +10,18 @@ The ethereumj library is a Java implementation of the Ethereum protocol. -This repository currently contains: +This repository currently contains: * [core](ethereumj-core): the core library which can be included into your own Java project. - * [studio](ethereumj-studio): a simple graphic interface for Ethereum functionality and set of showcases for core usage. + * [studio](ethereumj-studio): a simple graphic interface for Ethereum functionality and set of showcases for core usage. For an early peek, have a looki at this [video](https://youtu.be/D5ok7jh7AOg) # Todo The Ethereum protocol is currenty heavily in development, thus so is this implementation. -You can find a todo-list right [here](TODO.md) and the [milestone schedule](https://github.com/ethereum/ethereumj/milestones). +You can find a todo-list right [here](TODO.md) and the [milestone schedule](https://github.com/ethereum/ethereumj/milestones). For questions you can reach us in #ethereumj on Freenode. - + # Documentation To start you can visit [Ethereum.org](https://www.ethereum.org) and if you are looking for more information on the concept, the [ethereum white paper](https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-White-Paper) is a good place to start as it outlines the vision. For the more technical minded, a protocol description can be found in the [yellow paper](http://gavwood.com/Paper.pdf) by Gavin Wood. @@ -34,6 +34,6 @@ https://bintray.com/ethereum/maven/org.ethereum/view For building ethereumj-core or ethereumj-studio look in their own individual README -# License +# License This software is released under the MIT license, read it [here](LICENSE) diff --git a/TODO.md b/TODO.md index cd00bdae..cd5ab5be 100644 --- a/TODO.md +++ b/TODO.md @@ -4,26 +4,26 @@ ---------------- - [ ] **GUI screen** a screen that will hold table with full state representation -- [ ] **SerpentCompiler** compile create(gas, mem_start, import("examples/mul2.se")) +- [ ] **SerpentCompiler** compile create(gas, mem_start, import("examples/mul2.se")) https://github.com/ethereum/wiki/wiki/Serpent - [ ] **SerpentCompiler** compile return(array) correct - [ ] **ProgramPlayDialog** support internal calls -- [ ] **Performance:** BigInteger math change for constant arrays implementation +- [ ] **Performance:** BigInteger math change for constant arrays implementation economy for memory allocation -- [ ] **Command Line:** add the headless run option -- [ ] **SerpentCompiler** Serpent new syntax: -(@> @< @/ @%) - unsigned operations - > < / % - default are all signed operations -+= -= *= /= %= @/= @%= - short form operations +- [ ] **Command Line:** add the headless run option +- [ ] **SerpentCompiler** Serpent new syntax: +(@> @< @/ @%) - unsigned operations + > < / % - default are all signed operations ++= -= *= /= %= @/= @%= - short form operations share - code section - -- [ ] **LLL_to_ASM compiler** list style language to EVM assembly compiler: + +- [ ] **LLL_to_ASM compiler** list style language to EVM assembly compiler: - [ ] **Use home-directory** Create .ethereumj in home-directory for blockchain, state & details database. Make configurable in system.properties so developer can choose user.dir without the creation of .ethereumj directory. -##### UnitTest: +##### UnitTest: ---------------- -- [ ] **VM complex:** CREATE testing +- [ ] **VM complex:** CREATE testing - [ ] **VM complex:** SUICIDE testing - [ ] **SerpentCompiler** compile return(array) correct - [ ] **WorldManager** apply transactions @@ -36,14 +36,14 @@ share - code section - [X] ** Block Queue ** separate net layer and block processing layer, net layer should continue get blocks in time the vm layer process them (not stuck for it) - [X] **Build:** extract core module and studio application -- [x] **VM execution:** support CALL op -- [x] **VM execution:** support CALL op with in/out data +- [x] **VM execution:** support CALL op +- [x] **VM execution:** support CALL op with in/out data - [x] **VM execution:** support CREATE op - [x] **SerpentCompiler** compile create(gas, mem_start, mem_size) - [x] **VM complex:** CALL testing for in arrays - [x] **VM complex:** CALL testing for out result -- [x] **State management** trie for storage hash calculation +- [x] **State management** trie for storage hash calculation and update hash into AccountState - [x] **VM execution:** SUICIDE op adjust - [x] **Testing by JSON files:** follow cpp client performs test case by getting json file contains the test describe diff --git a/ethereumj-core/README.md b/ethereumj-core/README.md index ef0389e5..0619e048 100644 --- a/ethereumj-core/README.md +++ b/ethereumj-core/README.md @@ -1,7 +1,7 @@ The core library API for Ethereum project can be included -into any other Java/Scala project by simple maven -script include: +into any other Java/Scala project by simple maven +script include: ``` @@ -13,20 +13,20 @@ script include: ``` -EthereumJ release repository can be found here: +EthereumJ release repository can be found here: * https://bintray.com/ethereum/maven/org.ethereum/view The showcase for ethereumj-core usage can be found in [ethereumj-studio](../ethereumj-studio) - + ###### :small_blue_diamond: Build instructions (maven) - 1. build_1: [no test run] , [released to local repository] : ~> ` mvn clean install -Dmaven.test.skip=true ` - 2. build_2: [include test run] , [released to local repository] : ~> ` mvn clean install ` - + 1. build_1: [no test run] , [released to local repository] : ~> ` mvn clean install -Dmaven.test.skip=true ` + 2. build_2: [include test run] , [released to local repository] : ~> ` mvn clean install ` + ###### :small_blue_diamond: release instructions (ant) (!) credential required 1. ` mvn install ` - which release the lib to a local repositroy 2. after the release - ` ant -f bintray-publish-version.xml ` - - - + + + diff --git a/ethereumj-core/pom.xml b/ethereumj-core/pom.xml index 24d2875b..f8f558a7 100644 --- a/ethereumj-core/pom.xml +++ b/ethereumj-core/pom.xml @@ -446,5 +446,5 @@ - + 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 e4eb86bc..96552024 100644 --- a/ethereumj-core/src/main/java/org/ethereum/config/SystemProperties.java +++ b/ethereumj-core/src/main/java/org/ethereum/config/SystemProperties.java @@ -13,7 +13,7 @@ import org.springframework.stereotype.Component; /** * Utility class to retrieve property values from the system.properties files * - * @author Roman Mandeleil + * @author Roman Mandeleil * Created on: 22/05/2014 19:22 */ public class SystemProperties { @@ -46,7 +46,7 @@ public class SystemProperties { 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; @@ -281,17 +281,17 @@ public class SystemProperties { logger.info("Key: " + key + ", Value: " + value); } } - + /* - * + * * Testing - * + * */ public boolean vmTestLoadLocal() { if (prop.isEmpty() || !prop.containsKey("GitHubTests.VMTest.loadLocal")) return DEFAULT_VMTEST_LOAD_LOCAL; return Boolean.parseBoolean(prop.getProperty("GitHubTests.VMTest.loadLocal")); } - + public static void main(String args[]) { SystemProperties systemProperties = new SystemProperties(); systemProperties.print(); 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 3b62e9bb..aa822a91 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/AccountState.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/AccountState.java @@ -12,32 +12,32 @@ import static org.ethereum.crypto.HashUtil.EMPTY_TRIE_HASH; public class AccountState { private byte[] rlpEncoded; - + /* A value equal to the number of transactions sent - * from this address, or, in the case of contract accounts, + * from this address, or, in the case of contract accounts, * the number of contract-creations made by this account */ private BigInteger nonce; - + /* A scalar value equal to the number of Wei owned by this address */ private BigInteger balance; - - /* A 256-bit hash of the root node of a trie structure - * that encodes the storage contents of the contract, - * itself a simple mapping between byte arrays of size 32. - * The hash is formally denoted σ[a] s . - * - * Since I typically wish to refer not to the trie’s root hash + + /* A 256-bit hash of the root node of a trie structure + * that encodes the storage contents of the contract, + * itself a simple mapping between byte arrays of size 32. + * The hash is formally denoted σ[a] s . + * + * Since I typically wish to refer not to the trie’s root hash * but to the underlying set of key/value pairs stored within, - * I define a convenient equivalence TRIE (σ[a] s ) ≡ σ[a] s . - * It shall be understood that σ[a] s is not a ‘physical’ member + * I define a convenient equivalence TRIE (σ[a] s ) ≡ σ[a] s . + * It shall be understood that σ[a] s is not a ‘physical’ member * of the account and does not contribute to its later serialisation */ private byte[] stateRoot = EMPTY_TRIE_HASH; - - /* The hash of the EVM code of this contract—this is the code - * that gets executed should this address receive a message call; - * it is immutable and thus, unlike all other fields, cannot be changed - * after construction. All such code fragments are contained in - * the state database under their corresponding hashes for later + + /* The hash of the EVM code of this contract—this is the code + * that gets executed should this address receive a message call; + * it is immutable and thus, unlike all other fields, cannot be changed + * after construction. All such code fragments are contained in + * the state database under their corresponding hashes for later * retrieval */ private byte[] codeHash = EMPTY_DATA_HASH; @@ -53,7 +53,7 @@ public class AccountState { this.nonce = nonce; this.balance = balance; } - + public AccountState(byte[] rlpData) { this.rlpEncoded = rlpData; @@ -115,7 +115,7 @@ public class AccountState { this.balance = balance.subtract(value); setDirty(true); } - + public byte[] getEncoded() { if(rlpEncoded == null) { byte[] nonce = RLP.encodeBigInteger(this.nonce); 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 ef8ee2f3..8805a49b 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Block.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Block.java @@ -16,10 +16,10 @@ import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** - * The block in Ethereum is the collection of relevant pieces of information + * The block in Ethereum is the collection of relevant pieces of information * (known as the blockheader), H, together with information corresponding to - * the comprised transactions, R, and a set of other blockheaders U that are known - * to have a parent equal to the present block’s parent’s parent + * the comprised transactions, R, and a set of other blockheaders U that are known + * to have a parent equal to the present block’s parent’s parent * (such blocks are known as uncles). * * www.ethereumJ.com @@ -30,7 +30,7 @@ import java.util.concurrent.CopyOnWriteArrayList; public class Block { private static final Logger logger = LoggerFactory.getLogger("block"); - + public static BigInteger BLOCK_REWARD = BigInteger.valueOf(1500000000000000000L); public static BigInteger UNCLE_REWARD = BLOCK_REWARD.multiply( BigInteger.valueOf(15)).divide(BigInteger.valueOf(16)); @@ -38,28 +38,28 @@ public class Block { .divide(BigInteger.valueOf(32)); private BlockHeader header; - + /* Transactions */ private List transactionsList = new CopyOnWriteArrayList<>(); - + /* Uncles */ private List uncleList = new CopyOnWriteArrayList<>(); - /* Private */ - + /* Private */ + private byte[] rlpEncoded; private boolean parsed = false; - + private Trie txsState; - + /* Constructors */ - + public Block(byte[] rawData) { logger.debug("new from [" + Hex.toHexString(rawData) + "]"); this.rlpEncoded = rawData; this.parsed = false; } - + public Block(byte[] parentHash, byte[] unclesHash, byte[] coinbase, byte[] logsBloom, byte[] difficulty, long number, long gasLimit, long gasUsed, long timestamp, byte[] extraData, byte[] nonce, @@ -85,11 +85,11 @@ public class Block { RLPList params = RLP.decode2(rlpEncoded); RLPList block = (RLPList) params.get(0); - + // Parse Header RLPList header = (RLPList) block.get(0); this.header = new BlockHeader(header); - + // Parse Transactions RLPList txTransactions = (RLPList) block.get(1); this.parseTxs(this.header.getTxTrieRoot(), txTransactions); @@ -131,7 +131,7 @@ public class Block { return FastByteComparisons.compareTo(result, 0, 32, target, 0, 32) < 0; } - + public byte[] getParentHash() { if (!parsed) parseRLP(); return this.header.getParentHash(); @@ -151,7 +151,7 @@ public class Block { if (!parsed) parseRLP(); return this.header.getStateRoot(); } - + public void setStateRoot(byte[] stateRoot) { if (!parsed) parseRLP(); this.header.setStateRoot(stateRoot); @@ -180,12 +180,12 @@ public class Block { } return calcDifficulty; } - + public long getTimestamp() { if (!parsed) parseRLP(); return this.header.getTimestamp(); } - + public long getNumber() { if (!parsed) parseRLP(); return this.header.getNumber(); @@ -210,7 +210,7 @@ public class Block { if (!parsed) parseRLP(); return this.header.getNonce(); } - + public void setNonce(byte[] nonce) { this.header.setNonce(nonce); rlpEncoded = null; @@ -228,7 +228,7 @@ public class Block { private StringBuffer toStringBuff = new StringBuffer(); // [parent_hash, uncles_hash, coinbase, state_root, tx_trie_root, - // difficulty, number, minGasPrice, gasLimit, gasUsed, timestamp, + // difficulty, number, minGasPrice, gasLimit, gasUsed, timestamp, // extradata, nonce] @Override @@ -260,7 +260,7 @@ public class Block { toStringBuff.append("BlockData ["); toStringBuff.append("hash=" + ByteUtil.toHexString(this.getHash())).append(""); toStringBuff.append(header.toFlatString()); - + for (Transaction tx : getTransactionsList()) { toStringBuff.append("\n"); toStringBuff.append(tx.toString()); @@ -318,7 +318,7 @@ public class Block { this.getHeader().setUnclesHash( SHA3Helper.sha3( getUnclesEncoded() )); rlpEncoded = null; } - + public byte[] getEncoded() { if(rlpEncoded == null) { byte[] header = this.header.getEncoded(); @@ -328,7 +328,7 @@ public class Block { } return rlpEncoded; } - + public byte[] getEncodedWithoutNonce() { if (!parsed) parseRLP(); byte[] header = this.header.getEncodedWithoutNonce(); 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 45d9433c..bed731e0 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/BlockHeader.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/BlockHeader.java @@ -11,23 +11,23 @@ import static org.ethereum.crypto.HashUtil.EMPTY_TRIE_HASH; import static org.ethereum.util.ByteUtil.toHexString; /** - * Block header is a value object containing - * the basic information of a block + * Block header is a value object containing + * the basic information of a block */ public class BlockHeader { - + /* The SHA3 256-bit hash of the parent block, in its entirety */ 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 + /* The 160-bit address to which all fees collected from the * successful mining of this block be transferred; formally */ private byte[] coinbase; - /* The SHA3 256-bit hash of the root node of the state trie, + /* The SHA3 256-bit hash of the root node of the state trie, * after all transactions are executed and finalisations applied */ private byte[] stateRoot; - /* The SHA3 256-bit hash of the root node of the trie structure + /* The SHA3 256-bit hash of the root node of the trie structure * populated with each transaction in the transaction * list portion, the trie is populate by [key, val] --> [rlp(index), rlp(tx_reciepe)] * of the block */ @@ -41,33 +41,33 @@ public class BlockHeader { /*todo: comment it when you know what the fuck it is*/ private byte[] logsBloom; /* A scalar value corresponding to the difficulty level of this block. - * This can be calculated from the previous block’s difficulty level + * This can be calculated from the previous block’s difficulty level * and the timestamp */ private byte[] difficulty; - /* A scalar value equal to the reasonable output of Unix's time() + /* A scalar value equal to the reasonable output of Unix's time() * at this block's inception */ - private long timestamp; - /* A scalar value equal to the number of ancestor blocks. + private long timestamp; + /* A scalar value equal to the number of ancestor blocks. * The genesis block has a number of zero */ private long number; /* A scalar value equal to the current limit of gas expenditure per block */ private long gasLimit; /* A scalar value equal to the total gas used in transactions in this block */ private long gasUsed; - /* An arbitrary byte array containing data relevant to this block. + /* An arbitrary byte array containing data relevant to this block. * With the exception of the genesis block, this must be 32 bytes or fewer */ private byte[] extraData; - /* A 256-bit hash which proves that a sufficient amount + /* A 256-bit hash which proves that a sufficient amount * of computation has been carried out on this block */ private byte[] nonce; - + 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.txTrieRoot = rlpHeader.get(4).getRLPData(); if(this.txTrieRoot == null) this.txTrieRoot = EMPTY_TRIE_HASH; @@ -78,23 +78,23 @@ public class BlockHeader { 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(); - + 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.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, long gasLimit, long gasUsed, long timestamp, @@ -112,10 +112,10 @@ public class BlockHeader { this.nonce = nonce; this.stateRoot = HashUtil.EMPTY_TRIE_HASH; } - + /** - * Calculate Difficulty + * Calculate Difficulty * See Yellow Paper: http://www.gavwood.com/Paper.pdf - page 5, 4.3.4 (24) * @return byte array value of the difficulty */ @@ -217,15 +217,15 @@ public class BlockHeader { public void setNonce(byte[] nonce) { this.nonce = nonce; } - + public byte[] getEncoded() { return this.getEncoded(true); // with nonce } - + public byte[] getEncodedWithoutNonce() { return this.getEncoded(false); } - + public byte[] getEncoded(boolean withNonce) { byte[] parentHash = RLP.encodeElement(this.parentHash); @@ -262,7 +262,7 @@ public class BlockHeader { private StringBuffer toStringBuff = new StringBuffer(); - + public String toString() { toStringBuff.setLength(0); @@ -281,7 +281,7 @@ public class BlockHeader { toStringBuff.append(" nonce=" + toHexString(nonce)).append("\n"); return toStringBuff.toString(); } - + public String toFlatString() { toStringBuff.append(" parentHash=" + toHexString(parentHash)).append(""); toStringBuff.append(" unclesHash=" + toHexString(unclesHash)).append(""); 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 756ccb33..b7aa6149 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/BlockchainImpl.java @@ -29,14 +29,14 @@ import static org.ethereum.config.SystemProperties.CONFIG; import static org.ethereum.core.Denomination.SZABO; /** - * The Ethereum blockchain is in many ways similar to the Bitcoin blockchain, - * although it does have some differences. - * - * The main difference between Ethereum and Bitcoin with regard to the blockchain architecture - * is that, unlike Bitcoin, Ethereum blocks contain a copy of both the transaction list - * and the most recent state. Aside from that, two other values, the block number and - * the difficulty, are also stored in the block. - * + * The Ethereum blockchain is in many ways similar to the Bitcoin blockchain, + * although it does have some differences. + * + * The main difference between Ethereum and Bitcoin with regard to the blockchain architecture + * is that, unlike Bitcoin, Ethereum blocks contain a copy of both the transaction list + * and the most recent state. Aside from that, two other values, the block number and + * the difficulty, are also stored in the block. + * * The block validation algorithm in Ethereum is as follows: *
    *
  1. Check if the previous block referenced exists and is valid.
  2. @@ -44,9 +44,9 @@ import static org.ethereum.core.Denomination.SZABO; *
  3. Check that the block number, difficulty, transaction root, uncle root and gas limit (various low-level Ethereum-specific concepts) are valid.
  4. *
  5. Check that the proof of work on the block is valid.
  6. *
  7. Let S[0] be the STATE_ROOT of the previous block.
  8. - *
  9. 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]). - * If any applications returns an error, or if the total gas consumed in the block + *
  10. 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]). + * 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.
  11. *
  12. Let S_FINAL be S[n], but adding the block reward paid to the miner.
  13. *
  14. Check if S_FINAL is the same as the STATE_ROOT. If it is, the block is valid; otherwise, it is not valid.
  15. @@ -66,7 +66,7 @@ public class BlockchainImpl implements Blockchain { private static final Logger logger = LoggerFactory.getLogger("blockchain"); private static final Logger stateLogger = LoggerFactory.getLogger("state"); - + // to avoid using minGasPrice=0 from Genesis for the wallet private static final long INITIAL_MIN_GAS_PRICE = 10 * SZABO.longValue(); @@ -107,7 +107,7 @@ public class BlockchainImpl implements Blockchain { public byte[] getBestBlockHash() { return getBestBlock().getHash(); } - + @Override public long getSize() { return bestBlock.getNumber() + 1; @@ -313,7 +313,7 @@ public class BlockchainImpl implements Blockchain { logger.warn("Invalid block with nr: {}", block.getNumber()); } } - + private List applyBlock(Block block) { int i = 1; @@ -363,15 +363,15 @@ public class BlockchainImpl implements Blockchain { /** * Add reward to block- and every uncle coinbase * assuming the entire block is valid. - * + * * @param block object containing the header and uncles */ private void addReward(Block block) { // Add standard block reward BigInteger totalBlockReward = Block.BLOCK_REWARD; - - // Add extra rewards based on number of uncles + + // Add extra rewards based on number of uncles if(block.getUncleList().size() > 0) { for (BlockHeader uncle : block.getUncleList()) { track.addBalance(uncle.getCoinbase(), Block.UNCLE_REWARD); @@ -381,7 +381,7 @@ public class BlockchainImpl implements Blockchain { } track.addBalance(block.getCoinbase(), totalBlockReward); } - + @Override public void storeBlock(Block block, List receipts) { @@ -408,8 +408,8 @@ public class BlockchainImpl implements Blockchain { logger.debug("block added to the blockChain: index: [{}]", block.getNumber()); if (block.getNumber() % 100 == 0) logger.info("*** Last block added [ #{} ]", block.getNumber()); - } - + } + public boolean hasParentOnTheChain(Block block){ return getParent(block.getHeader()) != null; diff --git a/ethereumj-core/src/main/java/org/ethereum/core/Denomination.java b/ethereumj-core/src/main/java/org/ethereum/core/Denomination.java index 988eadc7..184b55ee 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Denomination.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Denomination.java @@ -12,10 +12,10 @@ public enum Denomination { FINNY(newBigInt(15)), ETHER(newBigInt(18)), EINSTEIN(newBigInt(21)), - DOUGLAS(newBigInt(42)); - + DOUGLAS(newBigInt(42)); + private BigInteger amount; - + private Denomination(BigInteger value) { this.amount = value; } @@ -23,7 +23,7 @@ public enum Denomination { public BigInteger value() { return amount; } - + public long longValue() { return value().longValue(); } @@ -31,7 +31,7 @@ public enum Denomination { private static BigInteger newBigInt(int value) { return BigInteger.valueOf(10).pow(value); } - + public static String toFriendlyString(BigInteger value) { if(value.compareTo(DOUGLAS.value()) == 1 || value.compareTo(DOUGLAS.value()) == 0) { return Float.toString(value.divide(DOUGLAS.value()).floatValue()) + " DOUGLAS"; 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 9b81c956..df505e41 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Genesis.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Genesis.java @@ -10,26 +10,26 @@ import org.ethereum.trie.TrieImpl; import org.spongycastle.util.encoders.Hex; /** - * The genesis block is the first block in the chain and has fixed values according to + * The genesis block is the first block in the chain and has fixed values according to * the protocol specification. The genesis block is 13 items, and is specified thus: - * + * * ( zerohash_256 , SHA3 RLP () , zerohash_160 , stateRoot, 0, 2^22 , 0, 0, 1000000, 0, 0, 0, SHA3 (42) , (), () ) - * - * - Where zerohash_256 refers to the parent hash, a 256-bit hash which is all zeroes; - * - zerohash_160 refers to the coinbase address, a 160-bit hash which is all zeroes; - * - 2^22 refers to the difficulty; - * - 0 refers to the timestamp (the Unix epoch); - * - the transaction trie root and extradata are both 0, being equivalent to the empty byte array. - * - The sequences of both uncles and transactions are empty and represented by (). - * - SHA3 (42) refers to the SHA3 hash of a byte array of length one whose first and only byte is of value 42. + * + * - Where zerohash_256 refers to the parent hash, a 256-bit hash which is all zeroes; + * - zerohash_160 refers to the coinbase address, a 160-bit hash which is all zeroes; + * - 2^22 refers to the difficulty; + * - 0 refers to the timestamp (the Unix epoch); + * - the transaction trie root and extradata are both 0, being equivalent to the empty byte array. + * - The sequences of both uncles and transactions are empty and represented by (). + * - SHA3 (42) refers to the SHA3 hash of a byte array of length one whose first and only byte is of value 42. * - SHA3 RLP () value refers to the hash of the uncle lists in RLP, both empty lists. - * + * * See Yellow Paper: http://www.gavwood.com/Paper.pdf (Appendix I. Genesis Block) */ public class Genesis extends Block { public final static BigInteger PREMINE_AMOUNT = BigInteger.valueOf(2).pow(200); - + private static String[] premine = new String[] { "51ba59315b3a95761d0863b05ccc7a7f54703d99", "e6716f9544a56c530d868e4bfbacb172315bdead", // # (J) @@ -56,14 +56,14 @@ public class Genesis extends Block { public static long TIMESTAMP = 0; public static byte[] EXTRA_DATA = new byte[0]; public static byte[] NONCE = sha3(new byte[]{42}); - + private static Block instance; - + private Genesis() { super(PARENT_HASH, UNCLES_HASH, COINBASE, LOG_BLOOM, DIFFICULTY, NUMBER, GAS_LIMIT, GAS_USED, TIMESTAMP, EXTRA_DATA, NONCE, null, null); - + Trie state = new TrieImpl(null); // The proof-of-concept series include a development pre-mine, making the state root hash // some value stateRoot. The latest documentation should be consulted for the value of the state root. @@ -74,14 +74,14 @@ public class Genesis extends Block { setStateRoot(state.getRootHash()); } - + public static Block getInstance() { if (instance == null) { instance = new Genesis(); } return instance; } - + public final static String[] getPremine() { return premine; } 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 61d428e0..d57cbc32 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Transaction.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Transaction.java @@ -16,17 +16,17 @@ import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; import static org.ethereum.util.ByteUtil.ZERO_BYTE_ARRAY; /** - * A transaction (formally, T) is a single cryptographically - * signed instruction sent by an actor external to Ethereum. - * An external actor can be a person (via a mobile device or desktop computer) - * or could be from a piece of automated software running on a server. - * There are two types of transactions: those which result in message calls + * A transaction (formally, T) is a single cryptographically + * signed instruction sent by an actor external to Ethereum. + * An external actor can be a person (via a mobile device or desktop computer) + * or could be from a piece of automated software running on a server. + * There are two types of transactions: those which result in message calls * and those which result in the creation of new contracts. */ public class Transaction { private static final Logger logger = LoggerFactory.getLogger(Transaction.class); - + /* SHA3 hash of the RLP encoded transaction */ private byte[] hash; @@ -64,7 +64,7 @@ public class Transaction { /* Tx in encoded form */ private byte[] rlpEncoded; private byte[] rlpRaw; - /* Indicates if this transaction has been parsed + /* Indicates if this transaction has been parsed * from the RLP-encoded data */ private boolean parsed = false; @@ -295,7 +295,7 @@ public class Transaction { byte[] data = RLP.encodeElement(this.data); byte[] v, r, s; - + if(signature != null) { v = RLP.encodeByte( signature.v ); r = RLP.encodeElement(BigIntegers.asUnsignedByteArray(signature.r)); 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 7ae3648a..a88f58f2 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/TransactionReceipt.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/TransactionReceipt.java @@ -13,9 +13,9 @@ import java.util.List; import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; /** - * The transaction receipt is a tuple of three items - * comprising the transaction, together with the post-transaction state, - * and the cumulative gas used in the block containing the transaction receipt + * The transaction receipt is a tuple of three items + * 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, * * 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 b1d09eee..8381a8e8 100644 --- a/ethereumj-core/src/main/java/org/ethereum/core/Wallet.java +++ b/ethereumj-core/src/main/java/org/ethereum/core/Wallet.java @@ -40,7 +40,7 @@ public class Wallet { // TODO: a) the values I need to keep for address state is balance & nonce & ECKey // TODO: b) keep it to be easy accessed by the toAddress() // private HashMap rows = new HashMap<>(); - + // This map of transaction designed // to approve the tx by external trusted peer private Map walletTransactions = new ConcurrentHashMap<>(); @@ -141,13 +141,13 @@ public class Wallet { return walletTransaction; } - + public void addTransactions(List transactions) { for (Transaction transaction : transactions) { this.addTransaction(transaction); } } - + public void removeTransactions(List transactions) { for (Transaction tx : transactions) { if (logger.isDebugEnabled()) @@ -182,7 +182,7 @@ public class Wallet { Account receiver = rows.get(Hex.toHexString(receiveAddress)); if (receiver != null) { receiver.addPendingTransaction(transaction); - + logger.info("Pending transaction added to " + "\n account: [{}], " + "\n tx: [{}]", @@ -221,7 +221,7 @@ public class Wallet { 900099909 - + */ String dir = System.getProperty("user.dir"); 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 c5707baf..43937be9 100644 --- a/ethereumj-core/src/main/java/org/ethereum/crypto/ECKey.java +++ b/ethereumj-core/src/main/java/org/ethereum/crypto/ECKey.java @@ -50,7 +50,7 @@ import org.spongycastle.util.encoders.Hex; * Creating a new ECKey with the empty constructor will generate a new random keypair. Other static methods can be used * when you already have the public or private parts. If you create a key with only the public part, you can check * signatures but not create them.

    - * + * *

    The ECDSA algorithm supports key recovery in which a signature plus a couple of discriminator bits can * be reversed to find the public key used to calculate it. This can be convenient when you have a message and a * signature and want to find out who signed it, rather than requiring the user to provide the expected identity.

    @@ -70,7 +70,7 @@ import org.spongycastle.util.encoders.Hex; */ public class ECKey implements Serializable { private static final Logger logger = LoggerFactory.getLogger(ECKey.class); - + /** The parameters of the secp256k1 curve that Ethereum uses. */ public static final ECDomainParameters CURVE; @@ -90,7 +90,7 @@ public class ECKey implements Serializable { HALF_CURVE_ORDER = params.getN().shiftRight(1); secureRandom = new SecureRandom(); } - + // The two parts of the key. If "priv" is set, "pub" can always be calculated. If "pub" is set but not "priv", we // can only verify signatures not make them. // TODO: Redesign this class to use consistent internals and more efficient serialization. @@ -129,7 +129,7 @@ public class ECKey implements Serializable { throw new IllegalArgumentException("Public key may not be null"); this.pub = pub; } - + /** * Utility for compressing an elliptic curve point. Returns the same point if it's already compressed. * See the ECKey class docs for a discussion of point compression. @@ -145,7 +145,7 @@ public class ECKey implements Serializable { public static ECPoint decompressPoint(ECPoint compressed) { return CURVE.getCurve().decodePoint(compressed.getEncoded(false)); } - + /** * Creates an ECKey given the private key only. The public key is calculated from it (this is slow). Note that * the resulting public key is compressed. @@ -197,7 +197,7 @@ public class ECKey implements Serializable { public static ECKey fromPublicOnly(byte[] pub) { return new ECKey(null, CURVE.getCurve().decodePoint(pub)); } - + /** * Returns a copy of this key, but with the public point represented in uncompressed form. Normally you would * never need this: it's for specialised scenarios or when backwards compatibility in encoded form is necessary. @@ -224,7 +224,7 @@ public class ECKey implements Serializable { public boolean hasPrivKey() { return priv != null; } - + /** * Returns public key bytes from the given private key. To convert a byte array into a BigInteger, use * new BigInteger(1, bytes); @@ -293,7 +293,7 @@ public class ECKey implements Serializable { } return b.toString(); } - + /** * Groups the two components that make up a signature, and provides a way to encode to Base64 form, which is * how ECDSA signatures are represented when embedded in other data structures in the Ethereum protocol. The raw @@ -311,11 +311,11 @@ public class ECKey implements Serializable { this.r = r; this.s = s; } - + private static ECDSASignature fromComponents(byte[] r, byte[] s) { return new ECDSASignature(new BigInteger(1, r), new BigInteger(1, s)); } - + public static ECDSASignature fromComponents(byte[] r, byte[] s, byte v) { ECDSASignature signature = fromComponents(r, s); signature.v = v; @@ -341,7 +341,7 @@ public class ECKey implements Serializable { return this; } } - + public String toBase64() { byte[] sigData = new byte[65]; // 1 header + 32 bytes for R + 32 bytes for S sigData[0] = v; @@ -349,7 +349,7 @@ public class ECKey implements Serializable { System.arraycopy(bigIntegerToBytes(this.s, 32), 0, sigData, 33, 32); return new String(Base64.encode(sigData), Charset.forName("UTF-8")); } - + @Override public boolean equals(Object o) { if (this == o) return true; @@ -370,11 +370,11 @@ public class ECKey implements Serializable { return result; } } - + /** - * Signs the given hash and returns the R and S components as BigIntegers - * and put them in ECDSASignature - * + * Signs the given hash and returns the R and S components as BigIntegers + * and put them in ECDSASignature + * * @param input to sign * @return ECDSASignature signature that contains the R and S components */ @@ -389,7 +389,7 @@ public class ECKey implements Serializable { BigInteger[] components = signer.generateSignature(input); return new ECDSASignature(components[0], components[1]).toCanonicalised(); } - + /** * Takes the sha3 hash (32 bytes) of data and returns the ECDSA signature * @@ -413,12 +413,12 @@ public class ECKey implements Serializable { sig.v = (byte) (recId + 27 + (isCompressed() ? 4 : 0)); return sig; } - + /** * Given a piece of text and a message signature encoded in base64, returns an ECKey * containing the public key that was used to sign it. This can then be compared to the expected public key to * determine if the signature was correct. - * + * * @param messageHash a piece of human readable text that was signed * @param signatureBase64 The Ethereum-format message signature in base64 * @throws SignatureException If the public key could not be recovered or if there was a signature format error. @@ -453,10 +453,10 @@ public class ECKey implements Serializable { throw new SignatureException("Could not recover public key from signature"); return key; } - + /** *

    Verifies the given ECDSA signature against the message bytes using the public key bytes.

    - * + * *

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

    * @@ -471,7 +471,7 @@ public class ECKey implements Serializable { try { return signer.verifySignature(data, signature.r, signature.s); } catch (NullPointerException npe) { - // Bouncy Castle contains a bug that can cause NPEs given specially crafted signatures. + // Bouncy Castle contains a bug that can cause NPEs given specially crafted signatures. // Those signatures are inherently invalid/attack sigs so we just fail them here rather than crash the thread. logger.error("Caught NPE inside bouncy castle", npe); return false; @@ -637,7 +637,7 @@ public class ECKey implements Serializable { byte[] bits = getPubKey(); return (bits[0] & 0xFF) | ((bits[1] & 0xFF) << 8) | ((bits[2] & 0xFF) << 16) | ((bits[3] & 0xFF) << 24); } - + @SuppressWarnings("serial") public static class MissingPrivateKeyException extends RuntimeException { } 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 5fa34da6..f0e6657c 100644 --- a/ethereumj-core/src/main/java/org/ethereum/crypto/HashUtil.java +++ b/ethereumj-core/src/main/java/org/ethereum/crypto/HashUtil.java @@ -18,14 +18,14 @@ import org.ethereum.util.LRUMap; public class HashUtil { - private static final int MAX_ENTRIES = 100; // Should contain most commonly hashed values + private static final int MAX_ENTRIES = 100; // Should contain most commonly hashed values private static LRUMap sha3Cache = new LRUMap<>(0, MAX_ENTRIES); public static final byte[] EMPTY_DATA_HASH = sha3(EMPTY_BYTE_ARRAY); public static final byte[] EMPTY_LIST_HASH = sha3(RLP.encodeList()); public static final byte[] EMPTY_TRIE_HASH = sha3(RLP.encodeElement(EMPTY_BYTE_ARRAY)); private static final MessageDigest sha256digest; - + static { try { sha256digest = MessageDigest.getInstance("SHA-256"); @@ -33,7 +33,7 @@ public class HashUtil { throw new RuntimeException(e); // Can't happen. } } - + public static byte[] sha256(byte[] input) { return sha256digest.digest(input); } @@ -47,7 +47,7 @@ public class HashUtil { sha3Cache.put(inputByteArray, result); return result; } - + public static byte[] ripemd160(byte[] message) { Digest digest = new RIPEMD160Digest(); if (message != null) { @@ -83,7 +83,7 @@ public class HashUtil { return newAddress; } - + /** * @see #doubleDigest(byte[], int, int) */ diff --git a/ethereumj-core/src/main/java/org/ethereum/crypto/SHA3Helper.java b/ethereumj-core/src/main/java/org/ethereum/crypto/SHA3Helper.java index 5f63cdaa..c7992e3a 100644 --- a/ethereumj-core/src/main/java/org/ethereum/crypto/SHA3Helper.java +++ b/ethereumj-core/src/main/java/org/ethereum/crypto/SHA3Helper.java @@ -6,9 +6,9 @@ import org.spongycastle.crypto.digests.SHA3Digest; import org.spongycastle.util.encoders.Hex; public class SHA3Helper { - + private static int DEFAULT_SIZE = 256; - + public static String sha3String(String message) { return sha3String(message, new SHA3Digest(DEFAULT_SIZE), true); } @@ -75,23 +75,23 @@ public class SHA3Helper { digest.doFinal(hash, 0); return hash; } - + public enum Size { - + S224(224), S256(256), S384(384), S512(512); - + int bits = 0; - + Size(int bits) { this.bits = bits; } - + public int getValue() { return this.bits; } } - + } diff --git a/ethereumj-core/src/main/java/org/ethereum/db/ByteArrayWrapper.java b/ethereumj-core/src/main/java/org/ethereum/db/ByteArrayWrapper.java index f7ca4930..f9d38b5b 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/ByteArrayWrapper.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/ByteArrayWrapper.java @@ -24,7 +24,7 @@ public class ByteArrayWrapper implements Comparable { return false; byte[] otherData = ((ByteArrayWrapper) other).getData(); return FastByteComparisons.compareTo( - data, 0, data.length, + data, 0, data.length, otherData, 0, otherData.length) == 0; } @@ -36,10 +36,10 @@ public class ByteArrayWrapper implements Comparable { @Override public int compareTo(ByteArrayWrapper o) { return FastByteComparisons.compareTo( - data, 0, data.length, + data, 0, data.length, o.getData(), 0, o.getData().length); } - + public byte[] getData() { return data; } 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 882345f0..f0194438 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/ContractDetails.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/ContractDetails.java @@ -32,7 +32,7 @@ public class ContractDetails { public ContractDetails() { } - + public ContractDetails(byte[] rlpCode) { decode(rlpCode); } diff --git a/ethereumj-core/src/main/java/org/ethereum/db/Database.java b/ethereumj-core/src/main/java/org/ethereum/db/Database.java index dde409ca..5d6a7fbc 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/Database.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/Database.java @@ -4,26 +4,26 @@ package org.ethereum.db; * Ethereum generic database interface */ public interface Database { - - /** + + /** * Get value from database - * + * * @param key for which to retrieve the value * @return the value for the given key */ public byte[] get(byte[] key); - + /** * Insert value into database - * + * * @param key for the given value * @param value to insert */ - public void put(byte[] key, byte[] value); - + public void put(byte[] key, byte[] value); + /** * Delete key/value pair from database - * + * * @param key for which to delete the value */ public void delete(byte[] key); 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 7320ad47..74663e45 100644 --- a/ethereumj-core/src/main/java/org/ethereum/db/DatabaseImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/db/DatabaseImpl.java @@ -19,18 +19,18 @@ import org.spongycastle.util.encoders.Hex; /** * 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 */ public class DatabaseImpl implements Database { - + private static final Logger logger = LoggerFactory.getLogger("db"); private DB db; private String name; - + public DatabaseImpl(String name) { // Initialize Database this.name = name; @@ -69,9 +69,9 @@ public class DatabaseImpl implements Database { } catch (IOException ioe) { logger.error(ioe.getMessage(), ioe); throw new RuntimeException("Can't initialize database"); - } + } } - + public void destroyDB(File fileLocation) { logger.debug("Destroying existing database"); Options options = new Options(); @@ -81,12 +81,12 @@ public class DatabaseImpl implements Database { logger.error(e.getMessage(), e); } } - + @Override public byte[] get(byte[] key) { return db.get(key); } - + @Override public void put(byte[] key, byte[] value) { @@ -96,7 +96,7 @@ public class DatabaseImpl implements Database { Hex.toHexString(value)); db.put(key, value); } - + @Override public void delete(byte[] key) { if(logger.isDebugEnabled()) @@ -104,11 +104,11 @@ public class DatabaseImpl implements Database { db.delete(key); } - + public DBIterator iterator() { return db.iterator(); } - + public DB getDb() { return this.db; } 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 bc5d2392..1ecfce92 100644 --- a/ethereumj-core/src/main/java/org/ethereum/facade/Repository.java +++ b/ethereumj-core/src/main/java/org/ethereum/facade/Repository.java @@ -21,7 +21,7 @@ public interface Repository { /** * Create a new account in the database - * + * * @param addr of the contract * @return newly created account state */ @@ -34,65 +34,65 @@ public interface Repository { * false otherwise */ public boolean isExist(byte[] addr); - + /** * Retrieve an account - * + * * @param addr of the account * @return account state as stored in the database */ public AccountState getAccountState(byte[] addr); - + /** * Deletes the account - * + * * @param addr of the account */ public void delete(byte[] addr); - + /** * Increase the account nonce of the given account by one - * + * * @param addr of the account * @return new value of the nonce */ public BigInteger increaseNonce(byte[] addr); - + /** * Get current nonce of a given account - * + * * @param addr of the account * @return value of the nonce */ public BigInteger getNonce(byte[] addr); - + /** * Retrieve contract details for a given account from the database - * + * * @param addr of the account - * @return new contract details + * @return new contract details */ public ContractDetails getContractDetails(byte[] addr); - + /** * Store code associated with an account - * + * * @param addr for the account * @param code that will be associated with this account */ public void saveCode(byte[] addr, byte[] code); - + /** * Retrieve the code associated with an account - * + * * @param addr of the account * @return code in byte-array format */ public byte[] getCode(byte[] addr); - + /** * Put a value in storage of an account at a given key - * + * * @param addr of the account * @param key of the data to store * @param value is the data to store @@ -102,34 +102,34 @@ public interface Repository { /** * Retrieve storage value from an account for a given key - * + * * @param addr of the account * @param key associated with this value * @return data in the form of a DataWord */ public DataWord getStorageValue(byte[] addr, DataWord key); - + /** * Retrieve balance of an account - * + * * @param addr of the account * @return balance of the account as a BigInteger value */ public BigInteger getBalance(byte[] addr); - + /** * Add value to the balance of an account - * + * * @param addr of the account * @param value to be added * @return new balance of the account */ public BigInteger addBalance(byte[] addr, BigInteger value); - + /** * Returns an iterator over the accounts in this database in proper sequence - * + * * @return an iterator over the accounts in this database in proper sequence */ public DBIterator getAccountsIterator(); @@ -137,12 +137,12 @@ public interface Repository { /** * Dump the full state of the current repository into a file with JSON format - * It contains all the contracts/account, their attributes and - * + * It contains all the contracts/account, their attributes and + * * @param block of the current state * @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. + * @param txHash is the hash of the given transaction. * If null, the block state post coinbase reward is dumped. */ public void dumpState(Block block, long gasUsed, int txNumber, byte[] txHash); @@ -158,13 +158,13 @@ public interface Repository { /** - * Store all the temporary changes made + * Store all the temporary changes made * to the repository in the actual database */ public void commit(); - + /** - * Undo all the changes made so far + * Undo all the changes made so far * to a snapshot of the repository */ public void rollback(); @@ -175,13 +175,13 @@ public interface Repository { * @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(); - + /** * Close the database */ 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 f3f553cd..fe778700 100644 --- a/ethereumj-core/src/main/java/org/ethereum/json/EtherObjectMapper.java +++ b/ethereumj-core/src/main/java/org/ethereum/json/EtherObjectMapper.java @@ -11,9 +11,9 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; /** - * An extended {@link com.fasterxml.jackson.databind.ObjectMapper ObjectMapper} class to + * An extended {@link com.fasterxml.jackson.databind.ObjectMapper ObjectMapper} class to * customize ethereum state dumps. - * + * * @author Alon Muroch * */ @@ -21,7 +21,7 @@ public class EtherObjectMapper extends ObjectMapper { @Override public String writeValueAsString(Object value) - throws JsonProcessingException { + throws JsonProcessingException { // alas, we have to pull the recycler directly here... SegmentedStringWriter sw = new SegmentedStringWriter(_jsonFactory._getBufferRecycler()); try { @@ -29,7 +29,7 @@ public class EtherObjectMapper extends ObjectMapper { // set ethereum custom pretty printer EtherPrettyPrinter pp = new EtherPrettyPrinter(); ge.setPrettyPrinter(pp); - + _configAndWriteValue(ge, value); } catch (JsonProcessingException e) { // to support [JACKSON-758] throw e; @@ -38,11 +38,11 @@ public class EtherObjectMapper extends ObjectMapper { } return sw.getAndClear(); } - + /** - * An extended {@link com.fasterxml.jackson.core.util.DefaultPrettyPrinter} class to customize + * 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 * */ @@ -51,7 +51,7 @@ public class EtherObjectMapper extends ObjectMapper { public EtherPrettyPrinter() { super(); } - + @Override public void writeObjectFieldValueSeparator(JsonGenerator jg) throws IOException, JsonGenerationException { 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 cb2b4d6c..2973033c 100644 --- a/ethereumj-core/src/main/java/org/ethereum/json/JSONHelper.java +++ b/ethereumj-core/src/main/java/org/ethereum/json/JSONHelper.java @@ -16,26 +16,26 @@ import java.math.BigInteger; import java.util.*; /** - * JSON Helper class to format data into ObjectNodes + * JSON Helper class to format data into ObjectNodes * to match PyEthereum blockstate output - * + * * Dump format: * { - * "address": - * { - * "nonce": "n1", - * "balance": "b1", - * "stateRoot": "s1", - * "codeHash": "c1", - * "code": "c2", - * "storage": - * { - * "key1": "value1", - * "key2": "value2" + * "address": + * { + * "nonce": "n1", + * "balance": "b1", + * "stateRoot": "s1", + * "codeHash": "c1", + * "code": "c2", + * "storage": + * { + * "key1": "value1", + * "key2": "value2" * } * } * } - * + * * www.ethereumJ.com * * @author: Roman Mandeleil @@ -43,14 +43,14 @@ import java.util.*; */ public class JSONHelper { - public static void dumpState(ObjectNode statesNode, String address, AccountState state, ContractDetails details) { + public static void dumpState(ObjectNode statesNode, String address, AccountState state, ContractDetails details) { List storageKeys = new ArrayList<>(details.getStorage().keySet()); Collections.sort((List) storageKeys); ObjectNode account = statesNode.objectNode(); ObjectNode storage = statesNode.objectNode(); - + for (DataWord key : storageKeys) { storage.put("0x" + Hex.toHexString(key.getData()), "0x" + Hex.toHexString(details.getStorage().get(key).getNoLeadZeroesData())); @@ -61,14 +61,14 @@ public class JSONHelper { account.put("nonce", state.getNonce() == null ? "0" : state.getNonce().toString()); account.put("storage", storage); account.put("storage_root", state.getStateRoot() == null ? "" : Hex.toHexString(state.getStateRoot())); - + statesNode.put(address, account); } - + public static void dumpBlock(ObjectNode blockNode, Block block, long gasUsed, byte[] state, List keys, Repository repository) { - + blockNode.put("coinbase", Hex.toHexString(block.getCoinbase())); blockNode.put("difficulty", new BigInteger(1, block.calcDifficulty()).toString()); blockNode.put("extra_data", "0x"); @@ -76,25 +76,25 @@ public class JSONHelper { blockNode.put("nonce", "0x" + Hex.toHexString(block.getNonce())); blockNode.put("number", String.valueOf(block.getNumber())); blockNode.put("prevhash", "0x" + Hex.toHexString(block.getParentHash())); - + ObjectNode statesNode = blockNode.objectNode(); for (ByteArrayWrapper key : keys) { byte[] keyBytes = key.getData(); AccountState accountState = repository.getAccountState(keyBytes); ContractDetails details = repository.getContractDetails(keyBytes); JSONHelper.dumpState(statesNode, Hex.toHexString(keyBytes), accountState, details); - } + } blockNode.put("state", statesNode); - + blockNode.put("state_root", Hex.toHexString(state)); blockNode.put("timestamp", String.valueOf(block.getTimestamp())); - + ArrayNode transactionsNode = blockNode.arrayNode(); blockNode.put("transactions", transactionsNode); - + blockNode.put("tx_list_root", ByteUtil.toHexString(block.getTxTrieRoot())); blockNode.put("uncles_hash", "0x" + Hex.toHexString(block.getUnclesHash())); - + // JSONHelper.dumpTransactions(blockNode, // stateRoot, codeHash, code, storage); } 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 adf33582..a7013592 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/JSONReader.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/JSONReader.java @@ -20,7 +20,7 @@ public class JSONReader { json = getFromUrl("https://raw.githubusercontent.com/ethereum/tests/develop/" + filename); return json == "" ? json = getFromLocal(filename) : json; } - + public static String getFromLocal(String filename) { System.out.println("Loading local file: " + filename); try { @@ -36,7 +36,7 @@ public class JSONReader { } return ""; } - + public static String getFromUrl(String urlToRead) { URL url; HttpURLConnection conn; 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 e06e82a4..8e1e3d42 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Logs.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/Logs.java @@ -15,7 +15,7 @@ import org.spongycastle.util.encoders.Hex; public class Logs { List logs = new ArrayList<>(); - + public Logs(JSONArray jLogs) { for (int i = 0; i < jLogs.size(); ++i){ 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 92a2c17d..14651bb8 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestCase.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestCase.java @@ -23,7 +23,7 @@ public class TestCase { // "env": { ... }, private Env env; - + // private Logs logs; @@ -64,7 +64,7 @@ public class TestCase { 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"); @@ -74,7 +74,7 @@ public class TestCase { if(testCaseJSONObj.containsKey("gas")) gasString = testCaseJSONObj.get("gas").toString(); this.gas = ByteUtil.bigIntegerToBytes(new BigInteger(gasString)); - + String outString = null; if(testCaseJSONObj.containsKey("out")) outString = testCaseJSONObj.get("out").toString(); @@ -122,7 +122,7 @@ public class TestCase { public Exec getExec() { return exec; } - + public Logs getLogs() { return logs; } 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 e9d8d136..2d8f493c 100644 --- a/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestRunner.java +++ b/ethereumj-core/src/main/java/org/ethereum/jsontestsuite/TestRunner.java @@ -33,7 +33,7 @@ public class TestRunner { private ProgramTrace trace = null; public List runTestSuite(TestSuite testSuite) { - + Iterator testIterator = testSuite.iterator(); List resultCollector = new ArrayList<>(); 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 5c5e0e30..031d89dd 100644 --- a/ethereumj-core/src/main/java/org/ethereum/manager/WorldManager.java +++ b/ethereumj-core/src/main/java/org/ethereum/manager/WorldManager.java @@ -25,8 +25,8 @@ import static org.ethereum.config.SystemProperties.CONFIG; /** * WorldManager is a singleton containing references to different parts of the system. - * - * @author Roman Mandeleil + * + * @author Roman Mandeleil * Created on: 01/06/2014 10:44 */ @Component @@ -57,12 +57,12 @@ public class WorldManager { @Autowired private AdminInfo adminInfo; - + private final Set pendingTransactions = Collections.synchronizedSet(new HashSet()); @Autowired private EthereumListener listener; - + @PostConstruct public void init() { byte[] cowAddr = HashUtil.sha3("cow".getBytes()); @@ -72,7 +72,7 @@ public class WorldManager { byte[] cbAddr = HashUtil.sha3(secret.getBytes()); wallet.importKey(cbAddr); } - + public void addListener(EthereumListener listener) { logger.info("Ethereum listener added"); ((EthereumListenerWrapper)this.listener).addListener(listener); @@ -115,7 +115,7 @@ public class WorldManager { public EthereumListener getListener() { return listener; } - + public void setWallet(Wallet wallet) { this.wallet = wallet; } @@ -123,11 +123,11 @@ public class WorldManager { public Repository getRepository() { return repository; } - + public Blockchain getBlockchain() { return blockchain; } - + public Wallet getWallet() { return wallet; } 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 7bd327b7..d340bdbf 100644 --- a/ethereumj-core/src/main/java/org/ethereum/mine/Miner.java +++ b/ethereumj-core/src/main/java/org/ethereum/mine/Miner.java @@ -14,18 +14,18 @@ import java.math.BigInteger; /** * The Miner performs the proof-of-work needed for a valid block - * + * * The mining proof-of-work (PoW) exists as a cryptographically secure nonce - * that proves beyond reasonable doubt that a particular amount of computation - * has been expended in the determination of some token value n. - * It is utilised to enforce the blockchain security by giving meaning - * and credence to the notion of difficulty (and, by extension, total difficulty). - * - * However, since mining new blocks comes with an attached reward, - * the proof-of-work not only functions as a method of securing confidence - * that the blockchain will remain canonical into the future, but also as + * that proves beyond reasonable doubt that a particular amount of computation + * has been expended in the determination of some token value n. + * It is utilised to enforce the blockchain security by giving meaning + * and credence to the notion of difficulty (and, by extension, total difficulty). + * + * However, since mining new blocks comes with an attached reward, + * the proof-of-work not only functions as a method of securing confidence + * that the blockchain will remain canonical into the future, but also as * a wealth distribution mechanism. - * + * * See Yellow Paper: http://www.gavwood.com/Paper.pdf (chapter 11.5 Mining Proof-of-Work) */ public class Miner { @@ -36,13 +36,13 @@ public class Miner { /** * Adds a nonce to given block which complies with the given difficulty - * - * For the PoC series, we use a simplified proof-of-work. - * This is not ASIC resistant and is meant merely as a placeholder. - * It utilizes the bare SHA3 hash function to secure the block chain by requiring - * the SHA3 hash of the concatenation of the nonce and the header’s SHA3 hash to be + * + * For the PoC series, we use a simplified proof-of-work. + * This is not ASIC resistant and is meant merely as a placeholder. + * It utilizes the bare SHA3 hash function to secure the block chain by requiring + * the SHA3 hash of the concatenation of the nonce and the header’s SHA3 hash to be * sufficiently low. It is formally defined as PoW: - * + * * PoW(H, n) ≡ BE(SHA3(SHA3(RLP(H!n)) ◦ n)) * * where: @@ -54,7 +54,7 @@ public class Miner { * o is the series concatenation operator; * BE(X) evaluates to the value equal to X when interpreted as a * big-endian-encoded integer. - * + * * @param newBlock without a valid nonce * @param difficulty - the mining difficulty * @return true if valid nonce has been added to the block @@ -76,7 +76,7 @@ public class Miner { byte[] testNonce = new byte[32]; byte[] concat; - + while(ByteUtil.increment(testNonce) && !stop) { if (testNonce[31] == 0 && testNonce[30] == 0){ 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 f053265a..b7ff4fae 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/BlockQueue.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/BlockQueue.java @@ -18,8 +18,8 @@ import java.util.concurrent.ConcurrentLinkedQueue; * The processing queue for blocks to be validated and added to the blockchain. * This class also maintains the list of hashes from the peer with the heaviest sub-tree. * Based on these hashes, blocks are added to the queue. - * - * @author Roman Mandeleil + * + * @author Roman Mandeleil * Created on: 27/07/2014 11:28 */ @Component @@ -27,13 +27,13 @@ public class BlockQueue { private static final Logger logger = LoggerFactory.getLogger("blockqueue"); - /** The list of hashes of the heaviest chain on the network, + /** 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 */ private Queue blockReceivedQueue = new ConcurrentLinkedQueue<>(); - + /** Highest known total difficulty, representing the heaviest chain on the network */ private BigInteger highestTotalDifficulty; @@ -59,7 +59,7 @@ public class BlockQueue { private void nudgeQueue() { if (blockReceivedQueue.isEmpty()) return; - + logger.info("BlockQueue size: {}", blockReceivedQueue.size()); while(!blockReceivedQueue.isEmpty()){ Block block = blockReceivedQueue.poll(); @@ -74,10 +74,10 @@ public class BlockQueue { * Add a list of blocks to the processing queue. * The list is validated by making sure the first block in the received list of blocks * is the next expected block number of the queue. - * + * * The queue is configured to contain a maximum number of blocks to avoid memory issues * If the list exceeds that, the rest of the received blocks in the list are discarded. - * + * * @param blockList - the blocks received from a peer to be added to the queue */ public void addBlocks(List blockList) { @@ -104,13 +104,13 @@ public class BlockQueue { blockReceivedQueue.size(), lastBlock.getNumber()); } - + /** - * Returns the last block in the queue. If the queue is empty, + * Returns the last block in the queue. If the queue is empty, * this will return the last block added to the blockchain. - * + * * @return The last known block this client on the network - * and will never return null as there is + * and will never return null as there is * always the Genesis block at the start of the chain. */ public Block getLastBlock() { @@ -122,7 +122,7 @@ public class BlockQueue { /** * Reset the queue of hashes of blocks to be retrieved * and add the best hash to the top of the queue - * + * * @param hash - the best hash */ public void setBestHash(byte[] hash) { @@ -131,9 +131,9 @@ public class BlockQueue { } /** - * Returns the last added hash to the queue representing + * Returns the last added hash to the queue representing * the latest known block on the network - * + * * @return The best hash on the network known to the client */ public byte[] getBestHash() { @@ -158,10 +158,10 @@ public class BlockQueue { public void addNewBlockHash(byte[] hash){ blockHashQueue.addFirst(hash); } - + /** * Return a list of hashes from blocks that still need to be downloaded. - * + * * @return A list of hashes for which blocks need to be retrieved. */ public List getHashes() { @@ -195,7 +195,7 @@ public class BlockQueue { return 0; } } - + public BigInteger getHighestTotalDifficulty() { return highestTotalDifficulty; } @@ -206,7 +206,7 @@ public class BlockQueue { /** * Returns the current number of blocks in the queue - * + * * @return the current number of blocks in the queue */ public int size() { @@ -223,7 +223,7 @@ public class BlockQueue { } /** - * Cancel and purge the timer-thread that + * Cancel and purge the timer-thread that * processes the blocks in the queue */ public void close() { diff --git a/ethereumj-core/src/main/java/org/ethereum/net/MessageRoundtrip.java b/ethereumj-core/src/main/java/org/ethereum/net/MessageRoundtrip.java index 840a5efc..30ba0f5f 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/MessageRoundtrip.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/MessageRoundtrip.java @@ -7,7 +7,7 @@ import org.ethereum.net.message.Message; * been offered This class also contains the last time a message was offered and * is updated when an answer has been received to it can be removed from the * queue. - * + * * @author Roman Mandeleil */ public class MessageRoundtrip { 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 8037f597..63c44833 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 @@ -8,7 +8,7 @@ public class Capability implements Comparable { public final static String P2P = "p2p"; public final static String ETH = "eth"; public final static String SHH = "shh"; - + private String name; private byte version; @@ -16,7 +16,7 @@ public class Capability implements Comparable { this.name = name; this.version = version; } - + public String getName() { return name; } @@ -24,7 +24,7 @@ public class Capability implements Comparable { public byte getVersion() { return version; } - + @Override public boolean equals(Object obj) { if (this == obj) return true; @@ -41,7 +41,7 @@ public class Capability implements Comparable { public int compareTo(Capability o) { return this.name.compareTo(o.name); } - + public String toString() { return name + ":" + version; } 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 7820b52b..664a7be5 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 @@ -50,12 +50,12 @@ public class PeerClient { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); - + b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONFIG.peerConnectionTimeout()); b.remoteAddress(host, port); - + b.handler(ethereumChannelInitializer); // Start the client. 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 e1838136..719fb3da 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 @@ -76,7 +76,7 @@ public class BlockHashesMessage extends EthMessage { @Override public String toString() { if (!parsed) parse(); - + StringBuffer sb = Utils.getHashlistShort(this.blockHashes); return "[" + this.getCommand().name() + sb.toString() + "] (" + this.blockHashes.size() + ")"; } 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 070011eb..9bad0f09 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 @@ -4,7 +4,7 @@ import org.ethereum.net.eth.EthMessageCodes; import org.ethereum.net.message.Message; public abstract class EthMessage extends Message { - + public EthMessage() {} public EthMessage(byte[] 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 e84b718e..286f5349 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 @@ -7,7 +7,7 @@ import java.util.Map; * A list of commands for the Ethereum network protocol. *
    * The codes for these commands are the first byte in every packet. - * + * * @see * https://github.com/ethereum/wiki/wiki/Ethereum-Wire-Protocol */ @@ -56,8 +56,8 @@ public enum EthMessageCodes { /** * [+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 + * 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. */ NEW_BLOCK(0x07), 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 7eae53a1..0c2f6b6b 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 @@ -9,15 +9,15 @@ import org.spongycastle.util.encoders.Hex; /** * Wrapper around an Ethereum GetBlockHashes message on the network - * + * * @see org.ethereum.net.eth.EthMessageCodes#GET_BLOCK_HASHES */ public class GetBlockHashesMessage extends EthMessage { /** The newest block hash from which to start sending older hashes */ private byte[] bestHash; - - /** The maximum number of blocks to return. + + /** The maximum number of blocks to return. * Note: the peer could return fewer. */ private int maxBlocks; @@ -80,8 +80,8 @@ public class GetBlockHashesMessage extends EthMessage { @Override public String toString() { if (!parsed) parse(); - return "[" + this.getCommand().name() + - " bestHash=" + Hex.toHexString(bestHash) + + return "[" + this.getCommand().name() + + " bestHash=" + Hex.toHexString(bestHash) + " maxBlocks=" + maxBlocks + "]"; } } \ No newline at end of file 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 c2920773..8db2431b 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 @@ -12,7 +12,7 @@ import static org.ethereum.net.eth.EthMessageCodes.GET_BLOCKS; /** * Wrapper around an Ethereum GetBlocks message on the network - * + * * @see org.ethereum.net.eth.EthMessageCodes#GET_BLOCKS */ public class GetBlocksMessage extends EthMessage { 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 0079b3c3..c4eff242 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 @@ -6,12 +6,12 @@ import org.spongycastle.util.encoders.Hex; /** * Wrapper around an Ethereum GetTransactions message on the network - * + * * @see org.ethereum.net.eth.EthMessageCodes#GET_TRANSACTIONS */ 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() { 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 f5d7e83d..4389b9cb 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 @@ -7,7 +7,7 @@ import org.spongycastle.util.encoders.Hex; /** * Wrapper around an Ethereum Blocks message on the network - * + * * @see org.ethereum.net.eth.EthMessageCodes#NEW_BLOCK */ public class NewBlockMessage extends EthMessage { @@ -48,7 +48,7 @@ public class NewBlockMessage extends EthMessage { if (!parsed) parse(); return block; } - + public byte[] getDifficulty(){ if (!parsed) parse(); return difficulty; 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 5dba278c..ef6efc85 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 @@ -9,8 +9,8 @@ import org.spongycastle.util.encoders.Hex; import static org.ethereum.net.eth.EthMessageCodes.STATUS; /** - * Wrapper around an Ethereum Status message on the network - * + * Wrapper around an Ethereum Status message on the network + * * @see org.ethereum.net.eth.EthMessageCodes#STATUS */ public class StatusMessage extends EthMessage { 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 8d00e3e2..953cec13 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 @@ -13,12 +13,12 @@ import java.util.List; import java.util.Set; /** - * Wrapper around an Ethereum Transactions message on the network - * + * Wrapper around an Ethereum Transactions message on the network + * * @see org.ethereum.net.eth.EthMessageCodes#TRANSACTIONS */ public class TransactionsMessage extends EthMessage { - + private Set transactions; public TransactionsMessage(byte[] encoded) { @@ -36,7 +36,7 @@ public class TransactionsMessage extends EthMessage { this.transactions = transactionList; parsed = true; } - + private void parse() { RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0); @@ -48,7 +48,7 @@ public class TransactionsMessage extends EthMessage { } parsed = true; } - + private void encode() { List encodedElements = new ArrayList<>(); encodedElements.add(RLP.encodeByte(TRANSACTIONS.asByte())); @@ -58,7 +58,7 @@ public class TransactionsMessage extends EthMessage { .toArray(new byte[encodedElements.size()][]); this.encoded = RLP.encodeList(encodedElementArray); } - + @Override public byte[] getEncoded() { if (encoded == null) encode(); @@ -80,7 +80,7 @@ public class TransactionsMessage extends EthMessage { public Class getAnswerMessage() { return null; } - + public String toString() { if(!parsed) parse(); StringBuffer sb = new StringBuffer(); 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 1ac0f4da..27ff07ce 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 @@ -2,7 +2,7 @@ package org.ethereum.net.message; /** * Abstract message class for all messages on the Ethereum network - * + * * @author Roman Mandeleil * Created on: 06/04/14 14:58 */ @@ -18,19 +18,19 @@ public abstract class Message { this.encoded = encoded; parsed = false; } - + /** * Gets the RLP encoded byte array of this message - * + * * @return RLP encoded byte array representation of this message */ public abstract byte[] getEncoded(); - + public abstract Class getAnswerMessage(); - + /** * Returns the message in String format - * + * * @return A string with all attributes of the message */ public abstract String toString(); 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 80bdfd98..05cbc32c 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 @@ -4,61 +4,61 @@ import java.util.HashMap; import java.util.Map; /** - * Reason is an optional integer specifying one - * of a number of reasons for disconnect + * Reason is an optional integer specifying one + * of a number of reasons for disconnect */ public enum ReasonCode { /** [0x00] Disconnect request by other peer */ REQUESTED(0x00), - + /** [0x01] */ TCP_ERROR(0x01), - + /** [0x02] Packets can not be parsed */ BAD_PROTOCOL(0x02), - + /** [0x03] This peer is too slow or delivers unreliable data */ USELESS_PEER(0x03), - + /** [0x04] Already too many connections with other peers */ TOO_MANY_PEERS(0x04), - + /** [0x05] Already have a running connection with this peer */ ALREADY_CONNECTED(0x05), - + /** [0x06] Version of the p2p protocol is not the same as ours */ INCOMPATIBLE_PROTOCOL(0x06), - + /** [0x07] Peer identifies itself with the wrong networkId */ INCOMPATIBLE_NETWORK(0x07), - + /** [0x08] Peer quit voluntarily */ PEER_QUITING(0x08), - + /** [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); } } - + private ReasonCode(int reason) { this.reason = reason; } - + public static ReasonCode fromInt(int i) { ReasonCode type = intToTypeMap.get(Integer.valueOf(i)); - if (type == null) + if (type == null) return ReasonCode.UNKNOWN; return type; } - + public byte asByte() { return (byte) reason; } 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 1c29524c..0cffa5a2 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 @@ -19,14 +19,14 @@ import org.spongycastle.util.encoders.Hex; /** * This class contains static values of messages on the network. These message * will always be the same and therefore don't need to be created each time. - * + * * @author Roman Mandeleil * Created on: 13/04/14 20:19 */ 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(); @@ -43,7 +43,7 @@ public class StaticMessages { new Capability(Capability.SHH, ShhHandler.VERSION)); int listenPort = SystemProperties.CONFIG.listenPort(); - return new HelloMessage(p2pVersion, helloAnnouncement, + return new HelloMessage(p2pVersion, helloAnnouncement, capabilities, listenPort, PEER_ID); } 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 fcfdcd06..b93020b2 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 @@ -4,7 +4,7 @@ import org.spongycastle.util.encoders.Hex; /** * Wrapper around an Ethereum GetPeers message on the network - * + * * @see org.ethereum.net.p2p.P2pMessageCodes#GET_PEERS */ public class GetPeersMessage extends P2pMessage { 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 ea68263b..c78e6a7b 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 @@ -15,7 +15,7 @@ import java.util.List; /** * Wrapper around an Ethereum HelloMessage on the network - * + * * @see org.ethereum.net.p2p.P2pMessageCodes#HELLO */ public class HelloMessage extends P2pMessage { @@ -24,7 +24,7 @@ public class HelloMessage extends P2pMessage { private byte p2pVersion; /** The underlying client. A user-readable string. */ private String clientId; - /** A peer-network capability code, readable ASCII and 3 letters. + /** 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 */ @@ -64,10 +64,10 @@ public class HelloMessage extends P2pMessage { 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]; - + Capability cap = new Capability(name, version); this.capabilities.add(cap); } 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 e37b3c65..cc5c435e 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 @@ -32,7 +32,7 @@ import org.springframework.stereotype.Component; /** * Process the basic protocol messages between every peer on the network. - * + * * Peers can send/receive *
      *
    • HELLO : Announce themselves to the network
    • @@ -48,7 +48,7 @@ import org.springframework.stereotype.Component; public class P2pHandler extends SimpleChannelInboundHandler { public final static byte VERSION = 2; - + private final static Logger logger = LoggerFactory.getLogger("net"); private final Timer timer = new Timer("MessageTimer"); @@ -69,7 +69,7 @@ public class P2pHandler extends SimpleChannelInboundHandler { this.peerDiscoveryMode = false; } - + public P2pHandler(MessageQueue msgQueue, boolean peerDiscoveryMode) { this.msgQueue = msgQueue; this.peerDiscoveryMode = peerDiscoveryMode; @@ -167,7 +167,7 @@ public class P2pHandler extends SimpleChannelInboundHandler { ctx.close(); killTimers(); } - + private void processPeers(ChannelHandlerContext ctx, PeersMessage peersMessage) { worldManager.getPeerDiscovery().addPeers(peersMessage.getPeers()); } @@ -264,7 +264,7 @@ public class P2pHandler extends SimpleChannelInboundHandler { if (capability.getName().equals(Capability.ETH)) { EthMessageCodes.setOffset(offset); offset += EthMessageCodes.values().length; - } + } if (capability.getName().equals(Capability.SHH)) { ShhMessageCodes.setOffset(offset); @@ -295,7 +295,7 @@ public class P2pHandler extends SimpleChannelInboundHandler { }, 500, 25000); */ } - + public void killTimers(){ timer.cancel(); timer.purge(); 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 e181e2d2..45c15daa 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 @@ -57,7 +57,7 @@ public class Peer { @Override public String toString() { - return "[ip=" + getAddress().getHostAddress() + + return "[ip=" + getAddress().getHostAddress() + " port=" + getPort() + " peerId=" + getPeerId() + "]"; } 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 d525f4c0..eacc6b84 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 @@ -16,7 +16,7 @@ import org.spongycastle.util.encoders.Hex; /** * Wrapper around an Ethereum Peers message on the network - * + * * @see org.ethereum.net.p2p.P2pMessageCodes#PEERS */ public class PeersMessage extends P2pMessage { 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 c66a8e9c..3252a1d3 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 @@ -4,7 +4,7 @@ import org.spongycastle.util.encoders.Hex; /** * Wrapper around an Ethereum Ping message on the network - * + * * @see org.ethereum.net.p2p.P2pMessageCodes#PING */ public class PingMessage extends P2pMessage { 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 a93d4c06..5b50ea8d 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 @@ -5,7 +5,7 @@ import org.spongycastle.util.encoders.Hex; /** * Wrapper around an Ethereum Pong message on the network - * + * * @see org.ethereum.net.p2p.P2pMessageCodes#PONG */ public class PongMessage extends P2pMessage { 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 b69b05a0..03aaec99 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 @@ -72,7 +72,7 @@ public class DiscoveryChannel { Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); - + b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONFIG.peerConnectionTimeout()); 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 20c033a6..0b07ab52 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 @@ -25,7 +25,7 @@ public class PeerDiscovery { private static final Logger logger = LoggerFactory.getLogger("peerdiscovery"); private final Set peers = Collections.synchronizedSet(new HashSet()); - + private PeerMonitorThread monitor; private ThreadFactory threadFactory; private ThreadPoolExecutor executorPool; @@ -77,11 +77,11 @@ public class PeerDiscovery { public boolean isStarted() { return started.get(); } - + public Set getPeers() { return peers; } - + /** * Update list of known peers with new peers * This method checks for duplicate peer id's and addresses diff --git a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/RejectionLogger.java b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/RejectionLogger.java index 521b7442..93406db5 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/RejectionLogger.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/peerdiscovery/RejectionLogger.java @@ -9,8 +9,8 @@ import java.util.concurrent.ThreadPoolExecutor; /** * A handler to log rejected threads when execution is blocked because the * thread bounds and queue capacities are reached - * - * @author Roman Mandeleil + * + * @author Roman Mandeleil * Created on: 22/05/2014 10:31 */ public class RejectionLogger implements RejectedExecutionHandler { 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 68cd1ae4..7a59cf8f 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 @@ -11,7 +11,7 @@ import org.springframework.stereotype.Component; import java.util.concurrent.ThreadPoolExecutor; /** - * @author Roman Mandeleil + * @author Roman Mandeleil * Created on: 22/05/2014 09:26 */ @Component diff --git a/ethereumj-core/src/main/java/org/ethereum/net/server/PeerServer.java b/ethereumj-core/src/main/java/org/ethereum/net/server/PeerServer.java index 68f6b326..49f98a62 100644 --- a/ethereumj-core/src/main/java/org/ethereum/net/server/PeerServer.java +++ b/ethereumj-core/src/main/java/org/ethereum/net/server/PeerServer.java @@ -57,7 +57,7 @@ public class PeerServer { b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); - + b.option(ChannelOption.SO_KEEPALIVE, true); b.option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, DefaultMessageSizeEstimator.DEFAULT); b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONFIG.peerConnectionTimeout()); 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 c1bd7509..7ee6925f 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 @@ -12,7 +12,7 @@ import org.springframework.stereotype.Component; /** * Process the messages between peers with 'shh' capability on the network. - * + * * Peers with 'shh' capability can send/receive: * * @@ -63,7 +63,7 @@ public class ShhHandler extends SimpleChannelInboundHandler { break; } } - + @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { logger.error(cause.getCause().toString()); 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 6e583a00..817bb1e0 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 @@ -7,7 +7,7 @@ import java.util.Map; * A list of commands for the Whisper network protocol. *
      * The codes for these commands are the first byte in every packet. - * + * * @see * https://github.com/ethereum/wiki/wiki/Wire-Protocol */ 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 7b95f4b9..510e84d1 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 @@ -39,7 +39,7 @@ public class MessageDecoder extends ByteToMessageDecoder { byte[] encoded = new byte[in.readInt()]; in.readBytes(encoded); - + if (loggerWire.isDebugEnabled()) loggerWire.debug("Encoded: [{}]", Hex.toHexString(encoded)); @@ -54,7 +54,7 @@ public class MessageDecoder extends ByteToMessageDecoder { out.add(msg); in.markReaderIndex(); } - + private boolean isValidEthereumPacket(ByteBuf in) { // Ethereum message is at least 8 bytes if (in.readableBytes() < 8) 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 fd6befaf..8cb3fa28 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 @@ -39,10 +39,10 @@ public class MessageEncoder extends MessageToByteEncoder { loggerNet.info("To: \t{} \tSend: \t{}", ctx.channel().remoteAddress(), msg); byte[] encoded = msg.getEncoded(); - + if (loggerWire.isDebugEnabled()) loggerWire.debug("Encoded: [{}]", Hex.toHexString(encoded)); - + out.capacity(encoded.length + 8); out.writeBytes(StaticMessages.SYNC_TOKEN); out.writeBytes(ByteUtil.calcPacketLength(encoded)); 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 de1a1382..1f2ff17a 100644 --- a/ethereumj-core/src/main/java/org/ethereum/serpent/SerpentCompiler.java +++ b/ethereumj-core/src/main/java/org/ethereum/serpent/SerpentCompiler.java @@ -124,7 +124,7 @@ public class SerpentCompiler { // encode ref for 5 bytes for (int i = 0; i < lexaList.size(); ++i) { - + String lexa = lexaList.get(i); if (!lexa.contains("REF_")) continue; lexaList.add(i + 1, lexa); 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 d3db0e1b..a8409552 100644 --- a/ethereumj-core/src/main/java/org/ethereum/trie/Cache.java +++ b/ethereumj-core/src/main/java/org/ethereum/trie/Cache.java @@ -15,7 +15,7 @@ import org.iq80.leveldb.WriteBatch; * Created on: 20/05/2014 10:44 */ public class Cache { - + private Map nodes = new ConcurrentHashMap<>(); private DB db; private boolean isDirty; @@ -26,8 +26,8 @@ public class Cache { /** * Put the node in the cache if RLP encoded value is longer than 32 bytes - * - * @param o the Node which could be a pair-, multi-item Node or single Value + * + * @param o the Node which could be a pair-, multi-item Node or single Value * @return sha3 hash of RLP encoded node if length > 32 otherwise return node itself */ public Object put(Object o) { 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 f0318ef9..670a6458 100644 --- a/ethereumj-core/src/main/java/org/ethereum/trie/Node.java +++ b/ethereumj-core/src/main/java/org/ethereum/trie/Node.java @@ -3,40 +3,40 @@ package org.ethereum.trie; 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) - * - * 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 - * a [ key, value ] node, where the key gives the hexadecimal path - * to descend, in the compact encoding described above, and the value + * + * 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 + * a [ key, value ] node, where the key gives the hexadecimal path + * to descend, in the compact encoding described above, and the value * is just the hash of the node like in the standard radix tree. - * + * * R * / \ * / \ * N N * / \ / \ * L L L L - * * - * Also, we add another conceptual change: internal nodes can no longer - * have values, only leaves with no children of their own can; however, - * since to be fully generic we want the key/value store to be able to - * store keys like 'dog' and 'doge' at the same time, we simply add - * a terminator symbol (16) to the alphabet so there is never a value - * "en-route" to another value. - * + * * + * Also, we add another conceptual change: internal nodes can no longer + * have values, only leaves with no children of their own can; however, + * since to be fully generic we want the key/value store to be able to + * store keys like 'dog' and 'doge' at the same time, we simply add + * a terminator symbol (16) to the alphabet so there is never a value + * "en-route" to another value. + * * Where a node is referenced inside a node, what is included is: - * + * * H(rlp.encode(x)) where H(x) = sha3(x) if len(x) >= 32 else x - * - * Note that when updating a trie, you will need to store the key/value pair (sha3(x), x) + * + * Note that when updating a trie, you will need to store the key/value pair (sha3(x), x) * in a persistent lookup table when you create a node with length >= 32, - * but if the node is shorter than that then you do not need to store anything + * but if the node is shorter than that then you do not need to store anything * when length < 32 for the obvious reason that the function f(x) = x is reversible. * * www.ethereumJ.com @@ -52,7 +52,7 @@ public class Node { public Node(Value val) { this(val, false); } - + public Node(Value val, boolean dirty) { this.value = val; this.dirty = dirty; @@ -65,11 +65,11 @@ public class Node { public boolean isDirty() { return dirty; } - + public void setDirty(boolean ditry) { this.dirty = ditry; } - + public Value getValue() { return value; } diff --git a/ethereumj-core/src/main/java/org/ethereum/trie/Trie.java b/ethereumj-core/src/main/java/org/ethereum/trie/Trie.java index c0382911..5e1ed68f 100644 --- a/ethereumj-core/src/main/java/org/ethereum/trie/Trie.java +++ b/ethereumj-core/src/main/java/org/ethereum/trie/Trie.java @@ -1,14 +1,14 @@ package org.ethereum.trie; /** - * Trie interface for the main data structure in Ethereum + * Trie interface for the main data structure in Ethereum * which is used to store both the account state and storage of each account. */ public interface Trie { - + /** * Gets a value from the trie for a given key - * + * * @param key - any length byte array * @return an rlp encoded byte array of the stored object */ @@ -16,43 +16,43 @@ public interface Trie { /** * Insert or update a value in the trie for a specified key - * + * * @param key - any length byte array * @param value rlp encoded byte array of the object to store */ public void update(byte[] key, byte[] value); - + /** * Deletes a key/value from the trie for a given key - * + * * @param key - any length byte array */ public void delete(byte[] key); - + /** * Returns a SHA-3 hash from the top node of the trie - * - * @return 32-byte SHA-3 hash representing the entire contents of the trie. + * + * @return 32-byte SHA-3 hash representing the entire contents of the trie. */ public byte[] getRootHash(); - + /** * Set the top node of the trie - * + * * @param root - 32-byte SHA-3 hash of the root node */ public void setRoot(byte[] root); - + /** * Commit all the changes until now */ public void sync(); - + /** * Discard all the changes until now */ public void undo(); - + public String getTrieDump(); public boolean validate(); 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 ed1d0082..8aed929d 100644 --- a/ethereumj-core/src/main/java/org/ethereum/trie/TrieImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/trie/TrieImpl.java @@ -19,19 +19,19 @@ import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; /** - * The modified Merkle Patricia tree (trie) provides a persistent data structure - * to map between arbitrary-length binary data (byte arrays). It is defined in terms of - * a mutable data structure to map between 256-bit binary fragments and arbitrary-length - * binary data, typically implemented as a database. The core of the trie, and its sole - * requirement in terms of the protocol specification is to provide a single value that - * identifies a given set of key-value pairs, which may either a 32 byte sequence or - * the empty byte sequence. It is left as an implementation consideration to store and - * maintain the structure of the trie in a manner the allows effective and efficient + * The modified Merkle Patricia tree (trie) provides a persistent data structure + * to map between arbitrary-length binary data (byte arrays). It is defined in terms of + * a mutable data structure to map between 256-bit binary fragments and arbitrary-length + * binary data, typically implemented as a database. The core of the trie, and its sole + * requirement in terms of the protocol specification is to provide a single value that + * identifies a given set of key-value pairs, which may either a 32 byte sequence or + * the empty byte sequence. It is left as an implementation consideration to store and + * maintain the structure of the trie in a manner the allows effective and efficient * realisation of the protocol. * - * The trie implements a caching mechanism and will use cached values if they are present. - * If a node is not present in the cache it will try to fetch it from the database and - * store the cached value. + * The trie implements a caching mechanism and will use cached values if they are present. + * If a node is not present in the cache it will try to fetch it from the database and + * store the cached value. * * Note: the data isn't persisted unless `sync` is explicitly called. * @@ -63,7 +63,7 @@ public class TrieImpl implements Trie { public TrieIterator getIterator() { return new TrieIterator(this); } - + public void setCache(Cache cache) { this.cache = cache; } @@ -101,14 +101,14 @@ public class TrieImpl implements Trie { @Override public byte[] get(byte[] key) { - if (logger.isDebugEnabled()) + if (logger.isDebugEnabled()) logger.debug("Retrieving key {}", Hex.toHexString(key)); byte[] k = binToNibbles(key); Value c = new Value(this.get(this.root, k)); return (c == null)? null : c.asBytes(); } - + /** * Insert key/value pair into trie * @@ -140,7 +140,7 @@ public class TrieImpl implements Trie { public void delete(String key) { this.update(key.getBytes(), "".getBytes()); } - + @Override public void delete(byte[] key) { delete(new String(key)); @@ -149,7 +149,7 @@ public class TrieImpl implements Trie { logger.debug("New root-hash: {}", Hex.toHexString(this.getRootHash())); } } - + @Override public byte[] getRootHash() { if (root == null 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 c4fb1486..fc9c51b1 100644 --- a/ethereumj-core/src/main/java/org/ethereum/trie/TrieIterator.java +++ b/ethereumj-core/src/main/java/org/ethereum/trie/TrieIterator.java @@ -11,7 +11,7 @@ import static org.ethereum.util.CompactEncoder.unpackToNibbles; * Created on: 20/05/2014 10:44 */ public class TrieIterator { - + private TrieImpl trie; private String key; private String value; @@ -73,9 +73,9 @@ public class TrieIterator { public int purge() { List shas = this.collect(); - + for (byte[] sha : shas) { - this.trie.getCache().delete(sha); + this.trie.getCache().delete(sha); } return this.values.size(); } 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 39038e9e..42852511 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/ByteUtil.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/ByteUtil.java @@ -24,7 +24,7 @@ public class ByteUtil { } /** - * The regular {@link java.math.BigInteger#toByteArray()} method isn't quite what we often need: + * The regular {@link java.math.BigInteger#toByteArray()} method isn't quite what we often need: * it appends a leading zero to indicate that the number is positive and may need padding. * * @param b the integer to format into a byte array @@ -39,23 +39,23 @@ public class ByteUtil { int start = (biBytes.length == numBytes + 1) ? 1 : 0; int length = Math.min(biBytes.length, numBytes); System.arraycopy(biBytes, start, bytes, numBytes - length, length); - return bytes; + return bytes; } /** * Omitting sign indication byte. *

      - * Instead of {@link org.spongycastle.util.BigIntegers#asUnsignedByteArray(BigInteger)} + * Instead of {@link org.spongycastle.util.BigIntegers#asUnsignedByteArray(BigInteger)} *
      we use this custom method to avoid an empty array in case of BigInteger.ZERO * * @param value - any big integer number. A null-value will return null - * @return A byte array without a leading zero byte if present in the signed encoding. + * @return A byte array without a leading zero byte if present in the signed encoding. * BigInteger.ZERO will return an array with length 1 and byte-value 0. */ public static byte[] bigIntegerToBytes(BigInteger value) { if (value == null) return null; - + byte[] data = value.toByteArray(); if (data.length != 1 && data[0] == 0) { @@ -66,10 +66,10 @@ public class ByteUtil { return data; } - /** + /** * Returns the amount of nibbles that match each other from 0 ... * amount will never be larger than smallest input - * + * * @param a - first input * @param b - second input * @return Number of bytes that match @@ -84,22 +84,22 @@ public class ByteUtil { } return i; } - + /** * Converts a long value into a byte array. - * + * * @param val - long value to convert * @return byte[] of length 8, representing the long value */ public static byte[] longToBytes(long val) { return ByteBuffer.allocate(8).putLong(val).array(); } - + /** * Convert a byte-array into a hex String.
      - * Works similar to {@link Hex#toHexString} + * Works similar to {@link Hex#toHexString} * but allows for null - * + * * @param data - byte-array to convert to a hex-string * @return hex representation of the data.
      * Returns an empty String if the input is null @@ -109,7 +109,7 @@ public class ByteUtil { public static String toHexString(byte[] data) { return data == null ? "" : Hex.toHexString(data); } - + /** * Calculate packet length * @param msg byte[] @@ -124,14 +124,14 @@ public class ByteUtil { (byte)((msgLen ) & 0xFF)}; return len; } - + /** * Cast hex encoded value from byte[] to int - * + * * Limited to Integer.MAX_VALUE: 2^32-1 (4 bytes) - * + * * @param b array contains the values - * @return unsigned positive int value. + * @return unsigned positive int value. */ public static int byteArrayToInt(byte[] b) { if (b == null || b.length == 0) @@ -153,10 +153,10 @@ public class ByteUtil { return new BigInteger(1, b).longValue(); } - + /** * Turn nibbles to a pretty looking output string - * + * * Example. [ 1, 2, 3, 4, 5 ] becomes '\x11\x23\x45' * * @param nibbles - getting byte of data [ 04 ] and turning @@ -171,7 +171,7 @@ public class ByteUtil { } return buffer.toString(); } - + public static String oneByteToHexString(byte value) { String retVal = Integer.toString(value & 0xFF, 16); if (retVal.length() == 1) retVal = "0" + retVal; @@ -197,7 +197,7 @@ public class ByteUtil { if (bytes == 0) ++bytes; return bytes; } - + /** * @param arg - not more that 32 bits * @return - bytes of the value pad with complete to 32 zeroes @@ -215,7 +215,7 @@ public class ByteUtil { else data = arg.toString().trim().getBytes(); - + if (data.length > 32) throw new RuntimeException("values can't be more than 32 byte"); @@ -304,9 +304,9 @@ public class ByteUtil { /** * Utility function to copy a byte array into a new byte array with given size. - * If the src length is smaller than the given size, the result will be left-padded + * If the src length is smaller than the given size, the result will be left-padded * with zeros. - * + * * @param value - a BigInteger with a maximum value of 2^256-1 * @return Byte array of given size with a copy of the src */ 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 47d75906..5db93a90 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/CompactEncoder.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/CompactEncoder.java @@ -12,29 +12,29 @@ import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; -/** +/** * Compact encoding of hex sequence with optional terminator - * - * The traditional compact way of encoding a hex string is to convert it into binary - * - that is, a string like 0f1248 would become three bytes 15, 18, 72. However, - * this approach has one slight problem: what if the length of the hex string is odd? - * In that case, there is no way to distinguish between, say, 0f1248 and f1248. - * - * Additionally, our application in the Merkle Patricia tree requires the additional feature - * that a hex string can also have a special "terminator symbol" at the end (denoted by the 'T'). - * A terminator symbol can occur only once, and only at the end. - * - * An alternative way of thinking about this to not think of there being a terminator symbol, - * but instead treat bit specifying the existence of the terminator symbol as a bit specifying + * + * The traditional compact way of encoding a hex string is to convert it into binary + * - that is, a string like 0f1248 would become three bytes 15, 18, 72. However, + * this approach has one slight problem: what if the length of the hex string is odd? + * In that case, there is no way to distinguish between, say, 0f1248 and f1248. + * + * Additionally, our application in the Merkle Patricia tree requires the additional feature + * that a hex string can also have a special "terminator symbol" at the end (denoted by the 'T'). + * A terminator symbol can occur only once, and only at the end. + * + * An alternative way of thinking about this to not think of there being a terminator symbol, + * but instead treat bit specifying the existence of the terminator symbol as a bit specifying * that the given node encodes a final node, where the value is an actual value, rather than * the hash of yet another node. - * - * To solve both of these issues, we force the first nibble of the final byte-stream to encode - * two flags, specifying oddness of length (ignoring the 'T' symbol) and terminator status; - * these are placed, respectively, into the two lowest significant bits of the first nibble. + * + * To solve both of these issues, we force the first nibble of the final byte-stream to encode + * two flags, specifying oddness of length (ignoring the 'T' symbol) and terminator status; + * these are placed, respectively, into the two lowest significant bits of the first nibble. * In the case of an even-length hex string, we must introduce a second nibble (of value zero) - * to ensure the hex-string is even in length and thus is representable by a whole number of bytes. - * + * to ensure the hex-string is even in length and thus is representable by a whole number of bytes. + * * Examples: * > [ 1, 2, 3, 4, 5 ] * '\x11\x23\x45' @@ -77,7 +77,7 @@ public class CompactEncoder { */ public static byte[] packNibbles(byte[] nibbles) { int terminator = 0; - + if (nibbles[nibbles.length-1] == TERMINATOR) { terminator = 1; nibbles = copyOf(nibbles, nibbles.length-1); @@ -100,9 +100,9 @@ public class CompactEncoder { /** * Unpack a binary string to its nibbles equivalent - * + * * @param str of binary data - * @return array of nibbles in byte-format + * @return array of nibbles in byte-format */ public static byte[] unpackToNibbles(byte[] str) { byte[] base = binToNibbles(str); @@ -122,7 +122,7 @@ public class CompactEncoder { * Transforms a binary array to hexadecimal format + terminator * * @param str byte[] - * @return array with each individual nibble adding a terminator at the end + * @return array with each individual nibble adding a terminator at the end */ public static byte[] binToNibbles(byte[] str) { byte[] hexEncoded = encode(str); 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 43c59cb6..7bfc4170 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/DecodeResult.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/DecodeResult.java @@ -9,23 +9,23 @@ public class DecodeResult implements Serializable { private int pos; private Object decoded; - + public DecodeResult(int pos, Object decoded) { this.pos = pos; this.decoded = decoded; } - + public int getPos() { return pos; } public Object getDecoded() { return decoded; } - + public String toString() { return asString(this.decoded); } - + private String asString(Object decoded) { if(decoded instanceof String) { return (String) decoded; @@ -37,7 +37,7 @@ public class DecodeResult implements Serializable { result += asString(item); } return result; - } + } throw new RuntimeException("Not a valid type. Should not occur"); } } 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 d3de4c95..f52c43d3 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/FastByteComparisons.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/FastByteComparisons.java @@ -72,7 +72,7 @@ public abstract class FastByteComparisons { 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 @@ -91,7 +91,7 @@ public abstract class FastByteComparisons { return lexicographicalComparerJavaImpl(); } } - + private enum PureJavaComparer implements Comparer { INSTANCE; @@ -116,7 +116,7 @@ public abstract class FastByteComparisons { return length1 - length2; } } - + @SuppressWarnings("unused") // used via reflection private enum UnsafeComparer implements Comparer { INSTANCE; 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 8f4148b1..54b1f91f 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/LRUMap.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/LRUMap.java @@ -10,7 +10,7 @@ public class LRUMap extends ConcurrentHashMap { private static final long serialVersionUID = 1L; protected final int maxEntries; - + public LRUMap(int initialEntries, int maxEntries) { super(initialEntries, 0.8f, 3); this.maxEntries = maxEntries; 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 0d09f5ac..d09a91eb 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/RLP.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/RLP.java @@ -19,8 +19,8 @@ import org.ethereum.util.RLPList; import org.spongycastle.util.encoders.Hex; /** - * Recursive Length Prefix (RLP) encoding. - * + * Recursive Length Prefix (RLP) encoding. + * * The purpose of RLP is to encode arbitrarily nested arrays of binary data, and * RLP is the main encoding method used to serialize objects in Ethereum. The * only purpose of RLP is to encode structure; encoding specific atomic data @@ -30,18 +30,18 @@ import org.spongycastle.util.encoders.Hex; * canonical forms are to either use [[k1,v1],[k2,v2]...] with keys in * lexicographic order or to use the higher-level Patricia Tree encoding as * Ethereum does. - * + * * The RLP encoding function takes in an item. An item is defined as follows: - * + * * - A string (ie. byte array) is an item - A list of items is an item - * + * * For example, an empty string is an item, as is the string containing the word * "cat", a list containing any number of strings, as well as more complex data * structures like ["cat",["puppy","cow"],"horse",[[]],"pig",[""],"sheep"]. Note * that in the context of the rest of this article, "string" will be used as a * synonym for "a certain number of bytes of binary data"; no special encodings * are used and no knowledge about the content of the strings is implied. - * + * * See: https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP * * www.ethereumJ.com @@ -57,16 +57,16 @@ public class RLP { /** * 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 + * - 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 **/ private static int SIZE_THRESHOLD = 56; - + /** RLP encoding rules are defined as follows: */ - + /* * For a single byte whose value is in the [0x00, 0x7f] range, that byte is * its own RLP encoding. @@ -110,12 +110,12 @@ public class RLP { * range of the first byte is thus [0xf8, 0xff]. */ private static int OFFSET_LONG_LIST = 0xf7; - - + + /* ****************************************************** * DECODING * * ******************************************************/ - + private static byte decodeOneByteItem(byte[] data, int index) { // null item if ((data[index] & 0xFF) == OFFSET_SHORT_ITEM) { @@ -183,7 +183,7 @@ public class RLP { } return value; } - + private static String decodeStringItem(byte[] data, int index) { String value = null; @@ -281,7 +281,7 @@ public class RLP { value = valueBytes; return value; } - + private static int nextItemLength(byte[] data, int index) { if (index >= data.length) @@ -517,7 +517,7 @@ public class RLP { } return length; } - + private static int calcLengthRaw(int lengthOfLength, byte[] msgData, int index) { byte pow = (byte) (lengthOfLength - 1); int length = 0; @@ -527,7 +527,7 @@ public class RLP { } return length; } - + public static byte getCommandCode(byte[] data) { byte command = 0; int index = getFirstListElement(data, 0); @@ -535,7 +535,7 @@ public class RLP { command = ((int) (command & 0xFF) == OFFSET_SHORT_ITEM) ? 0 : command; return command; } - + /** * Parse wire byte[] message into RLP elements * @@ -671,11 +671,11 @@ public class RLP { throw new RuntimeException("RLP wrong encoding", e); } } - + /** * Reads any RLP encoded byte-array and returns all objects as byte-array or list of byte-arrays - * - * @param data RLP encoded byte-array + * + * @param data RLP encoded byte-array * @param pos position in the array to start reading * @return DecodeResult encapsulates the decoded items as a single Object and the final read position */ @@ -709,7 +709,7 @@ public class RLP { throw new RuntimeException("Only byte values between 0x00 and 0xFF are supported, but got: " + prefix); } } - + private static DecodeResult decodeList(byte[] data, int pos, int prevPos, int len) { List slice = new ArrayList<>(); for (int i = 0; i < len;) { @@ -723,17 +723,17 @@ public class RLP { } return new DecodeResult(pos, slice.toArray()); } - + /* ****************************************************** * ENCODING * * ******************************************************/ - + /** * Turn Object into its RLP encoded equivalent of a byte-array * Support for String, Integer, BigInteger and Lists of any of these types. - * + * * @param input as object or List of objects - * @return byte[] RLP encoded + * @return byte[] RLP encoded */ public static byte[] encode(Object input) { Value val = new Value(input); @@ -749,16 +749,16 @@ public class RLP { byte[] prefix = encodeLength(output.length, OFFSET_SHORT_LIST); return concatenate(prefix, output); } else { - byte[] inputAsBytes = toBytes(input); + byte[] inputAsBytes = toBytes(input); if (inputAsBytes.length == 1) { return inputAsBytes; } else { - byte[] firstByte = encodeLength(inputAsBytes.length, OFFSET_SHORT_ITEM); + byte[] firstByte = encodeLength(inputAsBytes.length, OFFSET_SHORT_ITEM); return concatenate(firstByte, inputAsBytes); } - } + } } - + /** 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) { @@ -796,7 +796,7 @@ public class RLP { (byte) (singleShort >> 0 & 0xFF) }; } } - + public static byte[] encodeInt(int singleInt) { if (singleInt <= 0xFF) return encodeByte((byte) singleInt); @@ -821,9 +821,9 @@ public class RLP { } public static byte[] encodeBigInteger(BigInteger srcBigInteger) { - if(srcBigInteger == BigInteger.ZERO) + if(srcBigInteger == BigInteger.ZERO) return encodeByte((byte)0); - else + else return encodeElement(asUnsignedByteArray(srcBigInteger)); } @@ -910,9 +910,9 @@ public class RLP { } return data; } - + /* - * Utility function to convert Objects into byte arrays + * Utility function to convert Objects into byte arrays */ private static byte[] toBytes(Object input) { if (input instanceof byte[]) { @@ -921,10 +921,10 @@ public class RLP { String inputString = (String) input; return inputString.getBytes(); } else if(input instanceof Long) { - Long inputLong = (Long) input; + Long inputLong = (Long) input; return (inputLong == 0) ? ByteUtil.EMPTY_BYTE_ARRAY : asUnsignedByteArray(BigInteger.valueOf(inputLong)); } else if(input instanceof Integer) { - Integer inputInt = (Integer) input; + Integer inputInt = (Integer) input; return (inputInt == 0) ? ByteUtil.EMPTY_BYTE_ARRAY : asUnsignedByteArray(BigInteger.valueOf(inputInt.intValue())); } else if(input instanceof BigInteger) { BigInteger inputBigInt = (BigInteger) input; 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 f942b112..e0305afd 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/RLPItem.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/RLPItem.java @@ -2,18 +2,18 @@ package org.ethereum.util; /** - * www.ethereumJ.com + * www.ethereumJ.com * @author: Roman Mandeleil * Created on: 21/04/14 16:26 */ public class RLPItem implements RLPElement { byte[] rlpData; - + public RLPItem(byte[] rlpData) { this.rlpData = rlpData; } - + public byte[] getRLPData() { if (rlpData.length == 0) return null; 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 f0223bda..6a5cd4d5 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/RLPList.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/RLPList.java @@ -26,7 +26,7 @@ public class RLPList extends ArrayList implements RLPElement { if (element instanceof RLPList) { RLPList rlpList = (RLPList) element; - System.out.print("["); + System.out.print("["); for (RLPElement singleElement : rlpList) { recursivePrint(singleElement); } 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 128ab32b..657dbd11 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/Utils.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/Utils.java @@ -29,11 +29,11 @@ public class Utils { byte[] numberBytes = Hex.decode(hexNum.substring(2)); return (new BigInteger(1, numberBytes)).toString(); } - - /** + + /** * Return formatted Date String: yyyy.MM.dd HH:mm:ss * Based on Unix's time() input in seconds - * + * * @param timestamp seconds since start of Unix-time * @return String formatted as - yyyy.MM.dd HH:mm:ss */ @@ -42,7 +42,7 @@ public class Utils { DateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); return formatter.format(date); } - + public static ImageIcon getImageIcon(String resource) { URL imageURL = ClassLoader.getSystemResource(resource); ImageIcon image = new ImageIcon(imageURL); @@ -59,10 +59,10 @@ public class Utils { } return result.toString() + "·(" + "10^" + pow + ")"; } - + /** - * Decodes a hex string to address bytes and checks validity - * + * Decodes a hex string to address bytes and checks validity + * * @param hex - a hex string of the address, e.g., 6c386a4b26f73c802f34673f7248bb118f97424a * @return - decode and validated address byte[] */ @@ -70,12 +70,12 @@ public class Utils { byte[] addr = null; try { addr = Hex.decode(hex); } catch(DecoderException addressIsNotValid) { return null; } - + if(isValidAddress(addr)) return addr; return null; } - + public static boolean isValidAddress(byte[] addr) { return addr != null && addr.length == 20; } 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 f755896a..04653f5c 100644 --- a/ethereumj-core/src/main/java/org/ethereum/util/Value.java +++ b/ethereumj-core/src/main/java/org/ethereum/util/Value.java @@ -30,7 +30,7 @@ public class Value { this.value = obj; } } - + /* ***************** * Convert * *****************/ @@ -102,7 +102,7 @@ public class Value { // If this wasn't a slice you probably shouldn't be using this function return new Value(null); } - + /* ***************** * Utility * *****************/ @@ -114,7 +114,7 @@ public class Value { public boolean cmp(Value o) { return DeepEquals.deepEquals(this, o); } - + /* ***************** * Checks * *****************/ 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 b92a5255..3ae3eb09 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/DataWord.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/DataWord.java @@ -50,7 +50,7 @@ public class DataWord implements Comparable { else if (data.length <= 32) System.arraycopy(data, 0, this.data, 32 - data.length, data.length); else - throw new RuntimeException("Data word can't exit 32 bytes: " + data); + throw new RuntimeException("Data word can't exit 32 bytes: " + data); } public byte[] getData() { @@ -67,12 +67,12 @@ public class DataWord implements Comparable { public BigInteger value() { return new BigInteger(1, data); } - + /** - * Converts this DataWord to an int, checking for lost information. - * If this DataWord is out of the possible range for an int result + * Converts this DataWord to an int, checking for lost information. + * If this DataWord is out of the possible range for an int result * then an ArithmeticException is thrown. - * + * * @return this DataWord converted to an int. * @throws ArithmeticException - if this will not fit in an int. */ @@ -82,12 +82,12 @@ public class DataWord implements Comparable { return Integer.MAX_VALUE; return tmpValue.intValueExact(); } - + /** - * Converts this DataWord to a long, checking for lost information. - * If this DataWord is out of the possible range for a long result + * Converts this DataWord to a long, checking for lost information. + * If this DataWord is out of the possible range for a long result * then an ArithmeticException is thrown. - * + * * @return this DataWord converted to a long. * @throws ArithmeticException - if this will not fit in a long. */ @@ -153,7 +153,7 @@ public class DataWord implements Comparable { if (this.data[i] != 0) break; } } - + public void bnot() { if (this.isZero()) return; this.data = ByteUtil.copyToArray(MAX_VALUE.subtract(this.value())); @@ -170,13 +170,13 @@ public class DataWord implements Comparable { } this.data = result; } - + // old add-method with BigInteger quick hack public void add2(DataWord word) { BigInteger result = value().add(word.value()); this.data = ByteUtil.copyToArray(result.and(MAX_VALUE)); } - + // TODO: mul can be done in more efficient way // TODO: with shift left shift right trick // TODO without BigInteger quick hack @@ -212,7 +212,7 @@ public class DataWord implements Comparable { // TODO: improve with no BigInteger public void sub(DataWord word) { - BigInteger result = value().subtract(word.value()); + BigInteger result = value().subtract(word.value()); this.data = ByteUtil.copyToArray(result.and(MAX_VALUE)); } @@ -244,22 +244,22 @@ public class DataWord implements Comparable { BigInteger result = sValue().remainder(word.sValue()); this.data = ByteUtil.copyToArray(result.and(MAX_VALUE)); } - + public void addmod(DataWord word1, DataWord word2) { this.add(word1); BigInteger result = this.value().mod(word2.value()); this.data = ByteUtil.copyToArray(result.and(MAX_VALUE)); } - + public void mulmod(DataWord word1, DataWord word2) { BigInteger result = value().multiply(word1.value()).mod(word2.value()); this.data = ByteUtil.copyToArray(result.and(MAX_VALUE)); } - + public String toString() { return Hex.toHexString(data); } - + public String shortHex() { String hexValue = Hex.toHexString(getNoLeadZeroesData()).toUpperCase(); return "0x" + hexValue.replaceFirst("^0+(?!$)", ""); @@ -280,7 +280,7 @@ public class DataWord implements Comparable { return true; } - + @Override public int hashCode() { return java.util.Arrays.hashCode(data); 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 89151d13..36115d3b 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/GasCost.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/GasCost.java @@ -1,9 +1,9 @@ package org.ethereum.vm; /** - * The fundamental network cost unit. Paid for exclusively by Ether, which is converted - * freely to and from Gas as required. Gas does not exist outside of the internal Ethereum - * computation engine; its price is set by the Transaction and miners are free to + * The fundamental network cost unit. Paid for exclusively by Ether, which is converted + * freely to and from Gas as required. Gas does not exist outside of the internal Ethereum + * computation engine; its price is set by the Transaction and miners are free to * ignore Transactions whose Gas price is too low. */ public class GasCost { 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 389f3ebf..f8075831 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/MessageCall.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/MessageCall.java @@ -5,13 +5,13 @@ package org.ethereum.vm; * This can either be a normal CALL, STATELESS call or POST call. */ public class MessageCall { - - public enum MsgType { - CALL, - STATELESS, + + public enum MsgType { + CALL, + STATELESS, POST; } - + /** Type of internal call. Either CALL, STATELESS or POST */ private MsgType type; @@ -39,7 +39,7 @@ public class MessageCall { this.inDataOffs = inDataOffs; this.inDataSize = inDataSize; } - + public MessageCall(MsgType type, DataWord gas, DataWord codeAddress, DataWord endowment, DataWord inDataOffs, DataWord inDataSize, DataWord outDataOffs, DataWord 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 99481fcd..2d74c398 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/OpCode.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/OpCode.java @@ -5,7 +5,7 @@ import java.util.Map; /** * Instruction set for the Ethereum Virtual Machine - * See Yellow Paper: http://www.gavwood.com/Paper.pdf + * See Yellow Paper: http://www.gavwood.com/Paper.pdf * - Appendix G. Virtual Machine Specification */ public enum OpCode { @@ -29,10 +29,10 @@ public enum OpCode { MOD(0x06, 2), /** (0x07) Signed modulo remainder operation*/ SMOD(0x07, 2), - /** (0x08) Addition combined with modulo + /** (0x08) Addition combined with modulo * remainder operation */ ADDMOD(0x08, 3), - /** (0x09) Multiplication combined with modulo + /** (0x09) Multiplication combined with modulo * remainder operation */ MULMOD(0x09, 3), /** (0x0a) Exponential operation */ @@ -72,7 +72,7 @@ public enum OpCode { /* Environmental Information */ - /** (0x30) Get address of currently + /** (0x30) Get address of currently * executing account */ ADDRESS(0x30, 0), /** (0x31) Get balance of the given account */ @@ -81,38 +81,38 @@ public enum OpCode { ORIGIN(0x32, 0), /** (0x33) Get caller address */ CALLER(0x33, 0), - /** (0x34) Get deposited value by the - * instruction/transaction responsible + /** (0x34) Get deposited value by the + * instruction/transaction responsible * for this execution */ CALLVALUE(0x34, 0), - /** (0x35) Get input data of current + /** (0x35) Get input data of current * environment */ CALLDATALOAD(0x35, 1), /** (0x36) Get size of input data in current * environment */ CALLDATASIZE(0x36, 0), - /** (0x37) Copy input data in current + /** (0x37) Copy input data in current * environment to memory */ CALLDATACOPY(0x37, 3), - /** (0x38) Get size of code running in + /** (0x38) Get size of code running in * current environment */ CODESIZE(0x38, 0), - /** (0x39) Copy code running in current + /** (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 + /** (0x3a) Get price of gas in current * environment */ GASPRICE(0x3a, 0), - /** (0x3b) Get size of code running in + /** (0x3b) Get size of code running in * current environment with given offset */ EXTCODESIZE(0x3b, 1), - /** (0x3c) Copy code running in current + /** (0x3c) Copy code running in current * environment to memory with given offset */ EXTCODECOPY(0x3c, 4), /* Block Information */ - /** (0x40) Get hash of most recent + /** (0x40) Get hash of most recent * complete block */ PREVHASH(0x40, 0), /** (0x41) Get the block’s coinbase address */ @@ -142,7 +142,7 @@ public enum OpCode { SSTORE(0x55, 2), /** (0x56) Alter the program counter */ JUMP(0x56, 1), - /** (0x57) Conditionally alter the program + /** (0x57) Conditionally alter the program * counter */ JUMPI(0x57, 2), /** (0x58) Get the program counter */ @@ -218,7 +218,7 @@ public enum OpCode { PUSH30(0x7d, 0), /** (0x7e) Place 31-byte item on stack */ PUSH31(0x7e, 0), - /** (0x7f) Place 32-byte (full word) + /** (0x7f) Place 32-byte (full word) * item on stack */ PUSH32(0x7f, 0), @@ -316,7 +316,7 @@ public enum OpCode { private byte opcode; private int require; - + private static final Map intToTypeMap = new HashMap<>(); private static final Map stringToByteMap = new HashMap<>(); @@ -326,19 +326,19 @@ public enum OpCode { stringToByteMap.put(type.name(), type.opcode); } } - + private OpCode(int op, int require) { this.opcode = (byte) op; this.require = require; } - + public byte val() { return opcode; } - + /** * Returns the mininum amount of items required on the stack for this operation - * + * * @return minimum amount of expected items on the stack */ public int require() { 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 cbf93ea2..58b46266 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/Program.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/Program.java @@ -32,7 +32,7 @@ import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; * Created on: 01/06/2014 10:45 */ public class Program { - + private static final Logger logger = LoggerFactory.getLogger("VM"); private static final Logger gasLogger = LoggerFactory.getLogger("gas"); @@ -57,10 +57,10 @@ public class Program { ProgramInvoke invokeData; public Program(byte[] ops, ProgramInvoke invokeData) { - + if (ops == null) ops = EMPTY_BYTE_ARRAY; this.ops = ops; - + if (invokeData != null) { this.invokeData = invokeData; this.programAddress = invokeData.getOwnerAddress(); @@ -88,7 +88,7 @@ public class Program { public void setLastOp(byte op) { this.lastOp = op; } - + /** * Should be set only after the OP is fully executed * @param op @@ -96,7 +96,7 @@ public class Program { public void setPreviouslyExecutedOp(byte op) { this.previouslyExecutedOp = op; } - + /** * returns the last fully executed OP * @return @@ -104,7 +104,7 @@ public class Program { public byte getPreviouslyExecutedOp() { return this.previouslyExecutedOp; } - + public void stackPush(byte[] data) { DataWord stackWord = new DataWord(data); stack.push(stackWord); @@ -123,7 +123,7 @@ public class Program { public void stackPush(DataWord stackWord) { stack.push(stackWord); } - + public Stack getStack() { return this.stack; } @@ -138,7 +138,7 @@ public class Program { public void setPC(int pc) { this.pc = pc; - + if (this.pc >= ops.length) stop(); } @@ -175,11 +175,11 @@ public class Program { public DataWord stackPop() { return stack.pop(); } - + /** * Verifies that the stack is at least stackSize * @param stackSize int - * @throws StackTooSmallException If the stack is + * @throws StackTooSmallException If the stack is * smaller than stackSize */ public void stackRequire(int stackSize) { @@ -203,7 +203,7 @@ public class Program { /** * Allocates a piece of memory and stores value at given offset address - * + * * @param addr is the offset address * @param allocSize size of memory needed to write * @param value the data to write to memory @@ -213,11 +213,11 @@ public class Program { allocateMemory(addr, allocSize); System.arraycopy(value, 0, memory.array(), addr, value.length); } - + public DataWord memoryLoad(DataWord addr) { return memoryLoad(addr.intValue()); } - + public DataWord memoryLoad(int address) { allocateMemory(address, DataWord.ZERO.getData().length); @@ -255,14 +255,14 @@ public class Program { /** * Allocates extra memory in the program for * a specified size, calculated from a given offset - * + * * @param offset the memory address offset * @param size the number of bytes to allocate */ public void allocateMemory(int offset, int size) { int memSize = memory != null ? memory.limit() : 0; - double newMemSize = Math.max(memSize, size != 0 ? + double newMemSize = Math.max(memSize, size != 0 ? Math.ceil((double) (offset + size) / 32) * 32 : 0); ByteBuffer tmpMem = ByteBuffer.allocate((int)newMemSize); if (memory != null) @@ -295,7 +295,7 @@ public class Program { byte[] senderAddress = this.getOwnerAddress().getLast20Bytes(); if (logger.isInfoEnabled()) logger.info("creating a new contract inside contract run: [{}]", Hex.toHexString(senderAddress)); - + // actual gas subtract DataWord gasLimit = this.getGas(); this.spendGas(gasLimit.longValue(), "internal call"); @@ -332,9 +332,9 @@ public class Program { ProgramInvoke programInvoke = programInvokeFactory.createProgramInvoke( this, new DataWord(newAddress), DataWord.ZERO, gasLimit, newBalance, null, track); - + ProgramResult result = null; - + if (programCode != null && programCode.length != 0) { VM vm = new VM(); Program program = new Program(programCode, programInvoke); @@ -343,8 +343,8 @@ public class Program { this.result.addDeleteAccounts(result.getDeleteAccounts()); this.result.addLogInfos(result.getLogInfoList()); } - - if (result != null && + + if (result != null && result.getException() != null && result.getException() instanceof Program.OutOfGasException) { logger.debug("contract run halted by Exception: contract: [{}], exception: [{}]", @@ -374,7 +374,7 @@ public class Program { // IN SUCCESS PUSH THE ADDRESS INTO THE STACK stackPush(new DataWord(newAddress)); - + // 5. REFUND THE REMAIN GAS long refundGas = gasLimit.longValue() - result.getGasUsed(); @@ -390,14 +390,14 @@ public class Program { /** * That method is for internal code invocations - * + * * - Normal calls invoke a specified contract which updates itself * - Stateless calls invoke code from another contract, within the context of the caller * * @param msg is the message call object */ public void callToAddress(MessageCall msg) { - + byte[] data = memoryChunk(msg.getInDataOffs(), msg.getInDataSize()).array(); // FETCH THE SAVED STORAGE @@ -420,7 +420,7 @@ public class Program { Hex.toHexString(senderAddress), Hex.toHexString(codeAddress)); throw new OutOfGasException(); } - + BigInteger endowment = msg.getEndowment().value(); BigInteger senderBalance = result.getRepository().getBalance(senderAddress); if (senderBalance.compareTo(endowment) < 0) { @@ -429,22 +429,22 @@ public class Program { } result.getRepository().addBalance(senderAddress, endowment.negate()); BigInteger contextBalance = result.getRepository().addBalance(contextAddress, endowment); - + if (invokeData.byTestingSuite()) { // This keeps track of the calls created for a test this.getResult().addCallCreate(data, contextAddress, - msg.getGas().getNoLeadZeroesData(), + msg.getGas().getNoLeadZeroesData(), msg.getEndowment().getNoLeadZeroesData()); } - + // actual gas subtract this.spendGas(msg.getGas().longValue(), "internal call"); - + Repository trackRepository = result.getRepository().startTracking(); ProgramInvoke programInvoke = programInvokeFactory.createProgramInvoke( this, new DataWord(contextAddress), msg.getEndowment(), msg.getGas(), contextBalance, data, trackRepository); - + ProgramResult result = null; if (programCode != null && programCode.length != 0) { @@ -456,7 +456,7 @@ public class Program { this.result.addDeleteAccounts(result.getDeleteAccounts()); this.result.addLogInfos(result.getLogInfoList()); } - + if (result != null && result.getException() != null && result.getException() instanceof Program.OutOfGasException) { @@ -483,11 +483,11 @@ public class Program { this.memorySave(offset, allocSize, buffer.array()); } } - + // 4. THE FLAG OF SUCCESS IS ONE PUSHED INTO THE STACK trackRepository.commit(); stackPushOne(); - + // 5. REFUND THE REMAIN GAS if (result != null) { BigInteger refundGas = msg.getGas().value().subtract(BigInteger.valueOf(result.getGasUsed())); @@ -511,7 +511,7 @@ public class Program { throw new OutOfGasException(); result.spendGas(gasValue); } - + public void spendAllGas() { spendGas(invokeData.getGas().longValue() - result.getGasUsed(), "Spending all remaining"); } @@ -534,11 +534,11 @@ public class Program { DataWord valWord = new DataWord(val); result.getRepository().addStorageRow(this.programAddress.getLast20Bytes(), keyWord, valWord); } - + public byte[] getCode() { return ops; } - + public byte[] getCodeAt(DataWord address) { byte[] code = invokeData.getRepository().getCode(address.getLast20Bytes()); @@ -637,7 +637,7 @@ public class Program { public void setRuntimeFailure(RuntimeException e) { result.setException(e); } - + public String memoryToString() { StringBuilder memoryData = new StringBuilder(); StringBuilder firstLine = new StringBuilder(); @@ -645,7 +645,7 @@ public class Program { for (int i = 0; memory != null && i < memory.limit(); ++i) { byte value = memory.get(i); - // Check if value is ASCII + // Check if value is ASCII String character = ((byte) 0x20 <= value && value <= (byte) 0x7e) ? new String(new byte[] { value }) : "?"; firstLine.append(character).append(""); secondLine.append(ByteUtil.oneByteToHexString(value)).append(" "); @@ -820,29 +820,29 @@ public class Program { public static String stringify(byte[] code, int index, String result) { if(code == null || code.length == 0) return result; - + OpCode op = OpCode.code(code[index]); byte[] continuedCode = null; - + switch(op) { case PUSH1: case PUSH2: case PUSH3: case PUSH4: case PUSH5: case PUSH6: case PUSH7: case PUSH8: case PUSH9: case PUSH10: case PUSH11: case PUSH12: case PUSH13: case PUSH14: case PUSH15: case PUSH16: 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: result += ' ' + op.name() + ' '; - + int nPush = op.val() - OpCode.PUSH1.val() + 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); break; - + default: result += ' ' + op.name(); continuedCode = Arrays.copyOfRange(code, index + 1, code.length); break; - } + } return stringify(continuedCode, 0, result); } @@ -856,13 +856,13 @@ public class Program { @SuppressWarnings("serial") public class OutOfGasException extends RuntimeException {} - + @SuppressWarnings("serial") public class IllegalOperationException extends RuntimeException {} - + @SuppressWarnings("serial") public class BadJumpDestinationException extends RuntimeException {} - + @SuppressWarnings("serial") public class StackTooSmallException extends RuntimeException { public StackTooSmallException(String message) { 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 1ded4634..5af0957a 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactoryImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeFactoryImpl.java @@ -28,14 +28,14 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { @Autowired private Blockchain blockchain; - /** + /** * This attribute defines the number of recursive calls allowed in the EVM * Note: For the JVM to reach this level without a StackOverflow exception, - * ethereumj may need to be started with a JVM argument to increase + * ethereumj may need to be started with a JVM argument to increase * the stack size. For example: -Xss10m */ - private static final int MAX_DEPTH = 1024; - + private static final int MAX_DEPTH = 1024; + // Invocation by the wire tx @Override public ProgramInvoke createProgramInvoke(Transaction tx, Block block, Repository repository) { @@ -188,7 +188,7 @@ public class ProgramInvokeFactoryImpl implements ProgramInvokeFactory { Hex.toHexString(difficulty.getNoLeadZeroesData()), gasLimit.longValue()); } - + if (program.invokeData.getCallDeep() >= MAX_DEPTH) throw program.new OutOfGasException(); 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 049bff03..162d928e 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeImpl.java @@ -21,7 +21,7 @@ public class ProgramInvokeImpl implements ProgramInvoke { byte[] msgData; /*** BLOCK env ***/ - private DataWord prevHash, coinbase, timestamp, + private DataWord prevHash, coinbase, timestamp, number, difficulty, gaslimit; Map storage; @@ -151,7 +151,7 @@ public class ProgramInvokeImpl implements ProgramInvoke { return new DataWord(); if (index + size > msgData.length) size = msgData.length - index; - + byte[] data = new byte[32]; System.arraycopy(msgData, index, data, 0, size); return new DataWord(data); 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 f7f35008..9a0c73ef 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeMockImpl.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/ProgramInvokeMockImpl.java @@ -22,7 +22,7 @@ public class ProgramInvokeMockImpl implements ProgramInvoke { // default for most tests. This can be overwritten by the test private long gasLimit = 1000000; - + public ProgramInvokeMockImpl(byte[] msgDataRaw) { this(); this.msgData = msgDataRaw; @@ -31,9 +31,9 @@ public class ProgramInvokeMockImpl implements ProgramInvoke { public ProgramInvokeMockImpl() { this.repository = new RepositoryImpl("detailsMoc", "stateMoc"); this.repository.createAccount(ownerAddress); - + this.repository.createAccount(contractAddress); - this.repository.saveCode(contractAddress, + this.repository.saveCode(contractAddress, Hex.decode("385E60076000396000605f556014600054601e60" + "205463abcddcba6040545b51602001600a525451" + "6040016014525451606001601e52545160800160" @@ -84,7 +84,7 @@ public class ProgramInvokeMockImpl implements ProgramInvoke { /* GAS op */ public DataWord getGas() { - + return new DataWord(gasLimit); } @@ -190,10 +190,10 @@ public class ProgramInvokeMockImpl implements ProgramInvoke { public DataWord getGaslimit() { return new DataWord(gasLimit); } - + public void setGasLimit(long gasLimit) { this.gasLimit = gasLimit; - } + } public void setOwnerAddress(byte[] ownerAddress) { this.ownerAddress = ownerAddress; 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 dd81100d..43bf590c 100644 --- a/ethereumj-core/src/main/java/org/ethereum/vm/VM.java +++ b/ethereumj-core/src/main/java/org/ethereum/vm/VM.java @@ -26,35 +26,35 @@ import static org.ethereum.vm.OpCode.PUSH1; /** * The Ethereum Virtual Machine (EVM) is responsible for initialization * and executing a transaction on a contract. - * - * It is a quasi-Turing-complete machine; the quasi qualification - * comes from the fact that the computation is intrinsically bounded + * + * It is a quasi-Turing-complete machine; the quasi qualification + * comes from the fact that the computation is intrinsically bounded * through a parameter, gas, which limits the total amount of computation done. * - * The EVM is a simple stack-based architecture. The word size of the machine - * (and thus size of stack item) is 256-bit. This was chosen to facilitate - * the SHA3-256 hash scheme and elliptic-curve computations. The memory model - * is a simple word-addressed byte array. The stack has an unlimited size. - * The machine also has an independent storage model; this is similar in concept - * to the memory but rather than a byte array, it is a word-addressable word array. - * - * Unlike memory, which is volatile, storage is non volatile and is - * maintained as part of the system state. All locations in both storage + * The EVM is a simple stack-based architecture. The word size of the machine + * (and thus size of stack item) is 256-bit. This was chosen to facilitate + * the SHA3-256 hash scheme and elliptic-curve computations. The memory model + * is a simple word-addressed byte array. The stack has an unlimited size. + * The machine also has an independent storage model; this is similar in concept + * to the memory but rather than a byte array, it is a word-addressable word array. + * + * Unlike memory, which is volatile, storage is non volatile and is + * maintained as part of the system state. All locations in both storage * and memory are well-defined initially as zero. - * - * The machine does not follow the standard von Neumann architecture. - * Rather than storing program code in generally-accessible memory or storage, - * it is stored separately in a virtual ROM interactable only though + * + * The machine does not follow the standard von Neumann architecture. + * Rather than storing program code in generally-accessible memory or storage, + * it is stored separately in a virtual ROM interactable only though * a specialised instruction. - * - * The machine can have exceptional execution for several reasons, - * including stack underflows and invalid instructions. These unambiguously - * and validly result in immediate halting of the machine with all state changes - * left intact. The one piece of exceptional execution that does not leave - * state changes intact is the out-of-gas (OOG) exception. - * - * Here, the machine halts immediately and reports the issue to - * the execution agent (either the transaction processor or, recursively, + * + * The machine can have exceptional execution for several reasons, + * including stack underflows and invalid instructions. These unambiguously + * and validly result in immediate halting of the machine with all state changes + * left intact. The one piece of exceptional execution that does not leave + * state changes intact is the out-of-gas (OOG) exception. + * + * Here, the machine halts immediately and reports the issue to + * the execution agent (either the transaction processor or, recursively, * the spawning execution environment) and which will deal with it separately. * * www.ethereumJ.com @@ -62,22 +62,22 @@ import static org.ethereum.vm.OpCode.PUSH1; * Created on: 01/06/2014 10:44 */ public class VM { - + private static final Logger logger = LoggerFactory.getLogger("VM"); private static final Logger dumpLogger = LoggerFactory.getLogger("dump"); private static BigInteger _32_ = BigInteger.valueOf(32); private static String logString = "[{}]\t Op: [{}] Gas: [{}] Deep: [{}] Hint: [{}]"; - + private static BigInteger MAX_GAS = BigInteger.valueOf(Long.MAX_VALUE); - + /* Keeps track of the number of steps performed in this VM */ private int vmCounter = 0; - + public void step(Program program) { if (CONFIG.vmTrace()) program.saveOpTrace(); - + try { OpCode op = OpCode.code(program.getCurrentOp()); if (op == null) @@ -96,7 +96,7 @@ public class VM { long gasCost = GasCost.STEP; long gasBefore = program.getGas().longValue(); int stepBefore = program.getPC(); - + // Calculate fees and spend gas switch (op) { case STOP: case SUICIDE: @@ -123,7 +123,7 @@ public class VM { case BALANCE: gasCost = GasCost.BALANCE; break; - + // These all operate on memory and therefore potentially expand it: case MSTORE: newMemSize = memNeeded(stack.peek(), new DataWord(32)); @@ -196,13 +196,13 @@ public class VM { break; } program.spendGas(gasCost, op.name()); - + // Avoid overflows if(newMemSize.compareTo(MAX_GAS) == 1) throw program.new OutOfGasException(); // memory gas calc - long memoryUsage = (newMemSize.longValue() + 31) / 32 * 32; + long memoryUsage = (newMemSize.longValue() + 31) / 32 * 32; if (memoryUsage > oldMemSize) { memWords = (memoryUsage - oldMemSize) / 32; long memGas = GasCost.MEMORY * memWords; @@ -219,7 +219,7 @@ public class VM { // Log debugging line for VM if(program.getNumber().intValue() == CONFIG.dumpBlock()) this.dumpLine(op, gasBefore, gasCost+callGas, memWords, program); - + // Execute operation switch (op) { /** @@ -443,7 +443,7 @@ public class VM { /** * Bitwise Logic Operations */ - case AND:{ + case AND:{ DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -454,7 +454,7 @@ public class VM { program.stackPush(word1); program.step(); } break; - case OR: { + case OR: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -465,7 +465,7 @@ public class VM { program.stackPush(word1); program.step(); } break; - case XOR: { + case XOR: { DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); @@ -476,7 +476,7 @@ public class VM { program.stackPush(word1); program.step(); } break; - case BYTE:{ + case BYTE:{ DataWord word1 = program.stackPop(); DataWord word2 = program.stackPop(); DataWord result = null; @@ -515,7 +515,7 @@ public class VM { /** * SHA3 */ - case SHA3:{ + case SHA3:{ DataWord memOffsetData = program.stackPop(); DataWord lengthData = program.stackPop(); ByteBuffer buffer = program.memoryChunk(memOffsetData, lengthData); @@ -581,7 +581,7 @@ public class VM { program.stackPush(callValue); program.step(); } break; - case CALLDATALOAD:{ + case CALLDATALOAD:{ DataWord dataOffs = program.stackPop(); DataWord value = program.getDataValue(dataOffs); @@ -600,11 +600,11 @@ public class VM { program.stackPush(dataSize); program.step(); } break; - case CALLDATACOPY:{ + case CALLDATACOPY:{ DataWord memOffsetData = program.stackPop(); DataWord dataOffsetData = program.stackPop(); DataWord lengthData = program.stackPop(); - + byte[] msgData = program.getDataCopy(dataOffsetData, lengthData); if (logger.isInfoEnabled()) @@ -614,7 +614,7 @@ public class VM { program.step(); } break; case CODESIZE: case EXTCODESIZE: { - + int length; if (op == OpCode.CODESIZE) length = program.getCode().length; @@ -629,7 +629,7 @@ public class VM { program.stackPush(codeLength); program.step(); - } break; + } break; case CODECOPY: case EXTCODECOPY: { byte[] fullCode = ByteUtil.EMPTY_BYTE_ARRAY; @@ -733,19 +733,19 @@ public class VM { program.step(); } break; case DUP1: case DUP2: case DUP3: case DUP4: - case DUP5: case DUP6: case DUP7: case DUP8: - case DUP9: case DUP10: case DUP11: case DUP12: + case DUP5: case DUP6: case DUP7: case DUP8: + case DUP9: case DUP10: case DUP11: case DUP12: case DUP13: case DUP14: case DUP15: case DUP16:{ int n = op.val() - OpCode.DUP1.val() + 1; DataWord word_1 = stack.get(stack.size() - n); program.stackPush(word_1.clone()); program.step(); - + } break; case SWAP1: case SWAP2: case SWAP3: case SWAP4: - case SWAP5: case SWAP6: case SWAP7: case SWAP8: - case SWAP9: case SWAP10: case SWAP11: case SWAP12: + case SWAP5: case SWAP6: case SWAP7: case SWAP8: + case SWAP9: case SWAP10: case SWAP11: case SWAP12: case SWAP13: case SWAP14: case SWAP15: case SWAP16:{ int n = op.val() - OpCode.SWAP1.val() + 2; @@ -838,7 +838,7 @@ public class VM { if (nextPC != 0 && program.getOp(nextPC) != OpCode.JUMPDEST.val()) throw program.new BadJumpDestinationException(); } - + if (logger.isInfoEnabled()) hint = "~> " + nextPC; @@ -848,7 +848,7 @@ public class VM { 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()) { @@ -866,7 +866,7 @@ public class VM { } else { program.step(); } - + } break; case PC:{ int pc = program.getPC(); @@ -925,7 +925,7 @@ public class VM { String.format("%-12s", op.name()), program.getGas().value(), program.invokeData.getCallDeep(), hint); - + program.createContract(value, inOffset, inSize); program.step(); @@ -940,9 +940,9 @@ public class VM { DataWord outDataOffs = program.stackPop(); DataWord outDataSize = program.stackPop(); - + if (logger.isInfoEnabled()) { - hint = "addr: " + Hex.toHexString(codeAddress.getLast20Bytes()) + hint = "addr: " + Hex.toHexString(codeAddress.getLast20Bytes()) + " gas: " + gas.shortHex() + " inOff: " + inDataOffs.shortHex() + " inSize: " + inDataSize.shortHex(); @@ -951,7 +951,7 @@ public class VM { program.getGas().value(), program.invokeData.getCallDeep(), hint); } - + MessageCall msg = new MessageCall( op.equals(CALL) ? MsgType.CALL : MsgType.STATELESS, gas, codeAddress, value, inDataOffs, inDataSize, @@ -978,24 +978,24 @@ public class VM { case SUICIDE:{ DataWord address = program.stackPop(); program.suicide(address); - + if (logger.isInfoEnabled()) hint = "address: " + Hex.toHexString(program.getOwnerAddress().getLast20Bytes()); - + program.stop(); } break; default: break; } - + program.setPreviouslyExecutedOp(op.val()); - + if (logger.isInfoEnabled() && !op.equals(CALL) && !op.equals(CREATE)) logger.info(logString, stepBefore, String.format("%-12s", op.name()), program.getGas().longValue(), program.invokeData.getCallDeep(), hint); - + vmCounter++; } catch (RuntimeException e) { logger.warn("VM halted: [{}]", e.toString()); @@ -1022,7 +1022,7 @@ public class VM { program.spendGas(GasCost.TX_NO_ZERO_DATA * nonZeroesVals, "DATA"); program.spendGas(GasCost.TX_ZERO_DATA * zeroVals, "DATA"); } - + while(!program.isStopped()) this.step(program); @@ -1034,7 +1034,7 @@ public class VM { /** * Utility to calculate new total memory size needed for an operation. *
      Basically just offset + size, unless size is 0, in which case the result is also 0. - * + * * @param offset starting position of the memory * @param size number of bytes needed * @return offset + size, unless size is 0. In that case memNeeded is also 0. @@ -1044,12 +1044,12 @@ public class VM { return BigInteger.ZERO; return offset.value().add(size.value()); } - + /* * Dumping the VM state at the current operation in various styles * - standard Not Yet Implemented * - standard+ (owner address, program counter, operation, gas left) - * - pretty (stack, memory, storage, level, contract, + * - pretty (stack, memory, storage, level, contract, * vmCounter, internalSteps, operation gasBefore, gasCost, memWords) */ @@ -1057,12 +1057,12 @@ public class VM { if(CONFIG.dumpStyle().equals("standard+")) { switch (op) { case STOP: case RETURN: case SUICIDE: - + ContractDetails details = program.getResult().getRepository() .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()), @@ -1086,25 +1086,25 @@ public class VM { String memoryString = program.memoryToString(); if(!"".equals(memoryString)) dumpLogger.trace("{}", memoryString); - + dumpLogger.trace(" STORAGE"); ContractDetails details = program.getResult().getRepository() .getContractDetails(program.getOwnerAddress().getLast20Bytes()); List storageKeys = new ArrayList<>(details.getStorage().keySet()); Collections.sort((List) storageKeys); - + for (DataWord key : storageKeys) { dumpLogger.trace("{}: {}", key.shortHex(), details.getStorage().get(key).shortHex()); } - + int level = program.invokeData.getCallDeep(); String contract = Hex.toHexString(program.getOwnerAddress().getLast20Bytes()); String internalSteps = String.format("%4s", Integer.toHexString(program.getPC())).replace(' ', '0').toUpperCase(); dumpLogger.trace("{} | {} | #{} | {} : {} | {} | -{} | {}x32", level, contract, vmCounter, internalSteps, op, - gasBefore, gasCost, memWords); + gasBefore, gasCost, memWords); } - } + } } \ No newline at end of file diff --git a/ethereumj-core/src/main/resources/system.properties b/ethereumj-core/src/main/resources/system.properties index c6d9d582..4f455f10 100644 --- a/ethereumj-core/src/main/resources/system.properties +++ b/ethereumj-core/src/main/resources/system.properties @@ -42,7 +42,7 @@ peer.connection.timeout = 2 transaction.approve.timeout = 15 # the parameter specifies how much -# time we will wait for a message +# time we will wait for a message # to come before closing the channel peer.channel.read.timeout = 30 @@ -52,8 +52,8 @@ peer.channel.read.timeout = 30 samples.dir = samples # everytime the application starts -# the existing database will be -# destroyed and all the data will be +# the existing database will be +# destroyed and all the data will be # downloaded from peers again database.reset = true 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 f49ed7db..182ee359 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/BlockTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/BlockTest.java @@ -77,7 +77,7 @@ public class BlockTest { + "9e262996493846a590c7011697dba07bb7680a256ede4034212b7a1ae6c7caea73190cb0" + "7dedb91a07b72f34074e76a00cd22d78d556175604407dc6109797f5c8d990d05f1b352e" + "10c71b3dd74bc70f8201f4c0"; - + String block_32 = "f8f8f8f4a00a312c2b0a8f125c60a3976b6e508e740e095eb59943988d9bbfb8" + "aa43922e31a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4" + "934794e559de5527492bcb42ec68d07df0742a98ec3f1ea050188ab86bdf164ac90eb283" @@ -104,7 +104,7 @@ public class BlockTest { assertEquals(Hex.toHexString(genesis.getParentHash()), Hex.toHexString(genesisFromRLP.getParentHash())); assertEquals(Hex.toHexString(genesis.getStateRoot()), Hex.toHexString(genesisFromRLP.getStateRoot())); } - + @Test public void testGenesisFromNew() { Block genesis = Genesis.getInstance(); @@ -115,7 +115,7 @@ public class BlockTest { assertEquals(PoC7_GENESIS_HEX_HASH, Hex.toHexString(genesis.getHash())); assertEquals(PoC7_GENESIS_HEX_RLP_ENCODED, Hex.toHexString(genesis.getEncoded())); } - + @Test /* block without transactions - block#32 in PoC5 cpp-chain */ public void testEmptyBlock() { byte[] payload = Hex.decode(block_32); @@ -137,7 +137,7 @@ public class BlockTest { Block block = new Block(payload); logger.info(block.toString()); } - + @Test public void testCalcDifficulty() { @@ -157,7 +157,7 @@ public class BlockTest { logger.info("Block#1 calculated difficulty: [{}] ", calcDifficulty.toString()); assertEquals(actualDifficulty, calcDifficulty); } - + @Test public void testCalcGasLimit() { BlockchainImpl blockchain = (BlockchainImpl)worldManager.getBlockchain(); @@ -240,14 +240,14 @@ public class BlockTest { // TODO fail("Not yet implemented"); } - + @Test @Ignore public void testUncleInvalidGenerationGap() { // TODO fail("Not yet implemented"); } - + @Test @Ignore public void testUncleInvalidParentGenerationGap() { 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 b57566fb..cb8002fe 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/MinerTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/MinerTest.java @@ -19,30 +19,30 @@ public class MinerTest { // Example block#32 from Poc5 chain - rlpEncoded without nonce private String rlpWithoutNonce = "f894f890a00a312c2b0a8f125c60a3976b6e508e740e095eb59943988d9bbfb8" + "aa43922e31a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794e559de5527492bcb42ec68d07df0742a98ec3f1ea050188ab86bdf164ac90eb2835a04a8930aae5393c3a2ef1166fb95028f9456b880833ee248208609184e72a000830eca0080845387fd2080c0c0"; - + @Test @Ignore public void testMine() { boolean miningTestEnabled = false; - + if(miningTestEnabled) { Block block = createBlock(null); assertEquals(rlpWithoutNonce, Hex.toHexString(block.getEncodedWithoutNonce())); System.out.println("Searching for nonce of following block: \n" + block.toString()); - + Miner miner = new Miner(); boolean mined = miner.mine(block, block.getDifficulty()); assertTrue(mined); boolean valid = block.validateNonce(); assertTrue(valid); - + // expectedHash is the actual hash from block#32 in PoC5 chain based on nonce below String expectedHash = "ce7201f6cc5eb1a6f35c7dda8acda111647a0f8a5bf0518e46579b03e29fe14b"; assertEquals(expectedHash, Hex.toHexString(block.getHash())); // expectedNonce is the actual nonce from block#32 in Poc5 chain String expectedNonce = "0000000000000000000000000000000000000000000000001f52ebb192c4ea97"; // from Poc5 chain - // Actual is "000000000000000000000000000000000000000000000000000000000098cc15" + // Actual is "000000000000000000000000000000000000000000000000000000000098cc15" // but that might also be a valid nonce in compliance with PoW(H!n, n) < (2^256 / difficulty) assertEquals(expectedNonce, Hex.toHexString(block.getNonce())); } 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 0c8cc8aa..495f2251 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/StateTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/StateTest.java @@ -70,7 +70,7 @@ public class StateTest { byte[] minerAddress = Hex.decode("4c5f4d519dff3c16f0d54b6866e256fbbbc1a600"); AccountState account_3 = new AccountState(BigInteger.ZERO, new BigInteger("1506260000000000000")); trie.update(minerAddress, account_3.getEncoded()); - + assertEquals(expected, Hex.toHexString(trie.getRootHash())); @@ -116,7 +116,7 @@ public class StateTest { Trie trie = new TrieImpl(new MockDB()); for (String address : Genesis.getPremine()) { AccountState acct = new AccountState(BigInteger.ZERO, BigInteger.valueOf(2).pow(200)); - trie.update(Hex.decode(address), acct.getEncoded()); + trie.update(Hex.decode(address), acct.getEncoded()); } return trie; } 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 c70e9db4..f20301f3 100644 --- a/ethereumj-core/src/test/java/test/ethereum/core/TransactionTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/core/TransactionTest.java @@ -109,7 +109,7 @@ public class TransactionTest { ECKey ecKey = ECKey.fromPrivate(HashUtil.sha3("cat".getBytes())); byte[] senderPrivKey = HashUtil.sha3("cow".getBytes()); - + byte[] nonce = { 0x01 }; byte[] gasPrice = Hex.decode("09184e72a000"); byte[] gasLimit = Hex.decode("4255"); @@ -152,14 +152,14 @@ public class TransactionTest { byte[] testValue = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(10000000000000000L)); byte[] testData = Hex.decode(""); byte[] testInit = Hex.decode(""); - + @Test public void testTransactionFromSignedRLP() throws Exception { Transaction txSigned = new Transaction(Hex.decode(RLP_ENCODED_SIGNED_TX)); - + assertEquals(HASH_TX, Hex.toHexString(txSigned.getHash())); assertEquals(RLP_ENCODED_SIGNED_TX, Hex.toHexString(txSigned.getEncoded())); - + assertEquals(BigInteger.ZERO, new BigInteger(1, txSigned.getNonce())); assertEquals(new BigInteger(1, testGasPrice), new BigInteger(1, txSigned.getGasPrice())); assertEquals(new BigInteger(1, testGasLimit), new BigInteger(1, txSigned.getGasLimit())); @@ -170,16 +170,16 @@ public class TransactionTest { assertEquals("eab47c1a49bf2fe5d40e01d313900e19ca485867d462fe06e139e3a536c6d4f4", Hex.toHexString(BigIntegers.asUnsignedByteArray(txSigned.getSignature().r))); assertEquals("14a569d327dcda4b29f74f93c0e9729d2f49ad726e703f9cd90dbb0fbf6649f1", Hex.toHexString(BigIntegers.asUnsignedByteArray(txSigned.getSignature().s))); } - + @Test public void testTransactionFromUnsignedRLP() throws Exception { Transaction txUnsigned = new Transaction(Hex.decode(RLP_ENCODED_UNSIGNED_TX)); - + assertEquals(HASH_TX, Hex.toHexString(txUnsigned.getHash())); assertEquals(RLP_ENCODED_UNSIGNED_TX, Hex.toHexString(txUnsigned.getEncoded())); txUnsigned.sign(Hex.decode(KEY)); - assertEquals(RLP_ENCODED_SIGNED_TX, Hex.toHexString(txUnsigned.getEncoded())); - + assertEquals(RLP_ENCODED_SIGNED_TX, Hex.toHexString(txUnsigned.getEncoded())); + assertEquals(BigInteger.ZERO, new BigInteger(1, txUnsigned.getNonce())); assertEquals(new BigInteger(1, testGasPrice), new BigInteger(1, txUnsigned.getGasPrice())); assertEquals(new BigInteger(1, testGasLimit), new BigInteger(1, txUnsigned.getGasLimit())); @@ -190,11 +190,11 @@ public class TransactionTest { assertEquals("eab47c1a49bf2fe5d40e01d313900e19ca485867d462fe06e139e3a536c6d4f4", Hex.toHexString(BigIntegers.asUnsignedByteArray(txUnsigned.getSignature().r))); assertEquals("14a569d327dcda4b29f74f93c0e9729d2f49ad726e703f9cd90dbb0fbf6649f1", Hex.toHexString(BigIntegers.asUnsignedByteArray(txUnsigned.getSignature().s))); } - + @Test public void testTransactionFromNew1() throws MissingPrivateKeyException { Transaction txNew = new Transaction(testNonce, testGasPrice, testGasLimit, testReceiveAddress, testValue, testData); - + assertEquals("", Hex.toHexString(txNew.getNonce())); assertEquals(new BigInteger(1, testGasPrice), new BigInteger(1, txNew.getGasPrice())); assertEquals(new BigInteger(1, testGasLimit), new BigInteger(1, txNew.getGasLimit())); @@ -202,35 +202,35 @@ public class TransactionTest { assertEquals(new BigInteger(1, testValue), new BigInteger(1, txNew.getValue())); assertEquals("", Hex.toHexString(txNew.getData())); assertNull(txNew.getSignature()); - + assertEquals(RLP_ENCODED_RAW_TX, Hex.toHexString(txNew.getEncodedRaw())); assertEquals(HASH_TX, Hex.toHexString(txNew.getHash())); assertEquals(RLP_ENCODED_UNSIGNED_TX, Hex.toHexString(txNew.getEncoded())); txNew.sign(Hex.decode(KEY)); - assertEquals(RLP_ENCODED_SIGNED_TX, Hex.toHexString(txNew.getEncoded())); - + assertEquals(RLP_ENCODED_SIGNED_TX, Hex.toHexString(txNew.getEncoded())); + assertEquals(27, txNew.getSignature().v); assertEquals("eab47c1a49bf2fe5d40e01d313900e19ca485867d462fe06e139e3a536c6d4f4", Hex.toHexString(BigIntegers.asUnsignedByteArray(txNew.getSignature().r))); assertEquals("14a569d327dcda4b29f74f93c0e9729d2f49ad726e703f9cd90dbb0fbf6649f1", Hex.toHexString(BigIntegers.asUnsignedByteArray(txNew.getSignature().s))); } - + @Test public void testTransactionFromNew2() throws MissingPrivateKeyException { byte[] privKeyBytes = Hex.decode("c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4"); - + String RLP_TX_UNSIGNED = "eb8085e8d4a510008227109413978aee95f38490e9769c39b2773ed763d9cd5f872386f26fc1000080808080"; 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]; - + Transaction tx = new Transaction(nonce, gasPrice, gas, recieveAddress, value, data); - + // Testing unsigned String encodedUnsigned = Hex.toHexString(tx.getEncoded()); assertEquals(RLP_TX_UNSIGNED, encodedUnsigned); @@ -238,7 +238,7 @@ public class TransactionTest { // Testing signed tx.sign(privKeyBytes); - String encodedSigned = Hex.toHexString(tx.getEncoded()); + String encodedSigned = Hex.toHexString(tx.getEncoded()); assertEquals(RLP_TX_SIGNED, encodedSigned); assertEquals(HASH_TX_UNSIGNED, Hex.toHexString(tx.getHash())); } 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 9339819d..c010b176 100644 --- a/ethereumj-core/src/test/java/test/ethereum/crypto/ECKeyTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/crypto/ECKeyTest.java @@ -28,19 +28,19 @@ import com.google.common.util.concurrent.MoreExecutors; public class ECKeyTest { private static final Logger log = LoggerFactory.getLogger(ECKeyTest.class); - + private String privString = "3ecb44df2159c26e0f995712d4f39b6f6e499b40749b1cf1246c37f9516cb6a4"; private BigInteger privateKey = new BigInteger(Hex.decode(privString)); - + private String pubString = "0497466f2b32bc3bb76d4741ae51cd1d8578b48d3f1e68da206d47321aec267ce78549b514e4453d74ef11b0cd5e4e4c364effddac8b51bcfc8de80682f952896f"; private String compressedPubString = "0397466f2b32bc3bb76d4741ae51cd1d8578b48d3f1e68da206d47321aec267ce7"; private byte[] pubKey = Hex.decode(pubString); private byte[] compressedPubKey = Hex.decode(compressedPubString); private String address = "8a40bfaa73256b60764c1bf40675a99083efb075"; - + private String exampleMessage = new String("This is an example of a signed message."); private String sigBase64 = "HD5AsBr4wuH6UU9tXuSJhUvgfGayfwoY0cKT03sFUjnpQsupHznd/3mCIRfLuNHlRCVGdAyHecdyM8IVZMtc1I8="; - + @Test public void testHashCode() { Assert.assertEquals(1866897155, ECKey.fromPrivate(privateKey).hashCode()); @@ -84,7 +84,7 @@ public class ECKeyTest { byte[] pubFromPriv = ECKey.publicKeyFromPrivate(privateKey, false); assertArrayEquals(pubKey, pubFromPriv); } - + @Test public void testPublicKeyFromPrivateCompressed() { byte[] pubFromPriv = ECKey.publicKeyFromPrivate(privateKey, true); @@ -105,7 +105,7 @@ public class ECKeyTest { @Test public void testEthereumSign() throws IOException { - // TODO: Understand why key must be decompressed for this to work + // TODO: Understand why key must be decompressed for this to work ECKey key = ECKey.fromPrivate(privateKey).decompress(); System.out.println("Secret\t: " + Hex.toHexString(key.getPrivKeyBytes())); System.out.println("Pubkey\t: " + Hex.toHexString(key.getPubKey())); @@ -116,7 +116,7 @@ public class ECKeyTest { System.out.println("Signtr\t: " + output + " (Base64, length: " + output.length() + ")"); assertEquals(sigBase64, output); } - + @Test public void testVerifySignature1() { ECKey key = ECKey.fromPublicOnly(pubKey); @@ -125,7 +125,7 @@ public class ECKeyTest { ECDSASignature sig = ECDSASignature.fromComponents(r.toByteArray(), s.toByteArray(), (byte) 28); key.verify(HashUtil.sha3(exampleMessage.getBytes()), sig); } - + @Test public void testVerifySignature2() { BigInteger r = new BigInteger("c52c114d4f5a3ba904a9b3036e5e118fe0dbb987fe3955da20f2cd8f6c21ab9c", 16); @@ -158,7 +158,7 @@ public class ECKeyTest { // todo: add test assertion when the sign/verify part actually works. } - + @Test public void testSValue() throws Exception { // Check that we never generate an S value that is larger than half the curve order. This avoids a malleability @@ -184,7 +184,7 @@ public class ECKeyTest { assertEquals(sigs.get(0), duplicate); assertEquals(sigs.get(0).hashCode(), duplicate.hashCode()); } - + @Test public void testSignVerify() { ECKey key = ECKey.fromPrivate(privateKey); @@ -192,7 +192,7 @@ public class ECKeyTest { ECDSASignature output = key.doSign(message.getBytes()); assertTrue(key.verify(message.getBytes(), output)); } - + @Test public void testIsPubKeyCanonicalCorect() { // Test correct prefix 4, right length 65 @@ -205,7 +205,7 @@ public class ECKeyTest { byte[] canonicalPubkey3 = new byte[33]; canonicalPubkey3[0] = 0x03; assertTrue(ECKey.isPubKeyCanonical(canonicalPubkey3)); } - + @Test public void testIsPubKeyCanonicalWrongLength() { // Test correct prefix 4, but wrong length !65 @@ -218,7 +218,7 @@ public class ECKeyTest { byte[] nonCanonicalPubkey3 = new byte[32]; nonCanonicalPubkey3[0] = 0x03; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey3)); } - + @Test public void testIsPubKeyCanonicalWrongPrefix() { // Test wrong prefix 4, right length 65 @@ -231,7 +231,7 @@ public class ECKeyTest { byte[] nonCanonicalPubkey6 = new byte[33]; assertFalse(ECKey.isPubKeyCanonical(nonCanonicalPubkey6)); } - + @Test public void keyRecovery() throws Exception { ECKey key = new ECKey(); @@ -250,7 +250,7 @@ public class ECKeyTest { } assertTrue(found); } - + @Test public void testSignedMessageToKey() throws SignatureException { byte[] messageHash = HashUtil.sha3(exampleMessage.getBytes()); @@ -258,7 +258,7 @@ public class ECKeyTest { assertNotNull(key); assertArrayEquals(pubKey, key.getPubKey()); } - + @Test public void testGetPrivKeyBytes() { ECKey key = new ECKey(); @@ -271,9 +271,9 @@ public class ECKeyTest { ECKey key0 = new ECKey(); ECKey key1 = ECKey.fromPrivate(privateKey); ECKey key2 = ECKey.fromPrivate(privateKey); - + assertFalse(key0.equals(key1)); assertTrue(key1.equals(key1)); assertTrue(key1.equals(key2)); - } + } } 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 764444ec..57482782 100644 --- a/ethereumj-core/src/test/java/test/ethereum/db/ByteArrayWrapperTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/db/ByteArrayWrapperTest.java @@ -19,10 +19,10 @@ public class ByteArrayWrapperTest { static ByteArrayWrapper wrapper2; static ByteArrayWrapper wrapper3; static ByteArrayWrapper wrapper4; - + @BeforeClass public static void loadByteArrays() { - + String block = "f9072df8d3a077ef4fdaf389dca53236bcf7f72698e154eab2828f86fbc4fc6c" + "d9225d285c89a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0" + "a142fd40d493479476f5eabe4b342ee56b8ceba6ab2a770c3e2198e7a0faa0ca" @@ -81,18 +81,18 @@ public class ByteArrayWrapperTest { + "2ba37af8e83c3741225da066ae0ec1217b0ca698a5369d4881e1c4cbde56af99" + "31ebf9281580a23b659c08a051f947cb2315d0259f55848c630caa10cd91d6e4" + "4ff8bad7758c65b25e2191308227d2c0"; - + byte[] test1 = Hex.decode(block); byte[] test2 = Hex.decode(block); byte[] test3 = Hex.decode("4ff8bad7758c65b25e2191308227d2c0"); byte[] test4 = Hex.decode(""); - + wrapper1 = new ByteArrayWrapper(test1); wrapper2 = new ByteArrayWrapper(test2); wrapper3 = new ByteArrayWrapper(test3); wrapper4 = new ByteArrayWrapper(test4); } - + @Test public void testEqualsObject() { assertTrue(wrapper1.equals(wrapper2)); @@ -109,11 +109,11 @@ public class ByteArrayWrapperTest { assertTrue(wrapper1.compareTo(wrapper4) > 1); assertTrue(wrapper2.compareTo(wrapper3) > 1); } - + @Test public void testEqualsPerformance() { boolean testEnabled = false; - + if(testEnabled) { final int ITERATIONS = 10000000; long start1 = System.currentTimeMillis(); @@ -125,18 +125,18 @@ public class ByteArrayWrapperTest { wrapper2.getData()); } System.out.println(System.currentTimeMillis() - start1 + "ms"); - + long start2 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { Arrays.equals(wrapper1.getData(), wrapper2.getData()); } System.out.println(System.currentTimeMillis() - start2 + "ms"); - + long start3 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { FastByteComparisons.compareTo(wrapper1.getData(), 0, wrapper1.getData().length, wrapper2.getData(), 0, wrapper1.getData().length); } System.out.println(System.currentTimeMillis() - start3 + "ms"); } - } + } } 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 0c7b5c9f..2f6fad14 100644 --- a/ethereumj-core/src/test/java/test/ethereum/db/TrackDatabaseTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/db/TrackDatabaseTest.java @@ -22,7 +22,7 @@ import org.spongycastle.util.encoders.Hex; * Created on: 11/06/2014 14:54 */ public class TrackDatabaseTest { - + @Test public void test1() { @@ -50,7 +50,7 @@ public class TrackDatabaseTest { db1.close(); } - + @AfterClass public static void destroyDB() { try { 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 43712e22..776c514a 100644 --- a/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubJSONTestSuite.java +++ b/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubJSONTestSuite.java @@ -18,9 +18,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Test file specific for tests maintained in the GitHub repository + * Test file specific for tests maintained in the GitHub repository * by the Ethereum DEV team.
      - * + * * @see https://github.com/ethereum/tests/ */ @RunWith(Suite.class) @@ -31,7 +31,7 @@ public class GitHubJSONTestSuite { private static Logger logger = LoggerFactory.getLogger("TCK-Test"); - + protected static void runGitHubJsonTest(String json) throws ParseException { Assume.assumeFalse("Online test is not available", json.equals("")); @@ -44,7 +44,7 @@ public class GitHubJSONTestSuite { while (testIterator.hasNext()){ TestCase testCase = testIterator.next(); - + TestRunner runner = new TestRunner(); List result = runner.runTestCase(testCase); Assert.assertTrue(result.isEmpty()); 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 a519b9a9..9b40e3e4 100644 --- a/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubStateTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubStateTest.java @@ -97,6 +97,6 @@ public class GitHubStateTest { - + } diff --git a/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubVMTest.java b/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubVMTest.java index e7649c04..17ee1d4c 100644 --- a/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubVMTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/jsontestsuite/GitHubVMTest.java @@ -16,56 +16,56 @@ public class GitHubVMTest { String json = JSONReader.loadJSON("VMTests/vmArithmeticTest.json"); GitHubJSONTestSuite.runGitHubJsonTest(json); } - + @Test // testing full suite public void testBitwiseLogicOperationFromGitHub() throws ParseException { String json = JSONReader.loadJSON("VMTests/vmBitwiseLogicOperationTest.json"); GitHubJSONTestSuite.runGitHubJsonTest(json); } - + @Test // testing full suite public void testBlockInfoFromGitHub() throws ParseException { String json = JSONReader.loadJSON("VMTests/vmBlockInfoTest.json"); GitHubJSONTestSuite.runGitHubJsonTest(json); } - + @Test // testing full suite public void testEnvironmentalInfoFromGitHub() throws ParseException { String json = JSONReader.loadJSON("VMTests/vmEnvironmentalInfoTest.json"); GitHubJSONTestSuite.runGitHubJsonTest(json); } - + @Test // testing full suite public void testIOandFlowOperationsFromGitHub() throws ParseException { String json = JSONReader.loadJSON("VMTests/vmIOandFlowOperationsTest.json"); GitHubJSONTestSuite.runGitHubJsonTest(json); } - + @Test // testing full suite public void testPushDupSwapFromGitHub() throws ParseException { String json = JSONReader.loadJSON("VMTests/vmPushDupSwapTest.json"); GitHubJSONTestSuite.runGitHubJsonTest(json); } - + @Test // testing full suite public void testShaFromGitHub() throws ParseException { String json = JSONReader.loadJSON("VMTests/vmSha3Test.json"); GitHubJSONTestSuite.runGitHubJsonTest(json); } - + @Test // testing full suite public void testVMGitHub() throws ParseException { String json = JSONReader.loadJSON("VMTests/vmtests.json"); GitHubJSONTestSuite.runGitHubJsonTest(json); } - + @Test // testing full suite public void testVMLogGitHub() throws ParseException { 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 8dfcfa4f..aa9f0beb 100644 --- a/ethereumj-core/src/test/java/test/ethereum/mine/MinerThread.java +++ b/ethereumj-core/src/test/java/test/ethereum/mine/MinerThread.java @@ -13,7 +13,7 @@ import java.util.ArrayList; import java.util.List; /** - * @author Roman Mandeleil + * @author Roman Mandeleil * Created on: 22/05/2014 09:26 */ public class MinerThread implements Runnable { 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 a1c0cc18..e71f4314 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/BlockHashesMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/BlockHashesMessageTest.java @@ -14,22 +14,22 @@ import java.util.Arrays; public class BlockHashesMessageTest { /* BLOCK_HASHES_MESSAGE */ - + @Test /* BlockHashesMessage 1 from network */ public void test_1() { - + String blockHashesMessageRaw = "f9108114a04ee6424d776b3f59affc20bc2de59e67f36e22cc07897ff8df152242c921716ba07d2fe4df0dbbc9011da2b3bf177f0c6b7e71a11c509035c5d751efa5cf9b4817a0e32d9ac70a95a5084447143cba713ceae2cae614e79817bf76fc081480509912a07167d51e20b6bdd1457101b81300519f9eeb741008ba45ff9682912b96cc3231a05dc40186092d08fdb83e938774b318ce598ed3b44f2b0382cd8991d912135a08a08b7036a775a190094c4eb994a0e7a2f89ffa59d1f3461bd1de104f37aa0098eca0b0301705ba576e32d9e47fc5983fa49ba5e8f00e3e2d0a7e1b281a9625445ff5a033124a8da5113edff6afe4fb5efece3741895a7fba3d1c167586f4c3374f1d78a03c1aa5542d3fdafbd7b03c2085bcc940343f26b9711f8a215c4ea3f84364472fa0c959599f529ac1f085c4f9aadc0a17aad1c61311b0ad6b4e3f4a12eb3f93ad76a0eb26c71de8706185a717e21753b6e47e2d4b34e00e034f64b6c76f2de3af7f75a0e679e8b274cca37c2e449b993eb2228d062a78b4406f9323fa48fa182de640f3a0df26cd027609ad25739a041b3d9d81705b4fa73c86f6df04b836984e8b4c8489a0cfaad0dba4a266e9ccbf7474079647a4ac659d93f071091c90d454c1af48ae25a06f5232f5058b5b70fcd28070dfe716a6327b899d639cff2106b9907978c6dc7ca0ba3266b0a3877b4a81e8f6dd6c36aeb587a1a14acd10976d3ed6f686a35d8c13a08014d1ff07221b83a1996e6b80546310d430589f7cd6a9137e16f14c3a49e855a0dfce9bc6e8947b440f03a86f37ae639a4446ed27d8f56f9c7c1b00e9fc120aa2a03cfd099c3e1c974284477f6366b242372833ff6f618b4fd94d9cefb9912eaee4a085c4ac37b8a8d466dc66870838ccdec34a5df6f6548bf6c06cbb645f6980491ea0f3085b2449501113981af5274706a9dfea891fb28a6228375ba2cd28970d37fda0a63e45fcc5050d52a0eaee0a0c118e1b94c8ee6f2312e01f143f27fd360aee67a0c51c71816bf7c79475a7ebc1f1dcd6137e0950c4db57d7b947372751c114b6bea05e66b8849b5a2e90d98663c0428ca7c7483fbe8bcd1ae77f9dfd91fccb7a66ffa008a1e472e019b8f5b3b899ad1185c0fe953ee336ae3fe807cceca5e47728bcdda04700e66f3a96965ab08a7760f0ac9f15f4a282cfc09a50dce09e573e27054a3aa0c820e85e4b5bbf8f19f44e00b9ac43bbc2148f599b48c1257088616cf1909d50a0201bd78f79fded601eaa4b7484b079bf5e6214ee25b633988008ffbc2ff6fe86a033cb48d0197a0dfddd1ad4623df688784bbba4ada03a80ac560cf4f92d3eaf7fa053f100fa3088a48c17dba35efcf96a4c02a15a136d16c9b32bafff5771e969f2a0ab3db92acb1f5552c90d65efb93ba505d7390db6cfe2ddd7768282931b9d0e64a0e6cec0ca20da89288461e69d6e5eaaf466cc15feab145206a0f9e19783aab0b5a0c6bff7771c8d4d59dfe39abbc980b0e21fc68295961a0804139f10ce827e7f2da02bb1ce267a1fb3757daeebfc8ecac8ad417b66fa6a5211d3fc1cf2f6f401a048a06393a130996fce7024030531869d66ad4ed0264bc6efc34ebc246e9b739baf14a013ca792bb72a8f6f641af3d9c7ba4739181b6fbffecea9319fa3afe9185fe996a03330c6e385b275391ed715867746c8fb9eb7b6b939e9a2ca561593e54148618ba00accdcad654f4a9fdefd7a69cabc47e02a60840b93890a70b4e378189933264aa0a0e507ee34150a0cb777254a6fb5fc658d19f03fe00be84d6c2fb92eff1bf008a0319e9bc452c23f7dae6368729a6f6ce7c557a3f4c8c031902a84d07a0ad7279aa0b46e49cbe43a01deef74bb03727987822678f840f665251c4fe060c4d43cef99a0c6c820d402c873b50adc53582195f97ba4dcea02c4aac1f37680c1c5b786d3a1a070740ab0275db1cb4f06d1e7320984b3ad708dfbd999879e5bde12cda5641583a0b537199eabbf6aaa120ab4c3cbeed02311f2e2e7158b5f3a239147522d1c001aa0bdeaf137c59ee9985dcbae18410a223bd0cc061659ae76c85bff34c3831f4181a079a4d2a87b47f848524378abc99dd6b205ee19af316c8f3769f6ad870745845fa037dc76bdad66f0fb907b3244eb64c4193e3d84b4c81c0c2e006ad57866db0d48a071aaa649a631f724f95e71dd78dd97b69ab93d75082042944b76333c51bc6e85a0a22b3c6eb1b43fc1ffa79a6ff78255074cff4db7d3bbafae7ae13c3b493eeb5aa06426f3bc465d89db7fee576b1f97c97f13744dfa33561ece7e0d38bbcd34e9f0a0ff62c6aa7567b262f31fbcc794ac46bd96504ccb8f98451ea034b8aa434c6bcca06b942d48699b609829f1ecc89db076d59faec6664af3dc2b13da46d40daa9763a05f325608455045794b77a5fd8f2ed12e7cda40df2d8aeeec7e5a517b455a8157a0c054b8bd53545d78206de7fa0c8e206997d9c68f435fe06c3057f9545ba196f0a08ad94a4c53c397f3c63bffdcd790486c3f7588d155d6d86e0ff08907c7f7f682a0c3d9f991dac6c0e3ba032b6da7bc0cdc38c8c76e95a12c4f86326d09a2d69754a01b1cba8bdcbbbf02b9b876194713dfaf941f3f03bfc4a91746187e001edbb20ea0ec32df0dc1ce371c866d817f90497e620efb59b1baabe1e90f00e28fb57e1823a0d3a29747ed5cfed3467687eb63adc28bc646a5c66f610f55bb840c8e59f8b360a010bcf47b3c6c09b919db63b8e054458fad45f1dd8ca8cfda9759e5c53d90b0eba0075a78486d263b530834e88572a5e750658e263c1e3a3dc5801039101ece5ae9a0119b8487dc9ba0a2e95cb0dde90c26a70b48611baed1c9cca5ec73c161e8c98fa032c248078737a2f8542e70edf44854f87544b540a47c55292a0c718c57fa4578a0f38d4b93d2edc95ed526dc7f65d01bddbfb1e3e14f9a870bc3b23b164db62b24a030649acc70269c05316bfa3c20452ea21cff552c1e4da38e3fdde05371027660a000db5540f1ffd4d21aa351c511806e675cc3348604322c34e28970f9060e8d9fa06be5873726f8a76871141255c1332f4b1fb11906a5ab352ac1c8f262f2a0a817a0ae40366642d2f4d6b19e61978e84a27170648315bf93772bd9771f55abd61bbba0b8e6e8cb6008ae9a73a8d6b6d04e25d24e87b2f6f20a6714e59032550e37e213a0db0272777c2a5b49a89852bc5858bb531a7b37d08f72a4a5a9d109a40788d8c6a0d6fef3c812213467205f47f3edece2d74908e8cab599a5e42425520ad6b002e3a084856e32b9e8a0a4db75b4586ae492528f427fc814c2086340d942d24a1eb3bda0121bf2d712eb87605253775a4f93cd125e3c714388c74a4a5a321a43b8fe912aa0e13b4ddd63b6bd4abfff393463c62f298238d118c134328eee255b7fc191227ea01e278eab5967765720e5b791684a9dbe3d8d46e39c5dd615de92f02419a70fcda0a26ad0b4c36c77e619fe3100b9a44447c9d16a7db1780014cf6f409ee73145d7a0d113188b5bd282b9e9fd8e58df4431725ef85098db0bc845ed3a44132cc597efa0d303b816fbfcabe1c2eb6507ed886f6c35fa423d02ba0c5b38e268dafb38231aa017786974a83c2513e69451ae7a0bfed75f4fe09b194ae979a467e6f615bc08f1a07bde7299bbae3ff0178eae928f465070a88db0df33c4c3de53c681b8eaf17f1aa0d0c0e668f5bd6bd36b727688ba6212128390400ae3f00b42be3c2b587db24b75a0ee437f296d523f07de580979e598e522a05c0025ea8f79c7fbdbee0b679c3382a01cb65eaf5a15bd573d26fb4100208dd9389f87c1151bf46f77e6df8e3a113638a05c707c3a379ef1e2587dd0c60b252e8eb62992f0e6f3c2d7a964f0c6e9fbc3cda05ba3646ffacb6cf0cd648b4d471105291a217b23e118581f02ecd0b73fdb4691a0c102b0807c0f495eea1fa1000b9eedb2f692ab7e71c9dd47e83792e4153d3145a0ee15b8a5ef01c5fcfa73f29028b5310268302bcdf1a1a58a30d3027f375e08fda0d44965bf82d2c77e3e92d1c0e1091f87858c5e1b11b61db46feb57ebd7c046c5a04f34602a1e223e5e1325d3f55e0d8c10c0cacfdf490eb909c105876d62cb6912a0fbdc0438cd3cb503bff3f206cea3a02728ca7abd1b3316c5c1ed5cd59a79cc1ba00f628b7c8c50137b0c78ef962f6e6ee299b6600caa1dcd492c162041e2cfa893a0d9bb3e9b92d2246f00d2f28b544c9cd8c187d31d8a9f3d96a4368df575156d0ea0fa7159b9b87ea9943d12f4003e49c90b436a0654bb6ce6bcc979a7decc45ee1ca095052c3e80bedc1cb11aa0944fef5bcdc0e270fac53f8a416e7bad469e8cbbf6a0b83edf3de91030ee463552f8297d190b11068f5419d77c34e7e461f09443be35a0e4f4c4a3041e89f801e366aa6816e951d90d95ac87764fe1fe9bca9b224fb34da0796a235e7afb0160ed5a13a59649ac3ca5fda480a416741f8e9f6d6bf047d59aa041171c6698700a5f8519250d560053e4cc0696d9c878f3bc2aae47bd80918baea0c2918de602864702d9cb82ec306ff3167c687847caa0cabf707bb7691d9cd35da092c31980bd54614ce7b942d22c99200c2348b78d830ecc07775f4d72994df6b7a095f5cdbc3780f2214fc646c00cba5207c57c710ec01d3ab1c99b57d2985ae110a0b3cb73c4db8f9804456053c56ca19b0c7192a01e0b9df8d2438511fc36392be5a005e6f2ff464bbbac673aa2265b2e539e1de710cb5fa478ceda3f86572d4f22c2a0142bbc3c5165103b52b03d3ac7649d27f28f8d23244203f2dad6ac0f86c23288a06ee55fe32ec8b5832c099e83d802e24bc7b2d8255c9e4cdbcb28b190f06643eda0d119d6a03a7f77fd5af0804e1d0a1cd7e4b22b39b8554811fa014949db2791fca00fcd650300dc9383c6a3c4530e63cc29e28c8a773950faf2b886d805a1075ba3a0d4d65579b429665f8eece57164610cddde236e67d4a3a8e9ab518d19b4a5d6f4a07f3db2b8df96ff63907ac11dcca8f499bbb9a1e1ed021d13c6c29d1ef3337439a0ed254029ceb98dea0a11967a0dbf50b84d262f0397a7bcaac7c95fd52090af9fa0a879c624e761b93047c76db45ef4f2408075d5cd6190bd281b4efe1f034726a5a0a07e9452ebb9ef9f56e9e05d434ae452ee9972bc7f7ff9c729117608953b146fa0ee672fc517fb4c9a957ec3a8ded2a2fd89b80c398f393e29b1e98102e8f61053a0b61db41a25bbaa6acbb468b20a0085a74edcafefd8b0d78d8ee095387d0198efa0d612101516e4cdedbd21345b4caf48f96e82233f4f361bb3f96d77925fa667ada077dc1f4a8b062581425106878839c7e210abe2b38735bb9d7db8011204327d0ca0e152b9b0ab7499bee9bdfb14c3c3dc84072669506765959b3da1f6169e4ed458a0455408387e6c5b029b0d51f7d617a4d1dc4895fa6eda09455cc2ee62c08d907ea01fb1a00145067c01d2ac77f32edede63eb8b70a4308126dd505ce7b131dff013a064254a100bc90a6976fe0c41a91f1dc4a989a849b27299a88c3c327ed2b0bf96a08b13c687cb586af34da7b53329dd884fb6f903b2dd783cf6e72643ffb0331d6da011566138aa5f1ae4634bb3157557b57ac05d0c6eaa7f3f5e7cfaadfc77f34743a09aa82ceca9faba8fd1f3d00c4da529320e90dc141d70995cb52bfafdb92873d1a0ad3ec8c67e9a836420a3de77ade645f064ae1b642272014879e18ea6c56bbcfaa077f6a32b87b81d0ff453906c5098c0146190413cb0d3d4a505af2db3402df19ba0c99fb3ba58b9d24a7e07bcfe1a4de27e0563fbbf6d1c85b77f9f70c61e302f5ca03b5380620a07d1b4f0050a832a8865e58a8625df072c10bb6963a73fbc3fb649a05a29c29b6d492235af1d7978813502bea84bd1c79209374c50cd634e1fd501f7"; - + byte[] payload = Hex.decode(blockHashesMessageRaw); BlockHashesMessage blockHashesMessage = new BlockHashesMessage(payload); System.out.println(blockHashesMessage); - + assertEquals(EthMessageCodes.BLOCK_HASHES, blockHashesMessage.getCommand()); assertEquals(128, blockHashesMessage.getBlockHashes().size()); // TODO maybe also assert values for individual hashes assertEquals(null, blockHashesMessage.getAnswerMessage()); } - + @Test /* BlockHashesMessage 2 from new */ public void test_2() { List blockHashes = Arrays.asList( @@ -38,10 +38,10 @@ public class BlockHashesMessageTest { ); BlockHashesMessage blockHashesMessage = new BlockHashesMessage(blockHashes); System.out.println(blockHashesMessage); - + String expected = "f84304a04ee6424d776b3f59affc20bc2de59e67f36e22cc07897ff8df152242c921716ba07d2fe4df0dbbc9011da2b3bf177f0c6b7e71a11c509035c5d751efa5cf9b4817"; assertEquals(expected, Hex.toHexString(blockHashesMessage.getEncoded())); - + assertEquals(EthMessageCodes.BLOCK_HASHES, blockHashesMessage.getCommand()); assertEquals(2, blockHashesMessage.getBlockHashes().size()); // TODO maybe also assert values for individual hashes 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 2f07e645..01da5bc7 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/BlocksMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/BlocksMessageTest.java @@ -85,7 +85,7 @@ public class BlocksMessageTest { Hex.toHexString(block.getStateRoot())); } - + @Ignore @Test /* Block msg decode - found bug tool */ public void test_4() throws URISyntaxException, IOException { diff --git a/ethereumj-core/src/test/java/test/ethereum/net/DisconnectMessageTest.java b/ethereumj-core/src/test/java/test/ethereum/net/DisconnectMessageTest.java index 234b0b2b..90e76e5e 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/DisconnectMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/DisconnectMessageTest.java @@ -37,13 +37,13 @@ public class DisconnectMessageTest { @Test /* DisconnectMessage 2 - from constructor */ public void test_3() { - + DisconnectMessage disconnectMessage = new DisconnectMessage(ReasonCode.INCOMPATIBLE_NETWORK); System.out.println(disconnectMessage); String expected = "c20107"; assertEquals(expected, Hex.toHexString(disconnectMessage.getEncoded())); - + assertEquals(ReasonCode.INCOMPATIBLE_NETWORK, disconnectMessage.getReason()); } } diff --git a/ethereumj-core/src/test/java/test/ethereum/net/GetBlockHashesMessageTest.java b/ethereumj-core/src/test/java/test/ethereum/net/GetBlockHashesMessageTest.java index 234f1889..c52013b2 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/GetBlockHashesMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/GetBlockHashesMessageTest.java @@ -11,35 +11,35 @@ import org.spongycastle.util.encoders.Hex; public class GetBlockHashesMessageTest { /* BLOCK_HASHES_MESSAGE */ - + @Test /* BlockHashesMessage 1 from network */ public void test_1() { String blockHashesMessageRaw = "e513a05ad1c9caeade4cdf5798e796dc87939231d9c76c20a6a33fea6dab8e9d6dd009820100"; - + byte[] payload = Hex.decode(blockHashesMessageRaw); GetBlockHashesMessage getBlockHashesMessage = new GetBlockHashesMessage(payload); System.out.println(getBlockHashesMessage); - + assertEquals(EthMessageCodes.GET_BLOCK_HASHES, getBlockHashesMessage.getCommand()); assertEquals("5ad1c9caeade4cdf5798e796dc87939231d9c76c20a6a33fea6dab8e9d6dd009", Hex.toHexString(getBlockHashesMessage.getBestHash())); assertEquals(256, getBlockHashesMessage.getMaxBlocks()); assertEquals(BlockHashesMessage.class, getBlockHashesMessage.getAnswerMessage()); } - + @Test /* GetBlockHashesMessage 2 from new */ public void test_2() { - byte[] bestHash = Hex.decode("455408387e6c5b029b0d51f7d617a4d1dc4895fa6eda09455cc2ee62c08d907e"); + byte[] bestHash = Hex.decode("455408387e6c5b029b0d51f7d617a4d1dc4895fa6eda09455cc2ee62c08d907e"); GetBlockHashesMessage getBlockHashesMessage = new GetBlockHashesMessage(bestHash, 128); System.out.println(getBlockHashesMessage); - + String expected = "e403a0455408387e6c5b029b0d51f7d617a4d1dc4895fa6eda09455cc2ee62c08d907e8180"; assertEquals(expected, Hex.toHexString(getBlockHashesMessage.getEncoded())); - + assertEquals(EthMessageCodes.GET_BLOCK_HASHES, getBlockHashesMessage.getCommand()); assertEquals(Hex.toHexString(bestHash), Hex.toHexString(getBlockHashesMessage.getBestHash())); assertEquals(128, getBlockHashesMessage.getMaxBlocks()); assertEquals(BlockHashesMessage.class, getBlockHashesMessage.getAnswerMessage()); } - - + + } diff --git a/ethereumj-core/src/test/java/test/ethereum/net/GetBlocksMessageTest.java b/ethereumj-core/src/test/java/test/ethereum/net/GetBlocksMessageTest.java index b9c4e7fb..37a8b849 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/GetBlocksMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/GetBlocksMessageTest.java @@ -19,21 +19,21 @@ public class GetBlocksMessageTest { public void test_1() { String getBlocksMessageRaw = "f8a615a0497dcbd12fa99ced7b27cda6611f64eb13ab50e20260eec5ee6b7190e7206d54a00959bdfba5e54fcc9370e86b7996fbe32a277bab65c31a0102226f83c4d3e0f2a001a333c156485880776e929e84c26c9778c1e9b4dcb5cd3bff8ad0aeff385df0a0690e13595c9e8e4fa9a621dfed6ad828a6e8e591479af6897c979a83daf73084a0b20f253d2b62609e932c13f3bca59a22913ea5b1e532d8a707976997461ec143"; - + byte[] payload = Hex.decode(getBlocksMessageRaw); GetBlocksMessage getBlocksMessage = new GetBlocksMessage(payload); System.out.println(getBlocksMessage); - + assertEquals(EthMessageCodes.GET_BLOCKS, getBlocksMessage.getCommand()); assertEquals(5, getBlocksMessage.getBlockHashes().size()); String hash1 = "497dcbd12fa99ced7b27cda6611f64eb13ab50e20260eec5ee6b7190e7206d54"; String hash4 = "b20f253d2b62609e932c13f3bca59a22913ea5b1e532d8a707976997461ec143"; assertEquals(hash1, Hex.toHexString(getBlocksMessage.getBlockHashes().get(0))); assertEquals(hash4, Hex.toHexString(getBlocksMessage.getBlockHashes().get(4))); - + assertEquals(BlocksMessage.class, getBlocksMessage.getAnswerMessage()); } - + @Test /* GetBlocks from new */ public void test_2() { @@ -43,13 +43,13 @@ public class GetBlocksMessageTest { Hex.decode("01a333c156485880776e929e84c26c9778c1e9b4dcb5cd3bff8ad0aeff385df0"), Hex.decode("690e13595c9e8e4fa9a621dfed6ad828a6e8e591479af6897c979a83daf73084"), Hex.decode("b20f253d2b62609e932c13f3bca59a22913ea5b1e532d8a707976997461ec143")); - + GetBlocksMessage getBlocksMessage = new GetBlocksMessage(hashList); System.out.println(getBlocksMessage); - + String expected = "f8a605a0497dcbd12fa99ced7b27cda6611f64eb13ab50e20260eec5ee6b7190e7206d54a00959bdfba5e54fcc9370e86b7996fbe32a277bab65c31a0102226f83c4d3e0f2a001a333c156485880776e929e84c26c9778c1e9b4dcb5cd3bff8ad0aeff385df0a0690e13595c9e8e4fa9a621dfed6ad828a6e8e591479af6897c979a83daf73084a0b20f253d2b62609e932c13f3bca59a22913ea5b1e532d8a707976997461ec143"; assertEquals(expected, Hex.toHexString(getBlocksMessage.getEncoded())); - + assertEquals(EthMessageCodes.GET_BLOCKS, getBlocksMessage.getCommand()); assertEquals(5, getBlocksMessage.getBlockHashes().size()); assertEquals(BlocksMessage.class, getBlocksMessage.getAnswerMessage()); 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 ee349e55..e7cad5a0 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/HelloMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/HelloMessageTest.java @@ -24,7 +24,7 @@ public class HelloMessageTest { @Test public void test1() { String helloMessageRaw = "f87a8002a5457468657265756d282b2b292f76302e372e392f52656c656173652f4c696e75782f672b2bccc58365746827c583736868018203e0b8401fbf1e41f08078918c9f7b6734594ee56d7f538614f602c71194db0a1af5a77f9b86eb14669fe7a8a46a2dd1b7d070b94e463f4ecd5b337c8b4d31bbf8dd5646"; - + byte[] payload = Hex.decode(helloMessageRaw); HelloMessage helloMessage = new HelloMessage(payload); logger.info(helloMessage.toString()); @@ -40,6 +40,6 @@ public class HelloMessageTest { } - + } \ No newline at end of file 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 42445406..1989298d 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/PeersMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/PeersMessageTest.java @@ -30,7 +30,7 @@ public class PeersMessageTest { assertEquals(P2pMessageCodes.GET_PEERS, getPeersMessage.getCommand()); } - + /* PEERS */ @Test /* PeersMessage 1 from RLP */ diff --git a/ethereumj-core/src/test/java/test/ethereum/net/PingPongMessageTest.java b/ethereumj-core/src/test/java/test/ethereum/net/PingPongMessageTest.java index c90ead74..20e354d1 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/PingPongMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/PingPongMessageTest.java @@ -18,10 +18,10 @@ public class PingPongMessageTest { System.out.println(pingMessage); assertEquals(PongMessage.class, pingMessage.getAnswerMessage()); - + assertEquals(P2pMessageCodes.PING, pingMessage.getCommand()); } - + @Test /* PongMessage */ public void testPong() { 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 6e13f495..6bdfaa15 100644 --- a/ethereumj-core/src/test/java/test/ethereum/net/TransactionsMessageTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/net/TransactionsMessageTest.java @@ -23,7 +23,7 @@ import java.util.Arrays; public class TransactionsMessageTest { /* GET_TRANSACTIONS */ - + @Test /* GetTransactions message 1 */ public void testGetTransactions() { @@ -33,9 +33,9 @@ public class TransactionsMessageTest { assertEquals(EthMessageCodes.GET_TRANSACTIONS, getTransactionsMessage.getCommand()); assertEquals(TransactionsMessage.class, getTransactionsMessage.getAnswerMessage()); } - + /* TRANSACTIONS */ - + @Test /* Transactions message 1 */ public void test_1() { @@ -43,7 +43,7 @@ public class TransactionsMessageTest { + "881bc16d674ec80000801ba05c89ebf2b77eeab88251e553f6f9d53badc1d800" + "bbac02d830801c2aa94a4c9fa00b7907532b1f29c79942b75fff98822293bf5f" + "daa3653a8d9f424c6a3265f06c"; - + byte[] payload = Hex.decode(txsPacketRaw); TransactionsMessage transactionsMessage = new TransactionsMessage(payload); @@ -66,7 +66,7 @@ public class TransactionsMessageTest { assertEquals("5c89ebf2b77eeab88251e553f6f9d53badc1d800bbac02d830801c2aa94a4c9f", Hex.toHexString(tx.getSignature().r.toByteArray())); assertEquals("0b7907532b1f29c79942b75fff98822293bf5fdaa3653a8d9f424c6a3265f06c", Hex.toHexString(tx.getSignature().s.toByteArray())); } - + @Test /* Transactions message 2 */ public void test_2() { @@ -96,13 +96,13 @@ public class TransactionsMessageTest { System.out.println(transactionsMessage); assertEquals(EthMessageCodes.TRANSACTIONS, transactionsMessage.getCommand()); - + assertEquals(3, transactionsMessage.getTransactions().size()); Iterator txIter = transactionsMessage.getTransactions().iterator(); Transaction tx1 = txIter.next(); txIter.next(); // skip one Transaction tx3 = txIter.next(); - + assertEquals("1b9d9456293cbcbc2f28a0fdc67028128ea571b033fb0e21d0ee00bcd6167e5d", Hex.toHexString(tx3.getHash())); @@ -133,7 +133,7 @@ public class TransactionsMessageTest { Hex.toHexString(tx3.getSignature().s.toByteArray())); // Transaction #2 - + assertEquals("dde9543921850f41ca88e5401322cd7651c78a1e4deebd5ee385af8ac343f0ad", Hex.toHexString(tx1.getHash())); @@ -163,7 +163,7 @@ public class TransactionsMessageTest { assertEquals("1e87172a861f6c37b5a9e3a5d0d7393152a7fbe41530e5bb8ac8f35433e5931b", Hex.toHexString(tx1.getSignature().s.toByteArray())); } - + @Test /* Transactions msg encode */ public void test_3() throws Exception { 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 751db0bf..23493f7d 100644 --- a/ethereumj-core/src/test/java/test/ethereum/serpent/SerpentCompileTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/serpent/SerpentCompileTest.java @@ -767,7 +767,7 @@ public class SerpentCompileTest { " a=20 \n" + " \n" + " \n"; - + SerpentParser parser = ParserUtils.getParser(SerpentLexer.class, SerpentParser.class, code); @@ -799,7 +799,7 @@ public class SerpentCompileTest { " a=40 \n" + "else: \n" + " a=40 \n"; - + SerpentParser parser = ParserUtils.getParser(SerpentLexer.class, SerpentParser.class, code); @@ -1215,7 +1215,7 @@ public class SerpentCompileTest { "c = [22, 24, 25]\n" + "c[ 0 ] = 3" ; String expected = "MSIZE 32 ADD MSIZE DUP 32 ADD 2 SWAP MSTORE DUP 64 ADD 4 SWAP MSTORE DUP 96 ADD 6 SWAP MSTORE 128 SWAP MSTORE MSIZE 32 ADD MSIZE DUP 32 ADD 12 SWAP MSTORE DUP 64 ADD 14 SWAP MSTORE 96 SWAP MSTORE MSIZE 32 ADD MSIZE DUP 32 ADD 22 SWAP MSTORE DUP 64 ADD 24 SWAP MSTORE DUP 96 ADD 25 SWAP MSTORE 128 SWAP MSTORE 3 32 0 MUL 32 ADD 224 ADD 0 ADD MSTORE"; - + String asmResult = SerpentCompiler.compile(code); assertEquals(expected, asmResult); } @@ -1293,7 +1293,7 @@ public class SerpentCompileTest { * TODO: suicide(1) testing * TODO: stop testing */ - + /** TODO: add this namecoin sample to the testing if !(contract.storage[msg.data[0]]): 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 089abef9..4ea08ed3 100644 --- a/ethereumj-core/src/test/java/test/ethereum/trie/TrieTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/trie/TrieTest.java @@ -521,54 +521,54 @@ public class TrieTest { trie.update("te", "testy"); assertEquals("8452568af70d8d140f58d941338542f645fcca50094b20f3c3d8c3df49337928", Hex.toHexString(trie.getRootHash())); } - + private final String randomDictionary = "spinneries, archipenko, prepotency, herniotomy, preexpress, relaxative, insolvably, debonnaire, apophysate, virtuality, cavalryman, utilizable, diagenesis, vitascopic, governessy, abranchial, cyanogenic, gratulated, signalment, predicable, subquality, crystalize, prosaicism, oenologist, repressive, impanelled, cockneyism, bordelaise, compigne, konstantin, predicated, unsublimed, hydrophane, phycomyces, capitalise, slippingly, untithable, unburnable, deoxidizer, misteacher, precorrect, disclaimer, solidified, neuraxitis, caravaning, betelgeuse, underprice, uninclosed, acrogynous, reirrigate, dazzlingly, chaffiness, corybantes, intumesced, intentness, superexert, abstrusely, astounding, pilgrimage, posttarsal, prayerless, nomologist, semibelted, frithstool, unstinging, ecalcarate, amputating, megascopic, graphalloy, platteland, adjacently, mingrelian, valentinus, appendical, unaccurate, coriaceous, waterworks, sympathize, doorkeeper, overguilty, flaggingly, admonitory, aeriferous, normocytic, parnellism, catafalque, odontiasis, apprentice, adulterous, mechanisma, wilderness, undivorced, reinterred, effleurage, pretrochal, phytogenic, swirlingly, herbarized, unresolved, classifier, diosmosing, microphage, consecrate, astarboard, predefying, predriving, lettergram, ungranular, overdozing, conferring, unfavorite, peacockish, coinciding, erythraeum, freeholder, zygophoric, imbitterer, centroidal, appendixes, grayfishes, enological, indiscreet, broadcloth, divulgated, anglophobe, stoopingly, bibliophil, laryngitis, separatist, estivating, bellarmine, greasiness, typhlology, xanthation, mortifying, endeavorer, aviatrices, unequalise, metastatic, leftwinger, apologizer, quatrefoil, nonfouling, bitartrate, outchiding, undeported, poussetted, haemolysis, asantehene, montgomery, unjoinable, cedarhurst, unfastener, nonvacuums, beauregard, animalized, polyphides, cannizzaro, gelatinoid, apologised, unscripted, tracheidal, subdiscoid, gravelling, variegated, interabang, inoperable, immortelle, laestrygon, duplicatus, proscience, deoxidised, manfulness, channelize, nondefense, ectomorphy, unimpelled, headwaiter, hexaemeric, derivation, prelexical, limitarian, nonionized, prorefugee, invariably, patronizer, paraplegia, redivision, occupative, unfaceable, hypomnesia, psalterium, doctorfish, gentlefolk, overrefine, heptastich, desirously, clarabelle, uneuphonic, autotelism, firewarden, timberjack, fumigation, drainpipes, spathulate, novelvelle, bicorporal, grisliness, unhesitant, supergiant, unpatented, womanpower, toastiness, multichord, paramnesia, undertrick, contrarily, neurogenic, gunmanship, settlement, brookville, gradualism, unossified, villanovan, ecospecies, organising, buckhannon, prefulfill, johnsonese, unforegone, unwrathful, dunderhead, erceldoune, unwadeable, refunction, understuff, swaggering, freckliest, telemachus, groundsill, outslidden, bolsheviks, recognizer, hemangioma, tarantella, muhammedan, talebearer, relocation, preemption, chachalaca, septuagint, ubiquitous, plexiglass, humoresque, biliverdin, tetraploid, capitoline, summerwood, undilating, undetested, meningitic, petrolatum, phytotoxic, adiphenine, flashlight, protectory, inwreathed, rawishness, tendrillar, hastefully, bananaquit, anarthrous, unbedimmed, herborized, decenniums, deprecated, karyotypic, squalidity, pomiferous, petroglyph, actinomere, peninsular, trigonally, androgenic, resistance, unassuming, frithstool, documental, eunuchised, interphone, thymbraeus, confirmand, expurgated, vegetation, myographic, plasmagene, spindrying, unlackeyed, foreknower, mythically, albescence, rebudgeted, implicitly, unmonastic, torricelli, mortarless, labialized, phenacaine, radiometry, sluggishly, understood, wiretapper, jacobitely, unbetrayed, stadholder, directress, emissaries, corelation, sensualize, uncurbable, permillage, tentacular, thriftless, demoralize, preimagine, iconoclast, acrobatism, firewarden, transpired, bluethroat, wanderjahr, groundable, pedestrian, unulcerous, preearthly, freelanced, sculleries, avengingly, visigothic, preharmony, bressummer, acceptable, unfoolable, predivider, overseeing, arcosolium, piriformis, needlecord, homebodies, sulphation, phantasmic, unsensible, unpackaged, isopiestic, cytophagic, butterlike, frizzliest, winklehawk, necrophile, mesothorax, cuchulainn, unrentable, untangible, unshifting, unfeasible, poetastric, extermined, gaillardia, nonpendent, harborside, pigsticker, infanthood, underrower, easterling, jockeyship, housebreak, horologium, undepicted, dysacousma, incurrable, editorship, unrelented, peritricha, interchaff, frothiness, underplant, proafrican, squareness, enigmatise, reconciled, nonnumeral, nonevident, hamantasch, victualing, watercolor, schrdinger, understand, butlerlike, hemiglobin, yankeeland"; @Test public void testMasiveUpdate(){ boolean massiveUpdateTestEnabled = false; - + if(massiveUpdateTestEnabled) { List randomWords = Arrays.asList(randomDictionary.split(",")); HashMap testerMap = new HashMap<>(); - + TrieImpl trie = new TrieImpl(mockDb); Random generator = new Random(); - + // Random insertion for (int i = 0; i < 100000; ++i ){ - + int randomIndex1 = generator.nextInt(randomWords.size()); int randomIndex2 = generator.nextInt(randomWords.size()); - + String word1 = randomWords.get(randomIndex1).trim(); String word2 = randomWords.get(randomIndex2).trim(); - + trie.update(word1, word2); testerMap.put(word1, word2); } - + int half = testerMap.size() / 2; for (int r = 0; r < half; ++r){ - + int randomIndex = generator.nextInt(randomWords.size()); String word1 = randomWords.get(randomIndex).trim(); - + testerMap.remove(word1); trie.delete(word1); } - + trie.cleanCache(); trie.sync(); - + // Assert the result now Iterator keys = testerMap.keySet().iterator(); while (keys.hasNext()){ - + String mapWord1 = keys.next(); String mapWord2 = testerMap.get(mapWord1); String treeWord2 = new String(trie.get(mapWord1)); - + Assert.assertEquals(mapWord2, treeWord2); } } @@ -641,55 +641,55 @@ public class TrieTest { assertEquals(trieSingle.getRootHash(), trie2.getRootHash()); } - + @Test // tests saving keys to the file // public void testMasiveUpdateFromDB(){ boolean massiveUpdateFromDBEnabled = false; - + if(massiveUpdateFromDBEnabled) { List randomWords = Arrays.asList(randomDictionary.split(",")); Map testerMap = new HashMap<>(); TrieImpl trie = new TrieImpl(mockDb); Random generator = new Random(); - + // Random insertion for (int i = 0; i < 50000; ++i ){ - + int randomIndex1 = generator.nextInt(randomWords.size()); int randomIndex2 = generator.nextInt(randomWords.size()); - + String word1 = randomWords.get(randomIndex1).trim(); String word2 = randomWords.get(randomIndex2).trim(); - + trie.update(word1, word2); testerMap.put(word1, word2); } - + trie.cleanCache(); trie.sync(); - + // Assert the result now Iterator keys = testerMap.keySet().iterator(); while (keys.hasNext()){ - + String mapWord1 = keys.next(); String mapWord2 = testerMap.get(mapWord1); String treeWord2 = new String(trie.get(mapWord1)); - + Assert.assertEquals(mapWord2, treeWord2); } - + TrieImpl trie2 = new TrieImpl(mockDb, trie.getRootHash()); - + // Assert the result now keys = testerMap.keySet().iterator(); while (keys.hasNext()){ - + String mapWord1 = keys.next(); String mapWord2 = testerMap.get(mapWord1); String treeWord2 = new String(trie2.get(mapWord1)); - + Assert.assertEquals(mapWord2, treeWord2); } } 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 3930760b..d756a5c9 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/ByteUtilTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/ByteUtilTest.java @@ -19,7 +19,7 @@ public class ByteUtilTest { @Test public void testAppendByte() { byte[] bytes = "tes".getBytes(); - byte b = 0x74; + byte b = 0x74; Assert.assertArrayEquals("test".getBytes(), ByteUtil.appendByte(bytes, b)); } @@ -38,15 +38,15 @@ public class ByteUtilTest { byte[] actuals = ByteUtil.bigIntegerToBytes(b); assertArrayEquals(expecteds, actuals); } - - @Test + + @Test public void testBigIntegerToBytesZero() { byte[] expecteds = new byte[]{0x00}; BigInteger b = BigInteger.ZERO; byte[] actuals = ByteUtil.bigIntegerToBytes(b); assertArrayEquals(expecteds, actuals); } - + @Test public void testToHexString() { assertEquals("", ByteUtil.toHexString(null)); @@ -63,7 +63,7 @@ public class ByteUtilTest { public void testByteArrayToInt() { assertEquals(0, ByteUtil.byteArrayToInt(null)); assertEquals(0, ByteUtil.byteArrayToInt(new byte[0])); - + // byte[] x = new byte[] { 5,1,7,0,8 }; // long start = System.currentTimeMillis(); // for (int i = 0; i < 100000000; i++) { @@ -102,7 +102,7 @@ public class ByteUtilTest { assertArrayEquals(expected, ByteUtil.stripLeadingZeroes(test1)); assertArrayEquals(expected, ByteUtil.stripLeadingZeroes(test2)); } - + @Test public void testMatchingNibbleLength1() { // a larger than b @@ -119,7 +119,7 @@ public class ByteUtilTest { int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(1, result); } - + @Test public void testMatchingNibbleLength3() { // a and b the same length equal @@ -128,7 +128,7 @@ public class ByteUtilTest { int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(1, result); } - + @Test public void testMatchingNibbleLength4() { // a and b the same length not equal @@ -137,7 +137,7 @@ public class ByteUtilTest { int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(0, result); } - + @Test public void testNiceNiblesOutput_1(){ byte[] test = {7, 0, 7, 5, 7, 0, 7, 0, 7, 9}; @@ -151,7 +151,7 @@ public class ByteUtilTest { String result = "\\x07\\x00\\x07\\x0f\\x07\\x00\\x0a\\x00\\x07\\x09"; assertEquals(result, ByteUtil.nibblesToPrettyString(test)); } - + @Test(expected=NullPointerException.class) public void testMatchingNibbleLength5() { // a == null @@ -159,7 +159,7 @@ public class ByteUtilTest { byte[] b = new byte[] { 0x00 }; ByteUtil.matchingNibbleLength(a, b); } - + @Test(expected=NullPointerException.class) public void testMatchingNibbleLength6() { // b == null @@ -167,7 +167,7 @@ public class ByteUtilTest { byte[] b = null; ByteUtil.matchingNibbleLength(a, b); } - + @Test public void testMatchingNibbleLength7() { // a or b is empty @@ -176,18 +176,18 @@ public class ByteUtilTest { int result = ByteUtil.matchingNibbleLength(a, b); assertEquals(0, result); } - + /** - * This test shows the difference between iterating over, + * This test shows the difference between iterating over, * and comparing byte[] vs BigInteger value. - * + * * Results indicate that the former has ~15x better performance. * Therefore this is used in the Miner.mine() method. */ @Test public void testIncrementPerformance() { boolean testEnabled = false; - + if(testEnabled) { byte[] counter1 = new byte[4]; byte[] max = ByteBuffer.allocate(4).putInt(Integer.MAX_VALUE).array(); @@ -198,7 +198,7 @@ public class ByteUtilTest { } } System.out.println(System.currentTimeMillis() - start1 + "ms to reach: " + Hex.toHexString(counter1)); - + BigInteger counter2 = BigInteger.ZERO; long start2 = System.currentTimeMillis(); while(true) { 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 b5d3852d..307924f6 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/CompactEncoderTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/CompactEncoderTest.java @@ -8,14 +8,14 @@ import org.junit.Test; public class CompactEncoderTest { private final static byte T = 16; // terminator - + @Test public void testCompactEncodeOddCompact() { 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 }; @@ -31,7 +31,7 @@ public class CompactEncoderTest { } @Test - public void testCompactEncodeOddTerminated() { + public void testCompactEncodeOddTerminated() { 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)); diff --git a/ethereumj-core/src/test/java/test/ethereum/util/HashUtilTest.java b/ethereumj-core/src/test/java/test/ethereum/util/HashUtilTest.java index 233b5069..b9fe5a30 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/HashUtilTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/HashUtilTest.java @@ -7,21 +7,21 @@ import org.spongycastle.util.encoders.Hex; import static org.junit.Assert.assertEquals; public class HashUtilTest { - + @Test public void testSha256_EmptyString() { String expected1 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; String result1 = Hex.toHexString(HashUtil.sha256(new byte[0])); assertEquals(expected1, result1); } - + @Test public void testSha256_Test() { String expected2 = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"; String result2 = Hex.toHexString(HashUtil.sha256("test".getBytes())); assertEquals(expected2, result2); } - + @Test public void testSha256_Multiple() { String expected1 = "1b4f0e9851971998e732078544c96b36c3d01cedf7caa332359d6f1d83567014"; @@ -39,14 +39,14 @@ public class HashUtilTest { String result1 = Hex.toHexString(HashUtil.sha3(new byte[0])); assertEquals(expected1, result1); } - + @Test public void testSha3_Test() { String expected2 = "9c22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664fb9a3cb658"; String result2 = Hex.toHexString(HashUtil.sha3("test".getBytes())); assertEquals(expected2, result2); } - + @Test public void testSha3_Multiple() { String expected1 = "6d255fc3390ee6b41191da315958b7d6a1e5b17904cc7683558f98acc57977b4"; @@ -57,21 +57,21 @@ public class HashUtilTest { String result2 = Hex.toHexString(HashUtil.sha3("test2".getBytes())); assertEquals(expected2, result2); } - + @Test public void testRIPEMD160_EmptyString() { String expected1 = "9c1185a5c5e9fc54612808977ee8f548b2258d31"; String result1 = Hex.toHexString(HashUtil.ripemd160(new byte[0])); assertEquals(expected1, result1); } - + @Test public void testRIPEMD160_Test() { String expected2 = "5e52fee47e6b070565f74372468cdc699de89107"; String result2 = Hex.toHexString(HashUtil.ripemd160("test".getBytes())); assertEquals(expected2, result2); } - + @Test public void testRIPEMD160_Multiple() { String expected1 = "9295fac879006ff44812e43b83b515a06c2950aa"; 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 588b3c6c..c96cdd2d 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/RLPTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/RLPTest.java @@ -91,7 +91,7 @@ public class RLPTest { BigInteger expectedPeerId = new BigInteger("9650128800487972697726795438087510101805200020100629942070155319087371611597658887860952245483247188023303607186148645071838189546969115967896446355306572"); assertEquals(expectedPeerId, peerId); - + nextIndex = RLP.getNextElementIndex(payload, nextIndex); nextIndex = RLP.getFirstListElement(payload, nextIndex); ip = RLP.decodeIP4Bytes(payload, nextIndex); @@ -153,7 +153,7 @@ public class RLPTest { data = RLP.encodeShort((short)20202); assertArrayEquals(expected5, data); } - + @Test /** encode int */ public void testEncodeInt() { @@ -176,11 +176,11 @@ public class RLPTest { byte[] expected5 = {(byte)0x82, (byte)0x4E, (byte)0xEA}; data = RLP.encodeInt(20202); assertArrayEquals(expected5, data); - + byte[] expected6 = {(byte)0x83, 1, 0, 0}; data = RLP.encodeInt(65536); assertArrayEquals(expected6, data); - + byte[] expected7 = {(byte)0x80}; data = RLP.encodeInt(Integer.MIN_VALUE); assertArrayEquals(expected7, data); @@ -189,7 +189,7 @@ public class RLPTest { data = RLP.encodeInt(Integer.MAX_VALUE); assertArrayEquals(expected8, data); } - + @Test /** encode BigInteger */ public void test6() { @@ -264,32 +264,32 @@ public class RLPTest { @Test /** encode list */ public void test9() { - + byte[] actuals = RLP.encodeList(); assertArrayEquals(new byte[] { (byte) 0xc0 }, actuals); } - + @Test /** encode null value */ public void testEncodeElementNull() { - + byte[] actuals = RLP.encodeElement(null); assertArrayEquals(new byte[] { (byte) 0x80 }, actuals); } - + @Test /** encode single byte 0x00 */ public void testEncodeElementZero() { - + byte[] actuals = RLP.encodeElement(new byte[] {0x00}); assertArrayEquals(new byte[] { (byte) 0x00 }, actuals); } @Test /** encode single byte 0x01 */ public void testEncodeElementOne() { - + 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 */ public void test10() { @@ -375,24 +375,24 @@ public class RLPTest { RLPList.recursivePrint(rlpList); // TODO: add some asserts in place of just printing the rlpList } - + /************************************ * Test data from: https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP - * + * * Using assertEquals(String, String) instead of assertArrayEquals to see the actual content when the test fails. */ @Test(expected = RuntimeException.class) public void testEncodeNull() { RLP.encode(null); } - + @Test public void testEncodeEmptyString() { String test = ""; String expected = "80"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + String decodeResult = (String)RLP.decode(encoderesult, 0).getDecoded(); assertEquals(test, decodeResult); } @@ -403,18 +403,18 @@ public class RLPTest { String expected = "83646f67"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + byte[] decodeResult = (byte[]) RLP.decode(encoderesult, 0).getDecoded(); assertEquals(test, bytesToAscii(decodeResult)); } - + @Test public void testEncodeSingleCharacter() { String test = "d"; String expected = "64"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + byte[] decodeResult = (byte[]) RLP.decode(encoderesult, 0).getDecoded(); assertEquals(test, bytesToAscii(decodeResult)); } @@ -425,7 +425,7 @@ public class RLPTest { String expected = "b8384c6f72656d20697073756d20646f6c6f722073697420616d65742c20636f6e7365637465747572206164697069736963696e6720656c6974"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + byte[] decodeResult = (byte[]) RLP.decode(encoderesult, 0).getDecoded(); assertEquals(test, bytesToAscii(decodeResult)); } @@ -440,47 +440,47 @@ public class RLPTest { String decodeResult = (String) RLP.decode(encoderesult, 0).getDecoded(); assertEquals("", decodeResult); } - + @Test public void testEncodeSmallInteger() { Integer test = new Integer(15); String expected = "0f"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + byte[] decodeResult = (byte[]) RLP.decode(encoderesult, 0).getDecoded(); int result = byteArrayToInt(decodeResult); assertEquals(test, Integer.valueOf(result)); } - + @Test public void testEncodeMediumInteger() { Integer test = new Integer(1000); String expected = "8203e8"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + byte[] decodeResult = (byte[]) RLP.decode(encoderesult, 0).getDecoded(); int result = byteArrayToInt(decodeResult); assertEquals(test, Integer.valueOf(result)); - + test = new Integer(1024); expected = "820400"; encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + decodeResult = (byte[]) RLP.decode(encoderesult, 0).getDecoded(); result = byteArrayToInt(decodeResult); assertEquals(test, Integer.valueOf(result)); } - + @Test public void testEncodeBigInteger() { BigInteger test = new BigInteger("100102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", 16); String expected = "a0100102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + byte[] decodeResult = (byte[]) RLP.decode(encoderesult, 0).getDecoded(); assertEquals(test, new BigInteger(1, decodeResult)); } @@ -491,7 +491,7 @@ public class RLPTest { String expected = "c0"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + Object[] decodeResult = (Object[]) RLP.decode(encoderesult, 0).getDecoded(); assertTrue(decodeResult.length == 0); } @@ -502,22 +502,22 @@ public class RLPTest { String expected = "c88363617483646f67"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + Object[] decodeResult = (Object[]) RLP.decode(encoderesult, 0).getDecoded(); assertEquals("cat", bytesToAscii((byte[]) decodeResult[0])); assertEquals("dog", bytesToAscii((byte[]) decodeResult[1])); - + test = new String[] { "dog", "god", "cat" }; expected = "cc83646f6783676f6483636174"; encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + decodeResult = (Object[]) RLP.decode(encoderesult, 0).getDecoded(); assertEquals("dog", bytesToAscii((byte[]) decodeResult[0])); assertEquals("god", bytesToAscii((byte[]) decodeResult[1])); assertEquals("cat", bytesToAscii((byte[]) decodeResult[2])); } - + @Test public void testEncodeLongStringList() { String element1 = "cat"; @@ -526,16 +526,16 @@ public class RLPTest { String expected = "f83e83636174b8384c6f72656d20697073756d20646f6c6f722073697420616d65742c20636f6e7365637465747572206164697069736963696e6720656c6974"; byte[] encoderesult = (byte[]) RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + Object[] decodeResult = (Object[]) RLP.decode(encoderesult, 0).getDecoded(); assertEquals(element1, bytesToAscii((byte[]) decodeResult[0])); assertEquals(element2, bytesToAscii((byte[]) decodeResult[1])); } - + //multilist: - //in: [ 1, ["cat"], "dog", [ 2 ] ], + //in: [ 1, ["cat"], "dog", [ 2 ] ], //out: "cc01c48363617483646f67c102" - //in: [ [ ["cat"], ["dog"] ], [ [1] [2] ], [] ], + //in: [ [ ["cat"], ["dog"] ], [ [1] [2] ], [] ], //out: "cdc88363617483646f67c20102c0" @Test public void testEncodeMultiList() { @@ -543,18 +543,18 @@ public class RLPTest { 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] ))); - + 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] ))); @@ -562,7 +562,7 @@ public class RLPTest { assertEquals(2, byteArrayToInt( ((byte[]) ((Object[]) decodeResult[1])[1] ))); assertTrue( ( ((Object[]) decodeResult[2]).length == 0 )); } - + @Test public void testEncodeEmptyListOfList() { // list = [ [ [], [] ], [] ], @@ -570,7 +570,7 @@ public class RLPTest { 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); @@ -578,7 +578,7 @@ public class RLPTest { assertTrue( ( (Object[]) ( (Object[]) ( decodeResult[0] ) )[0]).length == 0); assertTrue( ( (Object[]) ( (Object[]) ( decodeResult[0] ) )[1]).length == 0); } - + //The set theoretical representation of two @Test public void testEncodeRepOfTwoListOfList() { @@ -587,7 +587,7 @@ public class RLPTest { String expected = "c7c0c1c0c3c0c1c0"; byte[] encoderesult = RLP.encode(test); assertEquals(expected, Hex.toHexString(encoderesult)); - + Object[] decodeResult = (Object[]) RLP.decode(encoderesult, 0).getDecoded(); assertTrue( decodeResult.length == 3 ); assertTrue( ( (Object[]) (decodeResult[0]) ).length == 0); @@ -596,12 +596,12 @@ public class RLPTest { 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( ( (Object[]) ( (Object[]) ( (Object[]) (decodeResult[2]) )[1] )[0]).length == 0); } - + @Test public void testRlpEncode() { - + assertEquals(result01, Hex.toHexString(RLP.encode(test01))); assertEquals(result02, Hex.toHexString(RLP.encode(test02))); assertEquals(result03, Hex.toHexString(RLP.encode(test03))); @@ -635,22 +635,22 @@ public class RLPTest { decodedData = (byte[]) RLP.decode(Hex.decode(result03), pos).getDecoded(); assertEquals(test03, bytesToAscii(decodedData)); - + decodedData = (byte[]) RLP.decode(Hex.decode(result04), pos).getDecoded(); assertEquals(test04, bytesToAscii(decodedData)); - + decodedData = (byte[]) RLP.decode(Hex.decode(result05), pos).getDecoded(); assertEquals(test05, bytesToAscii(decodedData)); - + decodedList = (Object[]) RLP.decode(Hex.decode(result06), pos).getDecoded(); assertEquals(test06[0], bytesToAscii((byte[]) decodedList[0])); assertEquals(test06[1], bytesToAscii((byte[]) decodedList[1])); - + decodedList = (Object[]) RLP.decode(Hex.decode(result07), pos).getDecoded(); assertEquals(test07[0], bytesToAscii((byte[]) decodedList[0])); assertEquals(test07[1], bytesToAscii((byte[]) decodedList[1])); assertEquals(test07[2], bytesToAscii((byte[]) decodedList[2])); - + // 1 decodedData = (byte[]) RLP.decode(Hex.decode(result08), pos).getDecoded(); assertEquals(test08, byteArrayToInt(decodedData)); @@ -663,23 +663,23 @@ public class RLPTest { decodedData = (byte[]) RLP.decode(Hex.decode(result10), pos).getDecoded(); assertEquals(test10, byteArrayToInt(decodedData)); - // 1000 + // 1000 decodedData = (byte[]) RLP.decode(Hex.decode(result11), pos).getDecoded(); assertEquals(test11, byteArrayToInt(decodedData)); - + decodedData = (byte[]) RLP.decode(Hex.decode(result12), pos).getDecoded(); assertTrue(test12.compareTo(new BigInteger(1, decodedData)) == 0); - + decodedData = (byte[]) RLP.decode(Hex.decode(result13), pos).getDecoded(); assertTrue(test13.compareTo(new BigInteger(1, decodedData)) == 0); - + // Need to test with different expected value, because decoding doesn't recognize types Object testObject1 = RLP.decode(Hex.decode(result14), pos).getDecoded(); assertTrue(DeepEquals.deepEquals(expected14, testObject1)); - + Object testObject2 = RLP.decode(Hex.decode(result15), pos).getDecoded(); assertTrue(DeepEquals.deepEquals(test15, testObject2)); - + // Need to test with different expected value, because decoding doesn't recognize types Object testObject3 = RLP.decode(Hex.decode(result16), pos).getDecoded(); assertTrue(DeepEquals.deepEquals(expected16, testObject3)); @@ -691,7 +691,7 @@ public class RLPTest { // length < 56 int length = 1; int offset = 128; byte[] encodedLength = RLP.encodeLength(length, offset); - String expected = "81"; + String expected = "81"; assertEquals(expected, Hex.toHexString(encodedLength)); // 56 > length < 2^64 @@ -723,7 +723,7 @@ public class RLPTest { } } - + // Code from: http://stackoverflow.com/a/4785776/459349 private String bytesToAscii(byte[] b) { String hex = Hex.toHexString(b); @@ -738,35 +738,35 @@ public class RLPTest { @Test public void performanceDecode() throws IOException { boolean performanceEnabled = false; - + if(performanceEnabled) { String blockRaw = "f8cbf8c7a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a02f4399b08efe68945c1cf90ffe85bbe3ce978959da753f9e649f034015b8817da00000000000000000000000000000000000000000000000000000000000000000834000008080830f4240808080a004994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829c0c0"; byte[] payload = Hex.decode(blockRaw); - + final int ITERATIONS = 10000000; RLPList list = null; DecodeResult result = null; System.out.println("Starting " + ITERATIONS + " decoding iterations..."); - + long start1 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { result = RLP.decode(payload, 0); } long end1 = System.currentTimeMillis(); - + long start2 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { list = RLP.decode2(payload); } long end2 = System.currentTimeMillis(); - + System.out.println("Result RLP.decode()\t: " + (end1-start1) + "ms and\t " + determineSize(result) + " bytes for each resulting object list"); System.out.println("Result RLP.decode2()\t: " + (end2-start2) + "ms and\t " + determineSize(list) + " bytes for each resulting object list"); } else { System.out.println("Performance test for RLP.decode() disabled"); - } + } } - + private int determineSize(Serializable ser) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); 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 1918ae03..4d7d2a56 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/RlpTestData.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/RlpTestData.java @@ -7,43 +7,43 @@ public class RlpTestData { /*********************************** * https://github.com/ethereum/tests/blob/master/rlptest.txt */ - public static int test01 = 0; + public static int test01 = 0; public static String result01 = "80"; - - public static String test02 = ""; + + public static String test02 = ""; public static String result02 = "80"; - - public static String test03 = "d"; + + public static String test03 = "d"; public static String result03 = "64"; - - public static String test04 = "cat"; + + public static String test04 = "cat"; public static String result04 = "83636174"; - public static String test05 = "dog"; + 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 result07 = "cc83646f6783676f6483636174"; - public static int test08 = 1; + public static int test08 = 1; public static String result08 = "01"; - public static int test09 = 10; + public static int test09 = 10; public static String result09 = "0a"; - public static int test10 = 100; + public static int test10 = 100; public static String result10 = "64"; - public static int test11 = 1000; + public static int test11 = 1000; public static String result11 = "8203e8"; - public static BigInteger test12 = new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639935"); + public static BigInteger test12 = new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639935"); public static String result12 = "a0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; - public static BigInteger test13 = new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639936"); + public static BigInteger test13 = new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639936"); public static String result13 = "a1010000000000000000000000000000000000000000000000000000000000000000"; public static Object[] test14 = new Object[] { 1, 2, new Object[] {} }; 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 31e99843..28b6cdc7 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/UtilsTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/UtilsTest.java @@ -61,7 +61,7 @@ public class UtilsTest { assertEquals(expected, result); } - + @Test public void testAddressStringToBytes() { // valid address @@ -69,19 +69,19 @@ public class UtilsTest { byte[] expected = Hex.decode(HexStr); byte[] result = Utils.addressStringToBytes(HexStr); assertEquals(Arrays.areEqual(expected, result), true); - + // invalid address, we removed the last char so it cannot decode HexStr = "6c386a4b26f73c802f34673f7248bb118f97424"; expected = null; result = Utils.addressStringToBytes(HexStr); assertEquals(expected, result); - + // invalid address, longer than 20 bytes HexStr = new String(Hex.encode("I am longer than 20 bytes, i promise".getBytes())); expected = null; result = Utils.addressStringToBytes(HexStr); assertEquals(expected, result); - + // invalid address, shorter than 20 bytes HexStr = new String(Hex.encode("I am short".getBytes())); expected = null; 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 e142fd77..b65f3069 100644 --- a/ethereumj-core/src/test/java/test/ethereum/util/ValueTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/util/ValueTest.java @@ -15,12 +15,12 @@ public class ValueTest { public void testCmp() { Value val1 = new Value("hello"); Value val2 = new Value("world"); - + assertFalse("Expected values not to be equal", val1.cmp(val2)); Value val3 = new Value("hello"); Value val4 = new Value("hello"); - + assertTrue("Expected values to be equal", val3.cmp(val4)); } 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 37725e60..30c051b3 100644 --- a/ethereumj-core/src/test/java/test/ethereum/vm/DataWordTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/vm/DataWordTest.java @@ -13,22 +13,22 @@ public class DataWordTest { @Test public void testAddPerformance() { boolean enabled = false; - + 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 - + int ITERATIONS = 10000000; - + long now1 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { DataWord x = new DataWord(one); x.add(x); } System.out.println("Add1: " + (System.currentTimeMillis() - now1) + "ms"); - + long now2 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { DataWord x = new DataWord(one); @@ -44,23 +44,23 @@ public class DataWordTest { public void testAdd2() { byte[] two = new byte[32]; two[31] = (byte) 0xff; // 0x000000000000000000000000000000000000000000000000000000000000ff - + DataWord x = new DataWord(two); x.add(new DataWord(two)); System.out.println(Hex.toHexString(x.getData())); - + DataWord y = new DataWord(two); y.add2(new DataWord(two)); System.out.println(Hex.toHexString(y.getData())); } - + @Test public void testAdd3() { byte[] three = new byte[32]; for (int i = 0; i < three.length; i++) { three[i] = (byte) 0xff; } - + DataWord x = new DataWord(three); x.add(new DataWord(three)); assertEquals(32, x.getData().length); @@ -71,27 +71,27 @@ public class DataWordTest { // y.add2(new DataWord(three)); // System.out.println(Hex.toHexString(y.getData())); } - + @Test public void testMod() { String expected = "000000000000000000000000000000000000000000000000000000000000001a"; - + byte[] one = new byte[32]; one[31] = 0x1e; // 0x000000000000000000000000000000000000000000000000000000000000001e - + byte[] two = new byte[32]; for (int i = 0; i < two.length; i++) { two[i] = (byte) 0xff; } two[31] = 0x56; // 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff56 - + DataWord x = new DataWord(one);// System.out.println(x.value()); DataWord y = new DataWord(two);// System.out.println(y.value()); y.mod(x); assertEquals(32, y.getData().length); assertEquals(expected, Hex.toHexString(y.getData())); } - + @Test public void testMul() { byte[] one = new byte[32]; @@ -106,10 +106,10 @@ public class DataWordTest { assertEquals(32, y.getData().length); assertEquals("0000000000000000000000010000000000000000000000000000000000000000", Hex.toHexString(y.getData())); } - + @Test public void testMulOverflow() { - + byte[] one = new byte[32]; one[30] = 0x1; // 0x0000000000000000000000000000000000000000000000000000000000000100 @@ -122,19 +122,19 @@ public class DataWordTest { assertEquals(32, y.getData().length); assertEquals("0100000000000000000000000000000000000000000000000000000000000000", Hex.toHexString(y.getData())); } - + @Test public void testPow() { - + BigInteger x = BigInteger.valueOf(Integer.MAX_VALUE); BigInteger y = BigInteger.valueOf(1000); - + BigInteger result1 = x.modPow(x, y); BigInteger result2 = pow(x, y); System.out.println(result1); System.out.println(result2); } - + @Test public void testSignExtend1() { @@ -238,7 +238,7 @@ public class DataWordTest { x.signExtend(k); // should throw an exception } - + @Test(expected=IndexOutOfBoundsException.class) public void testSignExtendException2() { @@ -247,7 +247,7 @@ public class DataWordTest { x.signExtend(k); // should throw an exception } - + public static BigInteger pow(BigInteger x, BigInteger y) { if (y.compareTo(BigInteger.ZERO) < 0) throw new IllegalArgumentException(); @@ -268,5 +268,5 @@ public class DataWordTest { } return result; } - + } 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 2b556adc..044984a1 100644 --- a/ethereumj-core/src/test/java/test/ethereum/vm/ProgramMemoryTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/vm/ProgramMemoryTest.java @@ -16,12 +16,12 @@ public class ProgramMemoryTest { ProgramInvokeMockImpl pi = null; Program program; ByteBuffer memory; - + @Before public void createProgram() { program = new Program(ByteUtil.EMPTY_BYTE_ARRAY, pi); } - + @Test public void testGetMemSize() { ByteBuffer memory = ByteBuffer.allocate(64); @@ -49,7 +49,7 @@ public class ProgramMemoryTest { program.memoryChunk(offset, size); assertEquals(160, program.getMemSize()); } - + @Test // size 0 doesn't increate memory public void testMemoryChunk2() { program.initMem(ByteBuffer.allocate(64)); @@ -68,7 +68,7 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(64, program.getMemSize()); } - + @Test public void testAllocateMemory2() { @@ -80,7 +80,7 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(96, program.getMemSize()); } - + @Test public void testAllocateMemory3() { @@ -91,7 +91,7 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(64, program.getMemSize()); } - + @Test public void testAllocateMemory4() { @@ -101,7 +101,7 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(64, program.getMemSize()); } - + @Test public void testAllocateMemory5() { @@ -111,7 +111,7 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(64, program.getMemSize()); } - + @Test public void testAllocateMemory6() { @@ -122,7 +122,7 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(96, program.getMemSize()); } - + @Test public void testAllocateMemory7() { @@ -133,7 +133,7 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(128, program.getMemSize()); } - + @Test public void testAllocateMemory8() { @@ -143,7 +143,7 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(96, program.getMemSize()); } - + @Test public void testAllocateMemory9() { @@ -155,10 +155,10 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(64, program.getMemSize()); } - + /************************************************/ - - + + @Test public void testAllocateMemory10() { @@ -168,7 +168,7 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(0, program.getMemSize()); } - + @Test public void testAllocateMemory11() { @@ -178,7 +178,7 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(32, program.getMemSize()); } - + @Test public void testAllocateMemory12() { @@ -189,7 +189,7 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(160, program.getMemSize()); } - + @Test public void testAllocateMemory13() { @@ -200,7 +200,7 @@ public class ProgramMemoryTest { program.allocateMemory(offset, size); assertEquals(160, program.getMemSize()); } - + @Test public void testAllocateMemory14() { @@ -249,73 +249,73 @@ public class ProgramMemoryTest { @Test public void testAllocateMemoryUnrounded1() { - // memory unrounded + // memory unrounded program.initMem(ByteBuffer.allocate(64)); int offset = 64; int size = 32; program.allocateMemory(offset, size); assertEquals(96, program.getMemSize()); } - + @Test public void testAllocateMemoryUnrounded2() { - // offset unrounded + // offset unrounded program.initMem(ByteBuffer.allocate(64)); int offset = 16; int size = 32; program.allocateMemory(offset, size); assertEquals(64, program.getMemSize()); } - + @Test public void testAllocateMemoryUnrounded3() { - // size unrounded + // size unrounded program.initMem(ByteBuffer.allocate(64)); int offset = 64; int size = 16; program.allocateMemory(offset, size); assertEquals(96, program.getMemSize()); } - + @Test public void testAllocateMemoryUnrounded4() { - // memory + offset unrounded + // memory + offset unrounded program.initMem(ByteBuffer.allocate(64)); int offset = 16; int size = 32; program.allocateMemory(offset, size); assertEquals(64 , program.getMemSize()); } - + @Test public void testAllocateMemoryUnrounded5() { - // memory + size unrounded + // memory + size unrounded program.initMem(ByteBuffer.allocate(64)); int offset = 32; int size = 16; program.allocateMemory(offset, size); assertEquals(64, program.getMemSize()); } - + @Test public void testAllocateMemoryUnrounded6() { - // offset + size unrounded + // offset + size unrounded program.initMem(ByteBuffer.allocate(32)); int offset = 16; int size = 16; program.allocateMemory(offset, size); assertEquals(32, program.getMemSize()); } - + @Test public void testAllocateMemoryUnrounded7() { - // memory + offset + size unrounded + // memory + offset + size unrounded program.initMem(ByteBuffer.allocate(32)); int offset = 16; int size = 16; 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 2afb105d..27d0f4e6 100644 --- a/ethereumj-core/src/test/java/test/ethereum/vm/VMComplexTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/vm/VMComplexTest.java @@ -32,11 +32,11 @@ public class VMComplexTest { /** * #The code will run * ------------------ - + a = contract.storage[999] if a > 0: contract.storage[999] = a - 1 - + # call to contract: 77045e71a7a2c50903d88e564cd72fab11e82051 send((tx.gas / 10 * 8), 0x77045e71a7a2c50903d88e564cd72fab11e82051, 0) else: @@ -338,13 +338,13 @@ public class VMComplexTest { // TODO: check that the value pushed after exec is the new address repository.close(); } - + @Test // CALL contract with too much gas @Ignore public void test5() { // TODO CALL contract with gas > gasRemaining && gas > Long.MAX_VALUE } - + @Test // contractB call itself with code from contractA public void test6() { /** @@ -353,13 +353,13 @@ public class VMComplexTest { contract A: 945304eb96065b2a98b57a48a06ae28d285a71b5 --------------- - - PUSH1 0 CALLDATALOAD SLOAD NOT PUSH1 9 JUMPI STOP + + PUSH1 0 CALLDATALOAD SLOAD NOT PUSH1 9 JUMPI STOP PUSH1 32 CALLDATALOAD PUSH1 0 CALLDATALOAD SSTORE contract B: 0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6 ----------- - { (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) + { (MSTORE 0 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) (MSTORE 32 0xaaffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffaa) [[ 0 ]] (CALLSTATELESS 1000000 0x945304eb96065b2a98b57a48a06ae28d285a71b5 23 0 64 64 0) } @@ -377,7 +377,7 @@ public class VMComplexTest { ProgramInvokeMockImpl pi = new ProgramInvokeMockImpl(); pi.setOwnerAddress(contractB_addr_bytes); pi.setGasLimit(10000000000000l); - + Repository repository = pi.getRepository(); repository.createAccount(contractA_addr_bytes); repository.saveCode(contractA_addr_bytes, codeA); 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 9c3f5e1b..c58908df 100644 --- a/ethereumj-core/src/test/java/test/ethereum/vm/VMCustomTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/vm/VMCustomTest.java @@ -25,10 +25,10 @@ import static org.junit.Assert.*; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class VMCustomTest { - + private ProgramInvokeMockImpl invoke; private Program program; - + @Before public void setup() { byte[] ownerAddress = Hex.decode("77045E71A7A2C50903D88E564CD72FAB11E82051"); @@ -41,12 +41,12 @@ public class VMCustomTest { invoke.getRepository().createAccount(ownerAddress); invoke.getRepository().addBalance(ownerAddress, BigInteger.valueOf(1000L)); } - + @After public void tearDown() { invoke.getRepository().close(); } - + @Test // CALLDATASIZE OP public void testCALLDATASIZE_1() { @@ -65,7 +65,7 @@ public class VMCustomTest { public void testCALLDATALOAD_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("600035"), invoke); String s_expected_1 = "00000000000000000000000000000000000000000000000000000000000000A1"; @@ -80,7 +80,7 @@ public class VMCustomTest { public void testCALLDATALOAD_2() { VM vm = new VM(); - program = + program = new Program(Hex.decode("600235"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000A10000"; @@ -96,7 +96,7 @@ public class VMCustomTest { public void testCALLDATALOAD_3() { VM vm = new VM(); - program = + program = new Program(Hex.decode("602035"), invoke); String s_expected_1 = "00000000000000000000000000000000000000000000000000000000000000B1"; @@ -112,7 +112,7 @@ public class VMCustomTest { public void testCALLDATALOAD_4() { VM vm = new VM(); - program = + program = new Program(Hex.decode("602335"), invoke); String s_expected_1 = "00000000000000000000000000000000000000000000000000000000B1000000"; @@ -127,7 +127,7 @@ public class VMCustomTest { public void testCALLDATALOAD_5() { VM vm = new VM(); - program = + program = new Program(Hex.decode("603F35"), invoke); String s_expected_1 = "B100000000000000000000000000000000000000000000000000000000000000"; @@ -142,7 +142,7 @@ public class VMCustomTest { public void testCALLDATALOAD_6() { VM vm = new VM(); - program = + program = new Program(Hex.decode("35"), invoke); try { vm.step(program); @@ -155,7 +155,7 @@ public class VMCustomTest { public void testCALLDATACOPY_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("60206000600037"), invoke); String m_expected = "00000000000000000000000000000000000000000000000000000000000000A1"; @@ -171,7 +171,7 @@ public class VMCustomTest { public void testCALLDATACOPY_2() { VM vm = new VM(); - program = + program = new Program(Hex.decode("60406000600037"), invoke); String m_expected = "00000000000000000000000000000000000000000000000000000000000000A1" + "00000000000000000000000000000000000000000000000000000000000000B1"; @@ -189,7 +189,7 @@ public class VMCustomTest { public void testCALLDATACOPY_3() { VM vm = new VM(); - program = + program = new Program(Hex.decode("60406004600037"), invoke); String m_expected = "000000000000000000000000000000000000000000000000000000A100000000" + "000000000000000000000000000000000000000000000000000000B100000000"; @@ -207,7 +207,7 @@ public class VMCustomTest { public void testCALLDATACOPY_4() { VM vm = new VM(); - program = + program = new Program(Hex.decode("60406000600437"), invoke); String m_expected = "0000000000000000000000000000000000000000000000000000000000000000" + "000000A100000000000000000000000000000000000000000000000000000000" + @@ -225,7 +225,7 @@ public class VMCustomTest { public void testCALLDATACOPY_5() { VM vm = new VM(); - program = + program = new Program(Hex.decode("60406000600437"), invoke); String m_expected = "0000000000000000000000000000000000000000000000000000000000000000" + "000000A100000000000000000000000000000000000000000000000000000000" + @@ -244,7 +244,7 @@ public class VMCustomTest { public void testCALLDATACOPY_6() { VM vm = new VM(); - program = + program = new Program(Hex.decode("6040600037"), invoke); try { @@ -260,7 +260,7 @@ public class VMCustomTest { public void testCALLDATACOPY_7() { VM vm = new VM(); - program = + program = new Program(Hex.decode("6020600073CC0929EB16730E7C14FEFC63006AC2D794C5795637"), invoke); try { @@ -272,7 +272,7 @@ public class VMCustomTest { assertTrue(program.isStopped()); } } - + @Test // ADDRESS OP public void testADDRESS_1() { @@ -291,7 +291,7 @@ public class VMCustomTest { public void testBALANCE_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("3031"), invoke); String s_expected_1 = "00000000000000000000000000000000000000000000000000000000000003E8"; @@ -306,7 +306,7 @@ public class VMCustomTest { public void testORIGIN_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("32"), invoke); String s_expected_1 = "00000000000000000000000013978AEE95F38490E9769C39B2773ED763D9CD5F"; @@ -320,7 +320,7 @@ public class VMCustomTest { public void testCALLER_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("33"), invoke); String s_expected_1 = "000000000000000000000000885F93EED577F2FC341EBB9A5C9B2CE4465D96C4"; @@ -334,7 +334,7 @@ public class VMCustomTest { public void testCALLVALUE_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("34"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000DE0B6B3A7640000"; @@ -348,7 +348,7 @@ public class VMCustomTest { public void testSHA3_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("60016000536001600020"), invoke); String s_expected_1 = "5FE7F977E71DBA2EA1A68E21057BEEBB9BE2AC30C6410AA38D4F3FBE41DCFFD2"; @@ -367,7 +367,7 @@ public class VMCustomTest { public void testSHA3_2() { VM vm = new VM(); - program = + program = new Program(Hex.decode("6102016000526002601E20"), invoke); String s_expected_1 = "114A3FE82A0219FCC31ABD15617966A125F12B0FD3409105FC83B487A9D82DE4"; @@ -386,7 +386,7 @@ public class VMCustomTest { public void testSHA3_3() { VM vm = new VM(); - program = + program = new Program(Hex.decode("610201600052600220"), invoke); try { vm.step(program); @@ -403,7 +403,7 @@ public class VMCustomTest { public void testPREVHASH_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("40"), invoke); String s_expected_1 = "961CB117ABA86D1E596854015A1483323F18883C2D745B0BC03E87F146D2BB1C"; @@ -417,7 +417,7 @@ public class VMCustomTest { public void testCOINBASE_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("41"), invoke); String s_expected_1 = "000000000000000000000000E559DE5527492BCB42EC68D07DF0742A98EC3F1E"; @@ -431,7 +431,7 @@ public class VMCustomTest { public void testTIMESTAMP_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("42"), invoke); String s_expected_1 = "000000000000000000000000000000000000000000000000000000005387FE24"; @@ -445,7 +445,7 @@ public class VMCustomTest { public void testNUMBER_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("43"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000021"; @@ -459,7 +459,7 @@ public class VMCustomTest { public void testDIFFICULTY_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("44"), invoke); String s_expected_1 = "00000000000000000000000000000000000000000000000000000000003ED290"; @@ -473,7 +473,7 @@ public class VMCustomTest { public void testGASPRICE_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("3A"), invoke); String s_expected_1 = "000000000000000000000000000000000000000000000000000009184E72A000"; @@ -487,7 +487,7 @@ public class VMCustomTest { public void testGAS_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("5A"), invoke); String s_expected_1 = "00000000000000000000000000000000000000000000000000000000000F423F"; @@ -501,7 +501,7 @@ public class VMCustomTest { public void testGASLIMIT_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("45"), invoke); String s_expected_1 = "00000000000000000000000000000000000000000000000000000000000F4240"; @@ -510,7 +510,7 @@ public class VMCustomTest { DataWord item1 = program.stackPop(); assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - + @Test(expected=Program.IllegalOperationException.class) // INVALID OP public void testINVALID_1() { @@ -525,7 +525,7 @@ public class VMCustomTest { assertTrue(program.isStopped()); DataWord item1 = program.stackPop(); assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); - } + } } /* TEST CASE LIST END */ 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 506ced6f..daa5ed62 100644 --- a/ethereumj-core/src/test/java/test/ethereum/vm/VMTest.java +++ b/ethereumj-core/src/test/java/test/ethereum/vm/VMTest.java @@ -25,20 +25,20 @@ import static org.junit.Assert.*; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class VMTest { - + private ProgramInvokeMockImpl invoke; private Program program; - + @Before public void setup() { invoke = new ProgramInvokeMockImpl(); } - + @After public void tearDown() { invoke.getRepository().close(); } - + @Test // PUSH1 OP public void testPUSH1() { @@ -1109,10 +1109,10 @@ public class VMTest { testDUPN_1(i); } } - + /** * Generic test function for DUP1-16 - * + * * @param n in DUPn */ private void testDUPN_1(int n) { @@ -1150,17 +1150,17 @@ public class VMTest { assertTrue(program.isStopped()); } } - + @Test // SWAP1...SWAP16 OP public void testSWAPS() { for (int i = 1; i < 17; i++) { testSWAPN_1(i); } } - + /** * Generic test function for SWAP1-16 - * + * * @param n in SWAPn */ private void testSWAPN_1(int n) { @@ -1178,7 +1178,7 @@ public class VMTest { for (int i = 0; i <= expected.length; i++) { vm.step(program); } - + 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--) { @@ -1803,38 +1803,38 @@ public class VMTest { assertTrue(program.isStopped()); } } - + @Test // JUMPDEST OP for JUMP public void testJUMPDEST_1() { VM vm = new VM(); program = new Program(Hex.decode("602360085660015b600255"), invoke); - + String s_expected_key = "0000000000000000000000000000000000000000000000000000000000000002"; String s_expected_val = "0000000000000000000000000000000000000000000000000000000000000023"; - + vm.step(program); vm.step(program); vm.step(program); vm.step(program); vm.step(program); - + DataWord key = new DataWord(Hex.decode(s_expected_key)); DataWord val = program.getResult().getRepository().getStorageValue(invoke.getOwnerAddress().getNoLeadZeroesData(), key); - + assertTrue(program.isStopped()); assertEquals(s_expected_val, Hex.toHexString(val.getData()).toUpperCase()); } - + @Test // JUMPDEST OP for JUMPI public void testJUMPDEST_2() { VM vm = new VM(); program = new Program(Hex.decode("6023600160095760015b600255"), invoke); - + String s_expected_key = "0000000000000000000000000000000000000000000000000000000000000002"; String s_expected_val = "0000000000000000000000000000000000000000000000000000000000000023"; - + vm.step(program); vm.step(program); vm.step(program); @@ -1845,7 +1845,7 @@ public class VMTest { DataWord key = new DataWord(Hex.decode(s_expected_key)); DataWord val = program.getResult().getRepository().getStorageValue(invoke.getOwnerAddress().getNoLeadZeroesData(), key); - + assertTrue(program.isStopped()); assertEquals(s_expected_val, Hex.toHexString(val.getData()).toUpperCase()); } @@ -1907,7 +1907,7 @@ public class VMTest { assertTrue(program.isStopped()); } } - + @Test // ADDMOD OP mal public void testADDMOD_1() { VM vm = new VM(); @@ -2025,7 +2025,7 @@ public class VMTest { assertTrue(program.isStopped()); } } - + @Test // MULMOD OP public void testMULMOD_1() { VM vm = new VM(); @@ -2446,7 +2446,7 @@ public class VMTest { public void testRETURN_3() { VM vm = new VM(); - program = + program = new Program(Hex.decode("7FA0B0C0D0E0F0A1B1C1D1E1F1A2B2C2D2E2F2A3B3C3D3E3F3A4B4C4D4E4F4A1B160005260206000F3"), invoke); String s_expected_1 = "A0B0C0D0E0F0A1B1C1D1E1F1A2B2C2D2E2F2A3B3C3D3E3F3A4B4C4D4E4F4A1B1"; @@ -2467,7 +2467,7 @@ public class VMTest { public void testRETURN_4() { VM vm = new VM(); - program = + program = new Program(Hex.decode("7FA0B0C0D0E0F0A1B1C1D1E1F1A2B2C2D2E2F2A3B3C3D3E3F3A4B4C4D4E4F4A1B160005260206010F3"), invoke); String s_expected_1 = "E2F2A3B3C3D3E3F3A4B4C4D4E4F4A1B100000000000000000000000000000000"; @@ -2488,7 +2488,7 @@ public class VMTest { public void testCODECOPY_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("60036007600039123456"), invoke); String m_expected_1 = "1234560000000000000000000000000000000000000000000000000000000000"; @@ -2506,7 +2506,7 @@ public class VMTest { public void testCODECOPY_2() { VM vm = new VM(); - program = + program = new Program(Hex.decode("605E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235602054"), invoke); String m_expected_1 = "6000605F556014600054601E60205463ABCDDCBA6040545B51602001600A5254516040016014525451606001601E5254516080016028525460A052546016604860003960166000F26000603F556103E756600054600053602002356020540000"; @@ -2529,7 +2529,7 @@ public class VMTest { // 95 - new bytes allocated VM vm = new VM(); - program = + program = new Program(Hex.decode("605E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235"), invoke); @@ -2545,7 +2545,7 @@ public class VMTest { public void testCODECOPY_4() { VM vm = new VM(); - program = + program = new Program(Hex.decode("605E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e756600054600053602002351234"), invoke); @@ -2562,7 +2562,7 @@ public class VMTest { public void testCODECOPY_5() { VM vm = new VM(); - program = + program = new Program(Hex.decode("611234600054615566602054607060006020396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e756600054600053602002351234"), invoke); @@ -2585,7 +2585,7 @@ public class VMTest { public void testCODECOPY_6() { VM vm = new VM(); - program = + program = new Program(Hex.decode("605E6007396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e756600054600053602002351234"), invoke); try { @@ -2601,7 +2601,7 @@ public class VMTest { public void testEXTCODECOPY_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("60036007600073471FD3AD3E9EEADEEC4608B92D16CE6B500704CC3C123456"), invoke); String m_expected_1 = "6000600000000000000000000000000000000000000000000000000000000000"; @@ -2610,7 +2610,7 @@ public class VMTest { vm.step(program); vm.step(program); vm.step(program); - + assertEquals(m_expected_1, Hex.toHexString(program.getMemory().array()).toUpperCase()); } @@ -2618,7 +2618,7 @@ public class VMTest { public void testEXTCODECOPY_2() { VM vm = new VM(); - program = + program = new Program(Hex.decode("603E6007600073471FD3AD3E9EEADEEC4608B92D16CE6B500704CC3C6000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235602054"), invoke); String m_expected_1 = "6000605F556014600054601E60205463ABCDDCBA6040545B51602001600A5254516040016014525451606001601E5254516080016028525460A0525460160000"; @@ -2635,7 +2635,7 @@ public class VMTest { @Test // EXTCODECOPY OP public void testEXTCODECOPY_3() { VM vm = new VM(); - program = + program = new Program(Hex.decode("605E6007600073471FD3AD3E9EEADEEC4608B92D16CE6B500704CC3C6000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235"), invoke); @@ -2653,7 +2653,7 @@ public class VMTest { @Test // EXTCODECOPY OP public void testEXTCODECOPY_4() { VM vm = new VM(); - program = + program = new Program(Hex.decode("611234600054615566602054603E6000602073471FD3AD3E9EEADEEC4608B92D16CE6B500704CC3C6000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e756600054600053602002351234"), invoke); @@ -2676,7 +2676,7 @@ public class VMTest { @Test(expected=StackTooSmallException.class) // EXTCODECOPY OP mal public void testEXTCODECOPY_5() { VM vm = new VM(); - program = + program = new Program(Hex.decode("605E600773471FD3AD3E9EEADEEC4608B92D16CE6B500704CC3C"), invoke); try { @@ -2694,7 +2694,7 @@ public class VMTest { public void testCODESIZE_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("385E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000062"; @@ -2704,11 +2704,11 @@ public class VMTest { DataWord item1 = program.stackPop(); assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - + @Test // EXTCODESIZE OP public void testEXTCODESIZE_1() { VM vm = new VM(); - program = + program = new Program(Hex.decode("73471FD3AD3E9EEADEEC4608B92D16CE6B500704CC395E60076000396000605f556014600054601e60205463abcddcba6040545b51602001600a5254516040016014525451606001601e5254516080016028525460a052546016604860003960166000f26000603f556103e75660005460005360200235"), invoke); // Push address on the stack and perform EXTCODECOPY String s_expected_1 = "000000000000000000000000471FD3AD3E9EEADEEC4608B92D16CE6B500704CC"; @@ -2718,13 +2718,13 @@ public class VMTest { DataWord item1 = program.stackPop(); assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - + @Test // MOD OP public void testMOD_1() { VM vm = new VM(); program = new Program(Hex.decode("6003600406"), invoke); String s_expected_1 = "0000000000000000000000000000000000000000000000000000000000000001"; - + vm.step(program); vm.step(program); vm.step(program); @@ -2821,7 +2821,7 @@ public class VMTest { DataWord item1 = program.stackPop(); assertEquals(s_expected_1, Hex.toHexString(item1.getData()).toUpperCase()); } - + @Test(expected=StackTooSmallException.class) // SMOD OP mal public void testSMOD_4() { VM vm = new VM(); diff --git a/ethereumj-core/src/test/resources/system.properties b/ethereumj-core/src/test/resources/system.properties index c1334252..7275d231 100644 --- a/ethereumj-core/src/test/resources/system.properties +++ b/ethereumj-core/src/test/resources/system.properties @@ -7,7 +7,7 @@ server.acceptConnections = false # values: [ip:port, ip:port, ip:port ...] peer.discovery.ip.list = poc-6.ethdev.com:30303,\ 54.204.10.41:30303 - + # Peer Server Zero (poc-6.ethdev.com) peer.active.ip = 207.12.89.101 peer.active.port = 30303 @@ -44,7 +44,7 @@ peer.connection.timeout = 2 transaction.approve.timeout = 3 # the parameter specifies how much -# time we will wait for a message +# time we will wait for a message # to come before closing the channel peer.channel.read.timeout = 15 @@ -54,8 +54,8 @@ peer.channel.read.timeout = 15 samples.dir = samples # everytime the application starts -# the existing database will be -# destroyed and all the data will be +# the existing database will be +# destroyed and all the data will be # downloaded from peers again database.reset = true diff --git a/ethereumj-core/track-untrack-local.bat b/ethereumj-core/track-untrack-local.bat index 3f147963..dba98252 100644 --- a/ethereumj-core/track-untrack-local.bat +++ b/ethereumj-core/track-untrack-local.bat @@ -5,14 +5,14 @@ rem * @echo off :getConfirmation -set /p command=What to do with lame properties [track/untrack] ?: +set /p command=What to do with lame properties [track/untrack] ?: if %command%==track goto :trackProps if %command%==untrack goto :untrackProps goto :end -rem # I use this to stop push every local propertie change +rem # I use this to stop push every local propertie change :untrackProps @echo on git update-index --assume-unchanged ./src/main/resources/log4j.properties diff --git a/ethereumj-studio/README.md b/ethereumj-studio/README.md index 083021fa..8ac1bd2b 100644 --- a/ethereumj-studio/README.md +++ b/ethereumj-studio/README.md @@ -3,10 +3,10 @@ 1. build_1: [a full application package] : ~> ` mvn clean package ` -. -. -. -[![ScreenShot](http://i.imgur.com/FQiBihl.jpg)](https://www.youtube.com/watch?v=D5ok7jh7AOg) -. -. -. +. +. +. +[![ScreenShot](http://i.imgur.com/FQiBihl.jpg)](https://www.youtube.com/watch?v=D5ok7jh7AOg) +. +. +. diff --git a/ethereumj-studio/pom.xml b/ethereumj-studio/pom.xml index b5683568..685d019b 100644 --- a/ethereumj-studio/pom.xml +++ b/ethereumj-studio/pom.xml @@ -315,5 +315,5 @@ - + diff --git a/ethereumj-studio/samples/call-me-more.se b/ethereumj-studio/samples/call-me-more.se index 9308a5cb..8986c471 100644 --- a/ethereumj-studio/samples/call-me-more.se +++ b/ethereumj-studio/samples/call-me-more.se @@ -1,6 +1,6 @@ -init: +init: // Setting the storage value contract.storage[999] = 3 @@ -9,11 +9,11 @@ code: // Using the storage on the call a = contract.storage[999] - - if a > 0: + + if a > 0: contract.storage[999] = a - 1 // call to myself: send((tx.gas/10 * 8), contract.address, 0) - else: - stop \ No newline at end of file + else: + stop \ No newline at end of file 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 9734e5e2..3215c974 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/geo/IpGeoDB.java +++ b/ethereumj-studio/src/main/java/org/ethereum/geo/IpGeoDB.java @@ -17,7 +17,7 @@ import java.net.URL; public class IpGeoDB { // change private static Logger logger = LoggerFactory.getLogger(IpGeoDB.class); - + static { try { File file = null; 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 dfdf095f..878a9b91 100755 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/AccountsListWindow.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/AccountsListWindow.java @@ -22,10 +22,10 @@ import org.spongycastle.util.Arrays; import org.spongycastle.util.encoders.Hex; public class AccountsListWindow extends JFrame { - + private JTable tblAccountsDataTable; private AccountsDataAdapter adapter; - + public AccountsListWindow() { java.net.URL url = ClassLoader.getSystemResource("ethereum-icon.png"); Toolkit kit = Toolkit.getDefaultToolkit(); @@ -35,25 +35,25 @@ public class AccountsListWindow extends JFrame { setSize(700, 500); setLocation(50, 180); setResizable(false); - + JPanel panel = new JPanel(); getContentPane().add(panel); - + tblAccountsDataTable = new JTable(); - + adapter = new AccountsDataAdapter(new ArrayList()); tblAccountsDataTable.setModel(adapter); - + JScrollPane scrollPane = new JScrollPane(tblAccountsDataTable); scrollPane.setPreferredSize(new Dimension(680,490)); panel.add(scrollPane); - + loadAccounts(); } - + private void loadAccounts() { new Thread(){ - + @Override public void run(){ Repository repository = UIEthereumManager.ethereum.getRepository(); @@ -61,25 +61,25 @@ public class AccountsListWindow extends JFrame { while(i.hasNext()) { DataClass dc = new DataClass(); dc.address = i.next().getKey(); - + AccountState state = repository.getAccountState(dc.address); dc.accountState = state; - + adapter.addDataPiece(dc); } } }.start(); } - + private class AccountsDataAdapter extends AbstractTableModel { List data; - + final String[] columns = new String[]{ "Account", "Balance", "Is Contract"}; - + public AccountsDataAdapter(List data) { this.data = data; } - + public void addDataPiece(DataClass d) { data.add(d); this.fireTableRowsInserted(Math.min(data.size() - 2, 0), data.size() - 1); @@ -94,12 +94,12 @@ public class AccountsListWindow extends JFrame { public int getColumnCount() { return 3; } - + @Override public String getColumnName(int column) { return columns[column]; } - + @Override public boolean isCellEditable(int row, int column) { // custom isCellEditable function return column == 0? true:false; @@ -125,7 +125,7 @@ public class AccountsListWindow extends JFrame { } } } - + private class DataClass { public byte[] address; public AccountState accountState; 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 943fac5f..b9b1ff9c 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/ConsoleTokenMaker.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/ConsoleTokenMaker.java @@ -14,7 +14,7 @@ import org.slf4j.LoggerFactory; * Created on: 24/04/14 11:52 */ public class ConsoleTokenMaker extends AbstractTokenMaker { - + private Logger logger = LoggerFactory.getLogger("gui"); protected final String operators = "+-*/%!=<>^&|?:"; 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 552989eb..41ed0078 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/ContractCallDialog.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/ContractCallDialog.java @@ -213,7 +213,7 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { this.getContentPane().revalidate(); this.getContentPane().repaint(); this.setResizable(false); - + this.setVisible(true); } @@ -223,7 +223,7 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { alertStatusMsg("Not a valid contract address"); return; } - + ContractDetails contractDetails = UIEthereumManager.ethereum .getRepository().getContractDetails(addr); if (contractDetails == null) { @@ -236,7 +236,7 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { alertStatusMsg("Such account exist but no code in the db"); return; } - + final Map storageMap = contractDetails.getStorage(); contractDataInput.setBounds(70, 80, 350, 145); @@ -307,14 +307,14 @@ class ContractCallDialog extends JDialog implements MessageAwareDialog { }); this.repaint(); } - - private void playContractCall() { + + private void playContractCall() { byte[] addr = Utils.addressStringToBytes(contractAddrInput.getText()); if(addr == null) { alertStatusMsg("Not a valid contract address"); return; } - + ContractDetails contractDetails = UIEthereumManager.ethereum .getRepository().getContractDetails(addr); if (contractDetails == null) { 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 7cd43102..dcebc5d1 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/ContractSubmitDialog.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/ContractSubmitDialog.java @@ -25,7 +25,7 @@ import java.util.Collection; class ContractSubmitDialog extends JDialog implements MessageAwareDialog { private static final long serialVersionUID = -3622984456084608996L; - + ContractSubmitDialog dialog; JComboBox creatorAddressCombo; final JTextField gasInput; @@ -194,7 +194,7 @@ class ContractSubmitDialog extends JDialog implements MessageAwareDialog { for (int i = 0; i < creatorAddressCombo.getComponentCount(); i++) { if (creatorAddressCombo.getComponent(i) instanceof CellRendererPane) { - CellRendererPane crp = ((CellRendererPane) + CellRendererPane crp = ((CellRendererPane) (creatorAddressCombo.getComponent(i))); } if (creatorAddressCombo.getComponent(i) instanceof AbstractButton) { @@ -207,7 +207,7 @@ class ContractSubmitDialog extends JDialog implements MessageAwareDialog { this.getContentPane().revalidate(); this.getContentPane().repaint(); this.setResizable(false); - + this.setVisible(true); } diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/MessageAwareDialog.java b/ethereumj-studio/src/main/java/org/ethereum/gui/MessageAwareDialog.java index 00714af3..e8f6353b 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/MessageAwareDialog.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/MessageAwareDialog.java @@ -1,7 +1,7 @@ package org.ethereum.gui; /** - * This interface describes the methods required + * This interface describes the methods required * for any dialog that displays info- and alert status messages. */ public interface MessageAwareDialog { 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 e792ab67..b0e3e70d 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/PayOutDialog.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/PayOutDialog.java @@ -241,7 +241,7 @@ class PayOutDialog extends JDialog implements MessageAwareDialog { setVisible(true); } }); - + return rootPane; } diff --git a/ethereumj-studio/src/main/java/org/ethereum/gui/PeerInfoWindow.java b/ethereumj-studio/src/main/java/org/ethereum/gui/PeerInfoWindow.java index 6c0b195a..8c33051d 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/PeerInfoWindow.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/PeerInfoWindow.java @@ -66,10 +66,10 @@ public class PeerInfoWindow extends JFrame { // setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); setLocation(802, 460); - + if (CONFIG.peerDiscovery()) UIEthereumManager.ethereum.startPeerDiscovery(); - + } 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 4df5056e..37350968 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/PeersTableModel.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/PeersTableModel.java @@ -77,7 +77,7 @@ public class PeersTableModel extends AbstractTableModel { } return flagIcon; } - if (column == 1) + if (column == 1) return peerInfo.getIp().getHostAddress(); if (column == 2) { 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 d5aa72e9..56c311b8 100755 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/ProgramPlayDialog.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/ProgramPlayDialog.java @@ -28,21 +28,21 @@ public class ProgramPlayDialog extends JPanel implements ActionListener, private List outputList; private JTextArea console; private JSlider stepSlider; - + private ProgramInvoke pi; - + public ProgramPlayDialog(byte[] code) { this(code, new ProgramInvokeMockImpl()); } - + public ProgramPlayDialog(byte[] code, Transaction tx, Block lastBlock) { // this(code, ProgramInvokeFactory.createProgramInvoke(tx, lastBlock, // UIEthereumManager.ethereum.getRepository())); } - + public ProgramPlayDialog(byte[] code, ProgramInvoke programInvoke) { pi = programInvoke; - + outputList = new ArrayList(); VM vm = new VM(); @@ -56,9 +56,9 @@ public class ProgramPlayDialog extends JPanel implements ActionListener, doGUI(); } - + public void doGUI() { - + setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); //Create the slider. @@ -152,7 +152,7 @@ public class ProgramPlayDialog extends JPanel implements ActionListener, //Add content to the window. frame.add(ppd, BorderLayout.CENTER); - + // close event frame.addWindowListener(new java.awt.event.WindowAdapter() { @Override @@ -169,7 +169,7 @@ public class ProgramPlayDialog extends JPanel implements ActionListener, frame.setVisible(true); ppd.setFocus(); } - + @Override public void output(String out) { 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 0713ae7c..df725c25 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/SerpentEditor.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/SerpentEditor.java @@ -26,7 +26,7 @@ import static org.ethereum.config.SystemProperties.CONFIG; public class SerpentEditor extends JFrame { private Logger logger = LoggerFactory.getLogger("gui"); - + private String codeSample = "\n\n\n" + "" + "if !contract.storage[msg.data[0]]:\n" + 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 6d1194a9..ef1e8713 100755 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/StateExplorerWindow.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/StateExplorerWindow.java @@ -45,21 +45,21 @@ import java.awt.Component; import java.awt.FlowLayout; public class StateExplorerWindow extends JFrame { - + private ToolBar toolBar = null; private JTextField txfAccountAddress; private WindowTextArea txaPrinter; private JButton btnPlayCode; private AccountsListWindow accountsListWindow; ProgramPlayDialog codePanel; - + private JTable tblStateDataTable; private StateDataTableModel dataModel; String[] dataTypes = {"String", "Hex", "Number"}; - + public StateExplorerWindow(ToolBar toolBar) { this.toolBar = toolBar; - + URL url = ClassLoader.getSystemResource("ethereum-icon.png"); Toolkit kit = Toolkit.getDefaultToolkit(); Image img = kit.createImage(url); @@ -68,19 +68,19 @@ public class StateExplorerWindow extends JFrame { setSize(700, 530); setLocation(50, 180); setResizable(false); - + /* - * top search panel + * top search panel */ JPanel panel = new JPanel(); getContentPane().add(panel); - + Box horizontalBox = Box.createHorizontalBox(); panel.add(horizontalBox); - + java.net.URL imageURL = ClassLoader.getSystemResource("buttons/list.png"); ImageIcon image = new ImageIcon(imageURL); - JToggleButton btnListAccounts = new JToggleButton(""); + JToggleButton btnListAccounts = new JToggleButton(""); btnListAccounts.setIcon(image); btnListAccounts.setContentAreaFilled(true); btnListAccounts.setToolTipText("Serpent Editor"); @@ -101,12 +101,12 @@ public class StateExplorerWindow extends JFrame { } }); horizontalBox.add(btnListAccounts); - - + + txfAccountAddress = new JTextField(); horizontalBox.add(txfAccountAddress); txfAccountAddress.setColumns(30); - + JButton btnSearch = new JButton("Search"); horizontalBox.add(btnSearch); btnSearch.addMouseListener(new MouseAdapter(){ @@ -115,9 +115,9 @@ public class StateExplorerWindow extends JFrame { byte[] addr = Utils.addressStringToBytes(txfAccountAddress.getText()); if(addr != null) searchAccount(addr); - } + } }); - + btnPlayCode = new JButton("Play Code"); horizontalBox.add(btnPlayCode); btnPlayCode.addMouseListener(new MouseAdapter(){ @@ -130,25 +130,25 @@ public class StateExplorerWindow extends JFrame { if(code != null) ProgramPlayDialog.createAndShowGUI(code, null, null); } - } + } }); - + /* * center text panel */ JPanel centerPanel = new JPanel(); panel.add(centerPanel); - + txaPrinter = new WindowTextArea(); centerPanel.add(txaPrinter); - + /* * bottom data panel - */ + */ // data type choice boxes Box Hbox = Box.createHorizontalBox(); panel.add(Hbox); - + Box VBox1 = Box.createVerticalBox(); JLabel l1 = new JLabel("Key Encoding"); l1.setAlignmentX(Component.CENTER_ALIGNMENT); @@ -163,7 +163,7 @@ public class StateExplorerWindow extends JFrame { }); VBox1.add(l1); VBox1.add(cmbKey); - + Box VBox2 = Box.createVerticalBox(); VBox2.setAlignmentX(LEFT_ALIGNMENT); JLabel l2 = new JLabel("Value Encoding"); @@ -179,92 +179,92 @@ public class StateExplorerWindow extends JFrame { }); VBox2.add(l2); VBox2.add(cmbValue); - + Hbox.add(VBox1); - + JPanel spacer = new JPanel(); FlowLayout flowLayout = (FlowLayout) spacer.getLayout(); flowLayout.setHgap(100); Hbox.add(spacer); Hbox.add(VBox2); - + // table tblStateDataTable = new JTable(); dataModel = new StateDataTableModel(); tblStateDataTable.setModel(dataModel); - - + + JScrollPane scrollPane = new JScrollPane(tblStateDataTable); scrollPane.setPreferredSize(new Dimension(600,200)); panel.add(scrollPane); } - + 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"; - + //2) print state Repository repository = UIEthereumManager.ethereum.getRepository(); AccountState state = repository.getAccountState(account); if(state != null) ret += state.toString() + "\n"; - + //3) print storage ContractDetails contractDetails = repository.getContractDetails(account); if(contractDetails != null) { Map accountStorage = contractDetails.getStorage(); dataModel.setData(accountStorage); } - + //4) code print byte[] code = repository.getCode(account); if(code != null) { ret += "\n\nCode:\n"; ret += Program.stringify(code, 0, ""); } - + return ret; } - + private class StateDataTableModel extends AbstractTableModel { Map data; DataEncodingType keyEncodingType = DataEncodingType.HEX; DataEncodingType valueEncodingType = DataEncodingType.HEX; String[] columns = new String[]{ "Key", "Value"}; - + public StateDataTableModel() { } - + public StateDataTableModel(Map initData) { setData(initData); } - + public void setData(Map initData) { data = initData; fireTableDataChanged(); } - + public void setKeyEncoding(DataEncodingType type) { keyEncodingType = type; fireTableDataChanged(); } - + public void setValueEncoding(DataEncodingType type) { valueEncodingType = type; fireTableDataChanged(); } - + @Override public String getColumnName(int column) { return columns[column]; } - + @Override public int getRowCount() { return data == null? 0:data.size(); @@ -278,7 +278,7 @@ public class StateExplorerWindow extends JFrame { @Override public Object getValueAt(int rowIndex, int columnIndex) { DataWord key = (DataWord) this.data.keySet().toArray()[rowIndex]; - + if(columnIndex == 0) { return getDataWithEncoding(key.getData(), keyEncodingType); } @@ -287,7 +287,7 @@ public class StateExplorerWindow extends JFrame { return getDataWithEncoding(value.getData(), valueEncodingType); } } - + private String getDataWithEncoding(byte[] data, DataEncodingType enc) { switch(enc) { case STRING: @@ -297,16 +297,16 @@ public class StateExplorerWindow extends JFrame { case NUMBER: return new BigInteger(data).toString(); } - + return data.toString(); } } - + private enum DataEncodingType{ STRING, HEX, NUMBER; - + static public DataEncodingType getTypeFromString(String value) { switch(value){ case "String": @@ -319,22 +319,22 @@ public class StateExplorerWindow extends JFrame { return STRING; } } - + private class WindowTextArea extends TextArea { - + public WindowTextArea() { super(); } - + public void println(String txt) { setText(getText() + txt + "\n"); } - + public void clean() { setText(""); } } - + public static void main(String[] args) { // Start all Swing applications on the EDT. SwingUtilities.invokeLater(new Runnable() { 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 d53b54f5..2e9c6091 100644 --- a/ethereumj-studio/src/main/java/org/ethereum/gui/ToolBar.java +++ b/ethereumj-studio/src/main/java/org/ethereum/gui/ToolBar.java @@ -96,7 +96,7 @@ public class ToolBar extends JFrame { java.net.URL imageURL_5 = ClassLoader.getSystemResource("buttons/wallet.png"); ImageIcon image_5 = new ImageIcon(imageURL_5); - + java.net.URL imageURL_6 = ClassLoader.getSystemResource("buttons/stateExplorer.png"); ImageIcon image_6 = new ImageIcon(imageURL_6); @@ -227,7 +227,7 @@ public class ToolBar extends JFrame { } } ); - + stateExplorer = new JToggleButton(); stateExplorer.setIcon(image_6); stateExplorer.setToolTipText("State Explorer"); diff --git a/ethereumj-studio/src/main/resources/system.properties b/ethereumj-studio/src/main/resources/system.properties index 4e032712..1b89ae78 100644 --- a/ethereumj-studio/src/main/resources/system.properties +++ b/ethereumj-studio/src/main/resources/system.properties @@ -43,7 +43,7 @@ peer.connection.timeout = 2 transaction.approve.timeout = 15 # the parameter specifies how much -# time we will wait for a message +# time we will wait for a message # to come before closing the channel peer.channel.read.timeout = 30 @@ -53,8 +53,8 @@ peer.channel.read.timeout = 30 samples.dir = samples # everytime the application starts -# the existing database will be -# destroyed and all the data will be +# the existing database will be +# destroyed and all the data will be # downloaded from peers again database.reset = true diff --git a/ethereumj-studio/track-untrack-local.bat b/ethereumj-studio/track-untrack-local.bat index 3f147963..dba98252 100644 --- a/ethereumj-studio/track-untrack-local.bat +++ b/ethereumj-studio/track-untrack-local.bat @@ -5,14 +5,14 @@ rem * @echo off :getConfirmation -set /p command=What to do with lame properties [track/untrack] ?: +set /p command=What to do with lame properties [track/untrack] ?: if %command%==track goto :trackProps if %command%==untrack goto :untrackProps goto :end -rem # I use this to stop push every local propertie change +rem # I use this to stop push every local propertie change :untrackProps @echo on git update-index --assume-unchanged ./src/main/resources/log4j.properties