repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/validators/OutputValidator.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite.validators; import org.spongycastle.util.encoders.Hex; import java.util.ArrayList; import java.util.List; import static org.ethereum.jsontestsuite.suite.Utils.parseData; public class OutputValidator { public static List<String> valid(String origOutput, String postOutput){ List<String> results = new ArrayList<>(); if (postOutput.startsWith("#")) { int postLen = Integer.parseInt(postOutput.substring(1)); if (postLen != origOutput.length() / 2) { results.add("Expected output length: " + postLen + ", actual: " + origOutput.length() / 2); } } else { String postOutputFormated = Hex.toHexString(parseData(postOutput)); if (!origOutput.equals(postOutputFormated)) { String formattedString = String.format("HReturn: wrong expected: %s, current: %s", postOutputFormated, origOutput); results.add(formattedString); } } return results; } }
1,868
34.942308
107
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/validators/LogsValidator.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite.validators; import org.ethereum.vm.DataWord; import org.ethereum.vm.LogInfo; import org.spongycastle.util.encoders.Hex; import java.util.ArrayList; import java.util.List; public class LogsValidator { public static List<String> valid(List<LogInfo> origLogs, List<LogInfo> postLogs) { List<String> results = new ArrayList<>(); int i = 0; for (LogInfo postLog : postLogs) { if (origLogs == null || origLogs.size() - 1 < i){ String formattedString = String.format("Log: %s: was expected but doesn't exist: address: %s", i, Hex.toHexString(postLog.getAddress())); results.add(formattedString); continue; } LogInfo realLog = origLogs.get(i); String postAddress = Hex.toHexString(postLog.getAddress()); String realAddress = Hex.toHexString(realLog.getAddress()); if (!postAddress.equals(realAddress)) { String formattedString = String.format("Log: %s: has unexpected address, expected address: %s found address: %s", i, postAddress, realAddress); results.add(formattedString); } String postData = Hex.toHexString(postLog.getData()); String realData = Hex.toHexString(realLog.getData()); if (!postData.equals(realData)) { String formattedString = String.format("Log: %s: has unexpected data, expected data: %s found data: %s", i, postData, realData); results.add(formattedString); } String postBloom = Hex.toHexString(postLog.getBloom().getData()); String realBloom = Hex.toHexString(realLog.getBloom().getData()); if (!postData.equals(realData)) { String formattedString = String.format("Log: %s: has unexpected bloom, expected bloom: %s found bloom: %s", i, postBloom, realBloom); results.add(formattedString); } List<DataWord> postTopics = postLog.getTopics(); List<DataWord> realTopics = realLog.getTopics(); int j = 0; for (DataWord postTopic : postTopics) { DataWord realTopic = realTopics.get(j); if (!postTopic.equals(realTopic)) { String formattedString = String.format("Log: %s: has unexpected topic: %s, expected topic: %s found topic: %s", i, j, postTopic, realTopic); results.add(formattedString); } ++j; } ++i; } return results; } }
3,568
34.69
131
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/runners/StateTestRunner.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite.runners; import org.ethereum.config.BlockchainConfig; import org.ethereum.config.SystemProperties; import org.ethereum.config.net.MainNetConfig; import org.ethereum.core.*; import org.ethereum.db.BlockStoreDummy; import org.ethereum.jsontestsuite.suite.Env; import org.ethereum.jsontestsuite.suite.StateTestCase; import org.ethereum.jsontestsuite.suite.TestProgramInvokeFactory; import org.ethereum.jsontestsuite.suite.builder.BlockBuilder; import org.ethereum.jsontestsuite.suite.builder.EnvBuilder; import org.ethereum.jsontestsuite.suite.builder.LogBuilder; import org.ethereum.jsontestsuite.suite.builder.RepositoryBuilder; import org.ethereum.jsontestsuite.suite.builder.TransactionBuilder; import org.ethereum.jsontestsuite.suite.validators.LogsValidator; import org.ethereum.jsontestsuite.suite.validators.OutputValidator; import org.ethereum.jsontestsuite.suite.validators.RepositoryValidator; import org.ethereum.vm.LogInfo; import org.ethereum.vm.program.ProgramResult; import org.ethereum.vm.program.invoke.ProgramInvokeFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class StateTestRunner { private static Logger logger = LoggerFactory.getLogger("TCK-Test"); public static List<String> run(StateTestCase stateTestCase2) { try { SystemProperties.getDefault().setBlockchainConfig(stateTestCase2.getConfig()); return new StateTestRunner(stateTestCase2).runImpl(); } finally { SystemProperties.getDefault().setBlockchainConfig(MainNetConfig.INSTANCE); } } protected StateTestCase stateTestCase; protected Repository repository; protected Transaction transaction; protected BlockchainImpl blockchain; protected Env env; protected ProgramInvokeFactory invokeFactory; protected Block block; public StateTestRunner(StateTestCase stateTestCase) { this.stateTestCase = stateTestCase; } protected ProgramResult executeTransaction(Transaction tx) { Repository track = repository.startTracking(); TransactionExecutor executor = new TransactionExecutor(transaction, env.getCurrentCoinbase(), track, new BlockStoreDummy(), invokeFactory, blockchain.getBestBlock()); try{ executor.init(); executor.execute(); executor.go(); executor.finalization(); } catch (StackOverflowError soe){ logger.error(" !!! StackOverflowError: update your java run command with -Xss4M !!!"); System.exit(-1); } track.commit(); return executor.getResult(); } public List<String> runImpl() { logger.info(""); repository = RepositoryBuilder.build(stateTestCase.getPre()); logger.info("loaded repository"); transaction = TransactionBuilder.build(stateTestCase.getTransaction()); logger.info("transaction: {}", transaction.toString()); blockchain = new BlockchainImpl(); blockchain.setRepository(repository); env = EnvBuilder.build(stateTestCase.getEnv()); invokeFactory = new TestProgramInvokeFactory(env); block = BlockBuilder.build(env); blockchain.setBestBlock(block); blockchain.setProgramInvokeFactory(invokeFactory); ProgramResult programResult = executeTransaction(transaction); // Tests only case. When: // - coinbase suicided or // - tx is bad so coinbase get no tx fee // we need to manually touch coinbase repository.addBalance(block.getCoinbase(), BigInteger.ZERO); // But ouch, our just touched coinbase could be subject to removal under EIP-161 BlockchainConfig config = SystemProperties.getDefault().getBlockchainConfig().getConfigForBlock(block.getNumber()); if (config.eip161()) { AccountState state = repository.getAccountState(block.getCoinbase()); if (state != null && state.isEmpty()) { repository.delete(block.getCoinbase()); } } repository.commit(); List<LogInfo> origLogs = programResult.getLogInfoList(); List<String> logsResult = stateTestCase.getLogs().compareToReal(origLogs); List<String> results = new ArrayList<>(); if (stateTestCase.getPost() != null) { Repository postRepository = RepositoryBuilder.build(stateTestCase.getPost()); List<String> repoResults = RepositoryValidator.valid(repository, postRepository); results.addAll(repoResults); } else if (stateTestCase.getPostStateRoot() != null) { results.addAll(RepositoryValidator.validRoot( Hex.toHexString(repository.getRoot()), stateTestCase.getPostStateRoot() )); } if (stateTestCase.getOut() != null) { List<String> outputResults = OutputValidator.valid(Hex.toHexString(programResult.getHReturn()), stateTestCase.getOut()); results.addAll(outputResults); } results.addAll(logsResult); logger.info("--------- POST Validation---------"); for (String result : results) { logger.error(result); } logger.info("\n\n"); return results; } }
6,305
36.987952
123
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/runners/TransactionTestRunner.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite.runners; import org.ethereum.config.BlockchainConfig; import org.ethereum.core.Transaction; import org.ethereum.jsontestsuite.suite.TransactionTestCase; import org.ethereum.jsontestsuite.suite.Utils; import org.ethereum.util.ByteUtil; import org.ethereum.util.FastByteComparisons; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class TransactionTestRunner { private static Logger logger = LoggerFactory.getLogger("TCK-Test"); public static List<String> run(TransactionTestCase transactionTestCase2) { return new TransactionTestRunner(transactionTestCase2).runImpl(); } protected TransactionTestCase transactionTestCase; protected Transaction transaction = null; protected byte[] expectedHash; protected byte[] expectedSender; protected long blockNumber; protected BlockchainConfig blockchainConfig; public TransactionTestRunner(TransactionTestCase transactionTestCase) { this.transactionTestCase = transactionTestCase; } public List<String> runImpl() { this.blockNumber = 0; this.blockchainConfig = transactionTestCase.getNetwork().getConfig().getConfigForBlock(blockNumber); try { byte[] rlp = Utils.parseData(transactionTestCase.getRlp()); transaction = new Transaction(rlp); transaction.verify(); } catch (Exception e) { transaction = null; } if (transaction == null || transaction.getEncoded().length < 10000) { logger.info("Transaction: {}", transaction); } else { logger.info("Transaction data skipped because it's too big", transaction); } this.expectedHash = (transactionTestCase.getExpectedHash() != null && !transactionTestCase.getExpectedHash().isEmpty()) ? ByteUtil.hexStringToBytes(transactionTestCase.getExpectedHash()) : null; this.expectedSender = (transactionTestCase.getExpectedRlp() != null && !transactionTestCase.getExpectedRlp().isEmpty()) ? ByteUtil.hexStringToBytes(transactionTestCase.getExpectedRlp()) : null; logger.info("Expected transaction: [hash: {}, sender: {}]", ByteUtil.toHexString(expectedHash), ByteUtil.toHexString(expectedSender)); // Not enough GAS if (transaction != null) { long basicTxCost = blockchainConfig.getTransactionCost(transaction); if (new BigInteger(1, transaction.getGasLimit()).compareTo(BigInteger.valueOf(basicTxCost)) < 0) { transaction = null; } } // Transaction signature verification String acceptFail = null; boolean shouldAccept = transaction != null && blockchainConfig.acceptTransactionSignature(transaction); if (!shouldAccept) transaction = null; if (shouldAccept == (expectedSender == null)) { acceptFail = "Transaction shouldn't be accepted"; } String wrongSender = null; String wrongHash = null; if (transaction != null && expectedHash != null) { // Verifying sender if (!FastByteComparisons.equal(transaction.getSender(), expectedSender)) wrongSender = "Sender is incorrect in parsed transaction"; // Verifying hash // NOTE: "hash" is not required field in test case if (expectedHash != null && !FastByteComparisons.equal(transaction.getHash(), expectedHash)) wrongHash = "Hash is incorrect in parsed transaction"; } List<String> results = new ArrayList<>(); if (acceptFail != null) results.add(acceptFail); if (wrongSender != null) results.add(wrongSender); if (wrongHash != null) results.add(wrongHash); for (String result : results) { logger.error(result); } logger.info("\n\n"); return results; } }
4,883
39.7
127
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/model/BlockHeaderTck.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite.model; public class BlockHeaderTck { String bloom; String coinbase; String difficulty; String extraData; String gasLimit; String gasUsed; String hash; String mixHash; String nonce; String number; String parentHash; String receiptTrie; String seedHash; String stateRoot; String timestamp; String transactionsTrie; String uncleHash; public BlockHeaderTck() { } public String getBloom() { return bloom; } public void setBloom(String bloom) { this.bloom = bloom; } public String getCoinbase() { return coinbase; } public void setCoinbase(String coinbase) { this.coinbase = coinbase; } public String getDifficulty() { return difficulty; } public void setDifficulty(String difficulty) { this.difficulty = difficulty; } public String getExtraData() { return extraData; } public void setExtraData(String extraData) { this.extraData = extraData; } public String getGasLimit() { return gasLimit; } public void setGasLimit(String gasLimit) { this.gasLimit = gasLimit; } public String getGasUsed() { return gasUsed; } public void setGasUsed(String gasUsed) { this.gasUsed = gasUsed; } public String getHash() { return hash; } public void setHash(String hash) { this.hash = hash; } public String getMixHash() { return mixHash; } public void setMixHash(String mixHash) { this.mixHash = mixHash; } public String getNonce() { return nonce; } public void setNonce(String nonce) { this.nonce = nonce; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getParentHash() { return parentHash; } public void setParentHash(String parentHash) { this.parentHash = parentHash; } public String getReceiptTrie() { return receiptTrie; } public void setReceiptTrie(String receiptTrie) { this.receiptTrie = receiptTrie; } public String getSeedHash() { return seedHash; } public void setSeedHash(String seedHash) { this.seedHash = seedHash; } public String getStateRoot() { return stateRoot; } public void setStateRoot(String stateRoot) { this.stateRoot = stateRoot; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getTransactionsTrie() { return transactionsTrie; } public void setTransactionsTrie(String transactionsTrie) { this.transactionsTrie = transactionsTrie; } public String getUncleHash() { return uncleHash; } public void setUncleHash(String uncleHash) { this.uncleHash = uncleHash; } @Override public String toString() { return "BlockHeader{" + "bloom='" + bloom + '\'' + ", coinbase='" + coinbase + '\'' + ", difficulty='" + difficulty + '\'' + ", extraData='" + extraData + '\'' + ", gasLimit='" + gasLimit + '\'' + ", gasUsed='" + gasUsed + '\'' + ", hash='" + hash + '\'' + ", mixHash='" + mixHash + '\'' + ", nonce='" + nonce + '\'' + ", number='" + number + '\'' + ", parentHash='" + parentHash + '\'' + ", receiptTrie='" + receiptTrie + '\'' + ", seedHash='" + seedHash + '\'' + ", stateRoot='" + stateRoot + '\'' + ", timestamp='" + timestamp + '\'' + ", transactionsTrie='" + transactionsTrie + '\'' + ", uncleHash='" + uncleHash + '\'' + '}'; } }
4,899
23.257426
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/model/BlockTck.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class BlockTck { BlockHeaderTck blockHeader; List<TransactionTck> transactions; List<BlockHeaderTck> uncleHeaders; String rlp; String blocknumber; boolean reverted; public BlockTck() { } public String getBlocknumber() { return blocknumber; } public void setBlocknumber(String blocknumber) { this.blocknumber = blocknumber; } public BlockHeaderTck getBlockHeader() { return blockHeader; } public void setBlockHeader(BlockHeaderTck blockHeader) { this.blockHeader = blockHeader; } public String getRlp() { return rlp; } public void setRlp(String rlp) { this.rlp = rlp; } public List<TransactionTck> getTransactions() { return transactions; } public void setTransactions(List<TransactionTck> transactions) { this.transactions = transactions; } public List<BlockHeaderTck> getUncleHeaders() { return uncleHeaders; } public void setUncleHeaders(List<BlockHeaderTck> uncleHeaders) { this.uncleHeaders = uncleHeaders; } public boolean isReverted() { return reverted; } public void setReverted(boolean reverted) { this.reverted = reverted; } @Override public String toString() { return "Block{" + "blockHeader=" + blockHeader + ", transactions=" + transactions + ", uncleHeaders=" + uncleHeaders + ", rlp='" + rlp + '\'' + '}'; } }
2,541
25.479167
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/model/TransactionDataTck.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.List; /** * @author Mikhail Kalinin * @since 09.08.2017 */ @JsonIgnoreProperties(ignoreUnknown = true) public class TransactionDataTck { List<String> data; List<String> gasLimit; String gasPrice; String nonce; String secretKey; String r; String s; String to; String v; List<String> value; public List<String> getData() { return data; } public void setData(List<String> data) { this.data = data; } public List<String> getGasLimit() { return gasLimit; } public void setGasLimit(List<String> gasLimit) { this.gasLimit = gasLimit; } public String getGasPrice() { return gasPrice; } public void setGasPrice(String gasPrice) { this.gasPrice = gasPrice; } public String getNonce() { return nonce; } public void setNonce(String nonce) { this.nonce = nonce; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public List<String> getValue() { return value; } public void setValue(List<String> value) { this.value = value; } public String getR() { return r; } public void setR(String r) { this.r = r; } public String getS() { return s; } public void setS(String s) { this.s = s; } public String getV() { return v; } public void setV(String v) { this.v = v; } public TransactionTck getTransaction(PostDataTck.Indexes idx) { // sanity check if (idx.getValue() >= value.size()) throw new IllegalArgumentException("Fail to get Tx.value by idx: " + idx.getValue()); if (idx.getData() >= data.size()) throw new IllegalArgumentException("Fail to get Tx.data by idx: " + idx.getData()); if (idx.getGas() >= gasLimit.size()) throw new IllegalArgumentException("Fail to get Tx.gasLimit by idx: " + idx.getGas()); TransactionTck tx = new TransactionTck(); tx.setValue(value.get(idx.getValue())); tx.setData(data.get(idx.getData())); tx.setGasLimit(gasLimit.get(idx.getGas())); tx.setGasPrice(gasPrice); tx.setNonce(nonce); tx.setSecretKey(secretKey); tx.setR(r); tx.setS(s); tx.setTo(to); tx.setV(v); return tx; } }
3,500
23.144828
131
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/model/LogTck.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite.model; import java.util.List; public class LogTck { String address; String bloom; String data; List<String> topics; public LogTck() { } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getBloom() { return bloom; } public void setBloom(String bloom) { this.bloom = bloom; } public String getData() { return data; } public void setData(String data) { this.data = data; } public List<String> getTopics() { return topics; } public void setTopics(List<String> topics) { this.topics = topics; } }
1,565
23.46875
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/model/TransactionTck.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite.model; /** * @author Roman Mandeleil * @since 28.06.2014 */ public class TransactionTck { String data; String gasLimit; String gasPrice; String nonce; String r; String s; String to; String v; String value; String secretKey; public TransactionTck() { } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getGasLimit() { return gasLimit; } public void setGasLimit(String gasLimit) { this.gasLimit = gasLimit; } public String getGasPrice() { return gasPrice; } public void setGasPrice(String gasPrice) { this.gasPrice = gasPrice; } public String getNonce() { return nonce; } public void setNonce(String nonce) { this.nonce = nonce; } public String getR() { return r; } public void setR(String r) { this.r = r; } public String getS() { return s; } public void setS(String s) { this.s = s; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getV() { return v; } public void setV(String v) { this.v = v; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } @Override public String toString() { return "TransactionTck{" + "data='" + data + '\'' + ", gasLimit='" + gasLimit + '\'' + ", gasPrice='" + gasPrice + '\'' + ", nonce='" + nonce + '\'' + ", r='" + r + '\'' + ", s='" + s + '\'' + ", to='" + to + '\'' + ", v='" + v + '\'' + ", value='" + value + '\'' + ", secretKey='" + secretKey + '\'' + '}'; } }
3,008
20.963504
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/model/EnvTck.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite.model; public class EnvTck { String currentCoinbase; String currentDifficulty; String currentGasLimit; String currentNumber; String currentTimestamp; String previousHash; public EnvTck() { } public String getCurrentCoinbase() { return currentCoinbase; } public void setCurrentCoinbase(String currentCoinbase) { this.currentCoinbase = currentCoinbase; } public String getCurrentDifficulty() { return currentDifficulty; } public void setCurrentDifficulty(String currentDifficulty) { this.currentDifficulty = currentDifficulty; } public String getCurrentGasLimit() { return currentGasLimit; } public void setCurrentGasLimit(String currentGasLimit) { this.currentGasLimit = currentGasLimit; } public String getCurrentNumber() { return currentNumber; } public void setCurrentNumber(String currentNumber) { this.currentNumber = currentNumber; } public String getCurrentTimestamp() { return currentTimestamp; } public void setCurrentTimestamp(String currentTimestamp) { this.currentTimestamp = currentTimestamp; } public String getPreviousHash() { return previousHash; } public void setPreviousHash(String previousHash) { this.previousHash = previousHash; } }
2,223
26.8
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/model/PostDataTck.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.ethereum.jsontestsuite.suite.Logs; /** * @author Mikhail Kalinin * @since 09.08.2017 */ @JsonIgnoreProperties(ignoreUnknown = true) public class PostDataTck { String hash; @JsonDeserialize(using = Logs.Deserializer.class) Logs logs; Indexes indexes; public String getHash() { return hash; } public void setHash(String hash) { this.hash = hash; } public Logs getLogs() { return logs; } public void setLogs(Logs logs) { this.logs = logs; } public Indexes getIndexes() { return indexes; } public void setIndexes(Indexes indexes) { this.indexes = indexes; } @JsonIgnoreProperties(ignoreUnknown = true) static class Indexes { Integer data; Integer gas; Integer value; public Integer getData() { return data; } public void setData(Integer data) { this.data = data; } public Integer getGas() { return gas; } public void setGas(Integer gas) { this.gas = gas; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } } }
2,273
23.989011
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/jsontestsuite/suite/model/AccountTck.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.jsontestsuite.suite.model; import java.util.*; /** * @author Roman Mandeleil * @since 28.06.2014 */ public class AccountTck { String balance; String code; String nonce; Map<String, String> storage = new HashMap<>(); String privateKey; public AccountTck() { } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public String getBalance() { return balance; } public void setBalance(String balance) { this.balance = balance; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getNonce() { return nonce; } public void setNonce(String nonce) { this.nonce = nonce; } public Map<String, String> getStorage() { return storage; } public void setStorage(Map<String, String> storage) { this.storage = storage; } @Override public String toString() { return "AccountState2{" + "balance='" + balance + '\'' + ", code='" + code + '\'' + ", nonce='" + nonce + '\'' + ", storage=" + storage + '}'; } }
2,146
23.123596
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/longrun/FastSyncSanityTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.longrun; import com.typesafe.config.ConfigFactory; import org.apache.commons.lang3.mutable.MutableObject; import org.ethereum.config.CommonConfig; import org.ethereum.config.SystemProperties; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListener; import org.ethereum.sync.SyncManager; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import java.util.EnumSet; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.Thread.sleep; /** * Fast sync with sanity check * * Runs sync with defined config. Stops when all nodes are downloaded in 1 minute. * - checks State Trie is not broken * Restarts, waits until SECURE sync state (all headers are downloaded) in 1 minute. * - checks block headers * Restarts, waits until full sync is over * - checks nodes/headers/blocks/tx receipts * * Run with '-Dlogback.configurationFile=longrun/logback.xml' for proper logging * Also following flags are available: * -Dreset.db.onFirstRun=true * -Doverride.config.res=longrun/conf/live.conf */ @Ignore public class FastSyncSanityTest { private Ethereum regularNode; private static AtomicBoolean firstRun = new AtomicBoolean(true); private static EnumSet<EthereumListener.SyncState> statesCompleted = EnumSet.noneOf(EthereumListener.SyncState.class); private static final Logger testLogger = LoggerFactory.getLogger("TestLogger"); private static final MutableObject<String> configPath = new MutableObject<>("longrun/conf/ropsten-fast.conf"); private static final MutableObject<Boolean> resetDBOnFirstRun = new MutableObject<>(null); private static final AtomicBoolean allChecksAreOver = new AtomicBoolean(false); public FastSyncSanityTest() throws Exception { String resetDb = System.getProperty("reset.db.onFirstRun"); String overrideConfigPath = System.getProperty("override.config.res"); if (Boolean.parseBoolean(resetDb)) { resetDBOnFirstRun.setValue(true); } else if (resetDb != null && resetDb.equalsIgnoreCase("false")) { resetDBOnFirstRun.setValue(false); } if (overrideConfigPath != null) configPath.setValue(overrideConfigPath); statTimer.scheduleAtFixedRate(() -> { try { if (fatalErrors.get() > 0) { statTimer.shutdownNow(); } } catch (Throwable t) { FastSyncSanityTest.testLogger.error("Unhandled exception", t); } }, 0, 15, TimeUnit.SECONDS); } /** * Spring configuration class for the Regular peer */ private static class RegularConfig { @Bean public RegularNode node() { return new RegularNode(); } /** * Instead of supplying properties via config file for the peer * we are substituting the corresponding bean which returns required * config for this instance. */ @Bean public SystemProperties systemProperties() { SystemProperties props = new SystemProperties(); props.overrideParams(ConfigFactory.parseResources(configPath.getValue())); if (firstRun.get() && resetDBOnFirstRun.getValue() != null) { props.setDatabaseReset(resetDBOnFirstRun.getValue()); } return props; } } /** * Just regular EthereumJ node */ static class RegularNode extends BasicNode { @Autowired SyncManager syncManager; public RegularNode() { super("sampleNode"); } private void stopSync() { config.setSyncEnabled(false); config.setDiscoveryEnabled(false); ethereum.getChannelManager().close(); syncPool.close(); syncManager.close(); } private void firstRunChecks() throws InterruptedException { if (!statesCompleted.containsAll(EnumSet.of(EthereumListener.SyncState.UNSECURE, EthereumListener.SyncState.SECURE))) return; sleep(60000); stopSync(); testLogger.info("Validating nodes: Start"); BlockchainValidation.checkNodes(ethereum, commonConfig, fatalErrors); testLogger.info("Validating nodes: End"); testLogger.info("Validating block headers: Start"); BlockchainValidation.checkFastHeaders(ethereum, commonConfig, fatalErrors); testLogger.info("Validating block headers: End"); firstRun.set(false); } @Override public void waitForSync() throws Exception { testLogger.info("Waiting for the complete blockchain sync (will take up to an hour on fast sync for the whole chain)..."); while(true) { sleep(10000); if (syncState == null) continue; switch (syncState) { case UNSECURE: if (!firstRun.get() || statesCompleted.contains(EthereumListener.SyncState.UNSECURE)) break; testLogger.info("[v] Unsecure sync completed"); statesCompleted.add(EthereumListener.SyncState.UNSECURE); firstRunChecks(); break; case SECURE: if (!firstRun.get() || statesCompleted.contains(EthereumListener.SyncState.SECURE)) break; testLogger.info("[v] Secure sync completed"); statesCompleted.add(EthereumListener.SyncState.SECURE); firstRunChecks(); break; case COMPLETE: testLogger.info("[v] Sync complete! The best block: " + bestBlock.getShortDescr()); stopSync(); return; } } } @Override public void onSyncDone() throws Exception { // Full sanity check fullSanityCheck(ethereum, commonConfig); } } private final static AtomicInteger fatalErrors = new AtomicInteger(0); private final static long MAX_RUN_MINUTES = 1440L; private static ScheduledExecutorService statTimer = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "StatTimer")); private static boolean logStats() { testLogger.info("---------====---------"); testLogger.info("fatalErrors: {}", fatalErrors); testLogger.info("---------====---------"); return fatalErrors.get() == 0; } private static void fullSanityCheck(Ethereum ethereum, CommonConfig commonConfig) { BlockchainValidation.fullCheck(ethereum, commonConfig, fatalErrors); logStats(); allChecksAreOver.set(true); statTimer.shutdownNow(); } @Test public void testTripleCheck() throws Exception { runEthereum(); new Thread(() -> { try { while(firstRun.get()) { sleep(1000); } testLogger.info("Stopping first run"); regularNode.close(); testLogger.info("First run stopped"); sleep(10_000); testLogger.info("Starting second run"); runEthereum(); while(!allChecksAreOver.get()) { sleep(1000); } testLogger.info("Stopping second run"); regularNode.close(); testLogger.info("All checks are finished"); } catch (Throwable e) { e.printStackTrace(); } }).start(); if(statTimer.awaitTermination(MAX_RUN_MINUTES, TimeUnit.MINUTES)) { logStats(); // Checking for errors assert allChecksAreOver.get(); if (!logStats()) assert false; } } public void runEthereum() throws Exception { testLogger.info("Starting EthereumJ regular instance!"); this.regularNode = EthereumFactory.createEthereum(RegularConfig.class); } }
9,417
35.933333
134
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/longrun/HardExitSanityTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.longrun; import com.typesafe.config.ConfigFactory; import org.apache.commons.lang3.mutable.MutableObject; import org.ethereum.config.CommonConfig; import org.ethereum.config.SystemProperties; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.Thread.sleep; import static org.junit.Assert.assertNotNull; /** * Sync with sanity check * * Runs sync with defined config * - checks that State Trie is not broken * - checks whether all blocks are in blockstore, validates parent connection and bodies * - checks and validates transaction receipts * * Stopped from time to time via process killing to replicate * most complicated conditions for application * * Run with '-Dlogback.configurationFile=longrun/logback.xml' for proper logging * *** NOTE: this test uses standard output for discovering node process pid, but if you run test using Gradle, * it will put away standard streams, so test is unable to work. To solve the issue, you need to add * "showStandardStreams = true" line and extend events with 'standard_out', 'standard_error' * in test.testLogging section of build.gradle * Also following flags are supported: * -Doverride.config.res=longrun/conf/live.conf * -Dnode.run.cmd="./gradlew run" */ @Ignore public class HardExitSanityTest { private Ethereum checkNode; private static AtomicBoolean checkInProgress = new AtomicBoolean(false); private static final Logger testLogger = LoggerFactory.getLogger("TestLogger"); // Database path and type of two following configurations should match, so check will run over the same DB private static final MutableObject<String> configPath = new MutableObject<>("longrun/conf/live.conf"); private String nodeRunCmd = "./gradlew run"; // Test made to use configuration started from Gradle private Process proc; private final static AtomicInteger fatalErrors = new AtomicInteger(0); private final static long MAX_RUN_MINUTES = 3 * 24 * 60L; // Maximum running time private static ScheduledExecutorService statTimer = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "StatTimer")); public HardExitSanityTest() throws Exception { String overrideNodeRunCmd = System.getProperty("node.run.cmd"); if (overrideNodeRunCmd != null) { nodeRunCmd = overrideNodeRunCmd; } testLogger.info("Test will run EthereumJ using command: {}", nodeRunCmd); String overrideConfigPath = System.getProperty("override.config.res"); if (overrideConfigPath != null) { configPath.setValue(overrideConfigPath); } // Catching errors in separate thread statTimer.scheduleAtFixedRate(() -> { try { if (fatalErrors.get() > 0) { statTimer.shutdownNow(); } } catch (Throwable t) { HardExitSanityTest.testLogger.error("Unhandled exception", t); } }, 0, 1, TimeUnit.SECONDS); } private static boolean logStats() { testLogger.info("---------====---------"); testLogger.info("fatalErrors: {}", fatalErrors); testLogger.info("---------====---------"); return fatalErrors.get() == 0; } /** * Spring configuration class for the Regular peer * - Peer will not sync * - Peer will run sanity check */ private static class SanityCheckConfig { @Bean public SyncSanityTest.RegularNode node() { return new SyncSanityTest.RegularNode() { @Override public void run() { testLogger.info("Begin sanity check for EthereumJ, best block [{}]", ethereum.getBlockchain().getBestBlock().getNumber()); fullSanityCheck(ethereum, commonConfig); checkInProgress.set(false); } }; } /** * Instead of supplying properties via config file for the peer * we are substituting the corresponding bean which returns required * config for this instance. */ @Bean public SystemProperties systemProperties() { SystemProperties props = new SystemProperties(); props.overrideParams(ConfigFactory.parseResources(configPath.getValue())); props.setDatabaseReset(false); props.setSyncEnabled(false); props.setDiscoveryEnabled(false); return props; } } private static void fullSanityCheck(Ethereum ethereum, CommonConfig commonConfig) { BlockchainValidation.fullCheck(ethereum, commonConfig, fatalErrors); logStats(); } @Test public void testMain() throws Exception { System.out.println("Test started"); Thread main = new Thread(() -> { try { while (true) { Random rnd = new Random(); int runDistance = 60 * 5 + rnd.nextInt(60 * 5); // 5 - 10 minutes testLogger.info("Running EthereumJ node for {} seconds", runDistance); startEthereumJ(); TimeUnit.SECONDS.sleep(runDistance); killEthereumJ(); sleep(2000); checkInProgress.set(true); testLogger.info("Starting EthereumJ sanity check instance"); this.checkNode = EthereumFactory.createEthereum(SanityCheckConfig.class); while (checkInProgress.get()) { sleep(1000); } checkNode.close(); testLogger.info("Sanity check is over", runDistance); } } catch (Throwable e) { e.printStackTrace(); } }); main.start(); if(statTimer.awaitTermination(MAX_RUN_MINUTES, TimeUnit.MINUTES)) { if (!checkInProgress.get()) { killEthereumJ(); } while (checkInProgress.get()) { sleep(1000); } assert logStats(); } } private void startEthereumJ() { try { File dir = new File(System.getProperty("user.dir")); if (dir.toString().contains("ethereumj-core")) { dir = new File(dir.getParent()); } String javaHomePath = System.getenv("JAVA_HOME"); proc = Runtime.getRuntime().exec(nodeRunCmd, new String[] {"JAVA_HOME=" + javaHomePath}, dir); flushOutput(proc); testLogger.info("EthereumJ started, pid {}", getUnixPID(proc)); // Uncomment following line for debugging purposes // System.out.print(getProcOutput(proc)); } catch (Exception ex) { testLogger.error("Error during starting of main EthereumJ using cmd: " + nodeRunCmd, ex); fatalErrors.addAndGet(1); } } private int getChildPID(int processPID) throws Exception { try { ProcessBuilder builder = new ProcessBuilder("pgrep", "-P", "" + processPID); builder.redirectErrorStream(true); Process getPID = builder.start(); String output = getProcOutput(getPID); String pidPart = output.substring(0, output.indexOf('\n')); Integer ret = new Integer(pidPart); if (ret <= 0) { throw new RuntimeException("Incorrect child PID detected"); } return ret; } catch (Exception ex) { testLogger.error("Failed to get child PID of gradle", ex); throw new RuntimeException("Cannot get child PID for parent #" + processPID); } } /** * Just eats process output and does nothing with eat * Some applications could hang if output buffer is not emptied from time to time, * probably, when they have synchronized output */ private void flushOutput(Process process) throws Exception { new Thread(() -> { String line = null; try (BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()))) { while ((line = input.readLine()) != null) { } } catch (IOException e) { e.printStackTrace(); } }).start(); new Thread(() -> { String line = null; try (BufferedReader input = new BufferedReader(new InputStreamReader(process.getErrorStream()))) { while ((line = input.readLine()) != null) { } } catch (IOException e) { e.printStackTrace(); } }).start(); } private String getProcOutput(Process process) throws Exception { StringBuilder buffer = new StringBuilder(); Thread listener = new Thread(() -> { String line = null; try (BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()))) { while ((line = input.readLine()) != null) { buffer.append(line); buffer.append('\n'); } process.waitFor(); } catch (Exception e) { e.printStackTrace(); } }); listener.start(); listener.join(); return buffer.toString(); } private void killEthereumJ() { try { if (!proc.isAlive()) { testLogger.warn("Not killing EthereumJ, already finished."); return; } testLogger.info("Killing EthereumJ"); // Gradle (PID) -> Java app (another PID) if (killUnixProcess(getChildPID(getUnixPID(proc))) != 0) { throw new RuntimeException("Killing EthereunJ was not successful"); } } catch (Exception ex) { testLogger.error("Error during shutting down of main EthereumJ", ex); fatalErrors.addAndGet(1); } } private static int getUnixPID(Process process) throws Exception { if (process.getClass().getName().equals("java.lang.UNIXProcess")) { Class cl = process.getClass(); Field field = cl.getDeclaredField("pid"); field.setAccessible(true); Object pidObject = field.get(process); return (Integer) pidObject; } else { throw new IllegalArgumentException("Needs to be a UNIXProcess"); } } private static int killUnixProcess(int pid) throws Exception { return Runtime.getRuntime().exec("kill -9 " + pid).waitFor(); } }
12,197
37.238245
142
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/longrun/SyncSanityTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.longrun; import com.typesafe.config.ConfigFactory; import org.apache.commons.lang3.mutable.MutableObject; import org.ethereum.config.CommonConfig; import org.ethereum.config.SystemProperties; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.Thread.sleep; /** * Sync with sanity check * * Runs sync with defined config * - checks State Trie is not broken * - checks whether all blocks are in blockstore, validates parent connection and bodies * - checks and validate transaction receipts * Stopped, than restarts in 1 minute, syncs and pass all checks again * * Run with '-Dlogback.configurationFile=longrun/logback.xml' for proper logging * Also following flags are available: * -Dreset.db.onFirstRun=true * -Doverride.config.res=longrun/conf/live.conf */ @Ignore public class SyncSanityTest { private Ethereum regularNode; private static AtomicBoolean firstRun = new AtomicBoolean(true); private static final Logger testLogger = LoggerFactory.getLogger("TestLogger"); private static final MutableObject<String> configPath = new MutableObject<>("longrun/conf/ropsten.conf"); private static final MutableObject<Boolean> resetDBOnFirstRun = new MutableObject<>(null); private static final AtomicBoolean allChecksAreOver = new AtomicBoolean(false); public SyncSanityTest() throws Exception { String resetDb = System.getProperty("reset.db.onFirstRun"); String overrideConfigPath = System.getProperty("override.config.res"); if (Boolean.parseBoolean(resetDb)) { resetDBOnFirstRun.setValue(true); } else if (resetDb != null && resetDb.equalsIgnoreCase("false")) { resetDBOnFirstRun.setValue(false); } if (overrideConfigPath != null) configPath.setValue(overrideConfigPath); statTimer.scheduleAtFixedRate(() -> { try { if (fatalErrors.get() > 0) { statTimer.shutdownNow(); } } catch (Throwable t) { SyncSanityTest.testLogger.error("Unhandled exception", t); } }, 0, 15, TimeUnit.SECONDS); } /** * Spring configuration class for the Regular peer */ private static class RegularConfig { @Bean public RegularNode node() { return new RegularNode(); } /** * Instead of supplying properties via config file for the peer * we are substituting the corresponding bean which returns required * config for this instance. */ @Bean public SystemProperties systemProperties() { SystemProperties props = new SystemProperties(); props.overrideParams(ConfigFactory.parseResources(configPath.getValue())); if (firstRun.get() && resetDBOnFirstRun.getValue() != null) { props.setDatabaseReset(resetDBOnFirstRun.getValue()); } return props; } } /** * Just regular EthereumJ node */ static class RegularNode extends BasicNode { public RegularNode() { super("sampleNode"); } @Override public void waitForSync() throws Exception { testLogger.info("Waiting for the whole blockchain sync (will take up to an hour on fast sync for the whole chain)..."); while(true) { sleep(10000); if (syncComplete) { testLogger.info("[v] Sync complete! The best block: " + bestBlock.getShortDescr()); // Stop syncing config.setSyncEnabled(false); config.setDiscoveryEnabled(false); ethereum.getChannelManager().close(); syncPool.close(); return; } } } @Override public void onSyncDone() throws Exception { // Full sanity check fullSanityCheck(ethereum, commonConfig); } } private final static AtomicInteger fatalErrors = new AtomicInteger(0); private final static long MAX_RUN_MINUTES = 180L; private static ScheduledExecutorService statTimer = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "StatTimer")); private static boolean logStats() { testLogger.info("---------====---------"); testLogger.info("fatalErrors: {}", fatalErrors); testLogger.info("---------====---------"); return fatalErrors.get() == 0; } private static void fullSanityCheck(Ethereum ethereum, CommonConfig commonConfig) { BlockchainValidation.fullCheck(ethereum, commonConfig, fatalErrors); logStats(); if (!firstRun.get()) { allChecksAreOver.set(true); statTimer.shutdownNow(); } firstRun.set(false); } @Test public void testDoubleCheck() throws Exception { runEthereum(); new Thread(() -> { try { while(firstRun.get()) { sleep(1000); } testLogger.info("Stopping first run"); regularNode.close(); testLogger.info("First run stopped"); sleep(60_000); testLogger.info("Starting second run"); runEthereum(); } catch (Throwable e) { e.printStackTrace(); } }).start(); if(statTimer.awaitTermination(MAX_RUN_MINUTES, TimeUnit.MINUTES)) { logStats(); // Checking for errors assert allChecksAreOver.get(); if (!logStats()) assert false; } } public void runEthereum() throws Exception { testLogger.info("Starting EthereumJ regular instance!"); this.regularNode = EthereumFactory.createEthereum(RegularConfig.class); } }
7,234
33.452381
131
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/longrun/BasicNode.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.longrun; import org.ethereum.config.CommonConfig; import org.ethereum.config.SystemProperties; import org.ethereum.core.Block; import org.ethereum.core.TransactionReceipt; import org.ethereum.db.DbFlushManager; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListener; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.net.eth.message.StatusMessage; import org.ethereum.net.rlpx.Node; import org.ethereum.net.server.Channel; import org.ethereum.sync.SyncPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import javax.annotation.PostConstruct; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Vector; import static java.lang.Thread.sleep; /** * BasicNode of ethereum instance */ class BasicNode implements Runnable { static final Logger sLogger = LoggerFactory.getLogger("sample"); private String loggerName; public Logger logger; @Autowired protected Ethereum ethereum; @Autowired protected SystemProperties config; @Autowired protected SyncPool syncPool; @Autowired protected CommonConfig commonConfig; @Autowired protected DbFlushManager dbFlushManager; // Spring config class which add this sample class as a bean to the components collections // and make it possible for autowiring other components private static class Config { @Bean public BasicNode basicSample() { return new BasicNode(); } } public static void main(String[] args) throws Exception { sLogger.info("Starting EthereumJ!"); // Based on Config class the BasicNode would be created by Spring // and its springInit() method would be called as an entry point EthereumFactory.createEthereum(Config.class); } public BasicNode() { this("sample"); } /** * logger name can be passed if more than one EthereumJ instance is created * in a single JVM to distinguish logging output from different instances */ public BasicNode(String loggerName) { this.loggerName = loggerName; } /** * The method is called after all EthereumJ instances are created */ @PostConstruct private void springInit() { logger = LoggerFactory.getLogger(loggerName); // adding the main EthereumJ callback to be notified on different kind of events ethereum.addListener(listener); logger.info("Sample component created. Listening for ethereum events..."); // starting lifecycle tracking method run() new Thread(this, "SampleWorkThread").start(); } /** * The method tracks step-by-step the instance lifecycle from node discovery till sync completion. * At the end the method onSyncDone() is called which might be overridden by a sample subclass * to start making other things with the Ethereum network */ public void run() { try { logger.info("Sample worker thread started."); if (!config.peerDiscovery()) { logger.info("Peer discovery disabled. We should actively connect to another peers or wait for incoming connections"); } waitForSync(); onSyncDone(); } catch (Exception e) { logger.error("Error occurred in Sample: ", e); } } /** * Waits until the whole blockchain sync is complete */ public void waitForSync() throws Exception { logger.info("Waiting for the whole blockchain sync (will take up to an hour on fast sync for the whole chain)..."); while(true) { sleep(10000); if (syncComplete) { logger.info("[v] Sync complete! The best block: " + bestBlock.getShortDescr()); return; } } } /** * Is called when the whole blockchain sync is complete */ public void onSyncDone() throws Exception { logger.info("Monitoring new blocks in real-time..."); } public void onSyncDoneImpl(EthereumListener.SyncState state) { logger.info("onSyncDone: " + state); } protected Map<Node, StatusMessage> ethNodes = new Hashtable<>(); protected List<Node> syncPeers = new Vector<>(); protected Block bestBlock = null; EthereumListener.SyncState syncState = null; boolean syncComplete = false; /** * The main EthereumJ callback. */ EthereumListener listener = new EthereumListenerAdapter() { @Override public void onSyncDone(SyncState state) { syncState = state; if (state.equals(SyncState.COMPLETE)) syncComplete = true; onSyncDoneImpl(state); } @Override public void onEthStatusUpdated(Channel channel, StatusMessage statusMessage) { ethNodes.put(channel.getNode(), statusMessage); } @Override public void onPeerAddedToSyncPool(Channel peer) { syncPeers.add(peer.getNode()); } @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { bestBlock = block; if (syncComplete) { logger.info("New block: " + block.getShortDescr()); } } }; }
6,310
30.39801
133
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/longrun/BlockchainValidation.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.longrun; import org.ethereum.config.CommonConfig; import org.ethereum.core.AccountState; import org.ethereum.core.Block; import org.ethereum.core.BlockHeader; import org.ethereum.core.BlockchainImpl; import org.ethereum.core.Bloom; import org.ethereum.core.Transaction; import org.ethereum.core.TransactionInfo; import org.ethereum.core.TransactionReceipt; import org.ethereum.crypto.HashUtil; import org.ethereum.datasource.NodeKeyCompositor; import org.ethereum.datasource.Source; import org.ethereum.datasource.SourceCodec; import org.ethereum.db.BlockStore; import org.ethereum.db.HeaderStore; import org.ethereum.facade.Ethereum; import org.ethereum.trie.SecureTrie; import org.ethereum.trie.TrieImpl; import org.ethereum.util.FastByteComparisons; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static org.ethereum.core.BlockchainImpl.calcReceiptsTrie; /** * Validation for all kind of blockchain data */ public class BlockchainValidation { private static final Logger testLogger = LoggerFactory.getLogger("TestLogger"); private static Integer getReferencedTrieNodes(final Source<byte[], byte[]> stateDS, final boolean includeAccounts, byte[] ... roots) { final AtomicInteger ret = new AtomicInteger(0); for (byte[] root : roots) { SecureTrie trie = new SecureTrie(stateDS, root); trie.scanTree(new TrieImpl.ScanAction() { @Override public void doOnNode(byte[] hash, TrieImpl.Node node) { ret.incrementAndGet(); } @Override public void doOnValue(byte[] nodeHash, TrieImpl.Node node, byte[] key, byte[] value) { if (includeAccounts) { AccountState accountState = new AccountState(value); if (!FastByteComparisons.equal(accountState.getCodeHash(), HashUtil.EMPTY_DATA_HASH)) { ret.incrementAndGet(); } if (!FastByteComparisons.equal(accountState.getStateRoot(), HashUtil.EMPTY_TRIE_HASH)) { NodeKeyCompositor nodeKeyCompositor = new NodeKeyCompositor(key); ret.addAndGet(getReferencedTrieNodes(new SourceCodec.KeyOnly<>(stateDS, nodeKeyCompositor), false, accountState.getStateRoot())); } } } }); } return ret.get(); } public static void checkNodes(Ethereum ethereum, CommonConfig commonConfig, AtomicInteger fatalErrors) { try { Source<byte[], byte[]> stateDS = commonConfig.stateSource(); byte[] stateRoot = ethereum.getBlockchain().getBestBlock().getHeader().getStateRoot(); int rootsSize = TrieTraversal.ofState(stateDS, stateRoot, true).go(); testLogger.info("Node validation successful"); testLogger.info("Non-unique node size: {}", rootsSize); } catch (Exception | AssertionError ex) { testLogger.error("Node validation error", ex); fatalErrors.incrementAndGet(); } } public static void checkHeaders(Ethereum ethereum, AtomicInteger fatalErrors) { int blockNumber = (int) ethereum.getBlockchain().getBestBlock().getHeader().getNumber(); byte[] lastParentHash = null; testLogger.info("Checking headers from best block: {}", blockNumber); try { while (blockNumber >= 0) { Block currentBlock = ethereum.getBlockchain().getBlockByNumber(blockNumber); if (lastParentHash != null) { assert FastByteComparisons.equal(currentBlock.getHash(), lastParentHash); } lastParentHash = currentBlock.getHeader().getParentHash(); assert lastParentHash != null; blockNumber--; } testLogger.info("Checking headers successful, ended on block: {}", blockNumber + 1); } catch (Exception | AssertionError ex) { testLogger.error(String.format("Block header validation error on block #%s", blockNumber), ex); fatalErrors.incrementAndGet(); } } public static void checkFastHeaders(Ethereum ethereum, CommonConfig commonConfig, AtomicInteger fatalErrors) { HeaderStore headerStore = commonConfig.headerStore(); int blockNumber = headerStore.size() - 1; byte[] lastParentHash = null; try { testLogger.info("Checking fast headers from best block: {}", blockNumber); while (blockNumber > 0) { BlockHeader header = headerStore.getHeaderByNumber(blockNumber); if (lastParentHash != null) { assert FastByteComparisons.equal(header.getHash(), lastParentHash); } lastParentHash = header.getParentHash(); assert lastParentHash != null; blockNumber--; } Block genesis = ethereum.getBlockchain().getBlockByNumber(0); assert FastByteComparisons.equal(genesis.getHash(), lastParentHash); testLogger.info("Checking fast headers successful, ended on block: {}", blockNumber + 1); } catch (Exception | AssertionError ex) { testLogger.error(String.format("Fast header validation error on block #%s", blockNumber), ex); fatalErrors.incrementAndGet(); } } public static void checkBlocks(Ethereum ethereum, AtomicInteger fatalErrors) { Block currentBlock = ethereum.getBlockchain().getBestBlock(); int blockNumber = (int) currentBlock.getHeader().getNumber(); try { BlockStore blockStore = ethereum.getBlockchain().getBlockStore(); testLogger.info("Checking blocks from best block: {}", blockNumber); BigInteger curTotalDiff = blockStore.getTotalDifficultyForHash(currentBlock.getHash()); while (blockNumber > 0) { currentBlock = ethereum.getBlockchain().getBlockByNumber(blockNumber); // Validate uncles assert ((BlockchainImpl) ethereum.getBlockchain()).validateUncles(currentBlock); // Validate total difficulty Assert.assertTrue(String.format("Total difficulty, count %s == %s blockStore", curTotalDiff, blockStore.getTotalDifficultyForHash(currentBlock.getHash())), curTotalDiff.compareTo(blockStore.getTotalDifficultyForHash(currentBlock.getHash())) == 0); curTotalDiff = curTotalDiff.subtract(currentBlock.getDifficultyBI()); blockNumber--; } // Checking total difficulty for genesis currentBlock = ethereum.getBlockchain().getBlockByNumber(0); Assert.assertTrue(String.format("Total difficulty for genesis, count %s == %s blockStore", curTotalDiff, blockStore.getTotalDifficultyForHash(currentBlock.getHash())), curTotalDiff.compareTo(blockStore.getTotalDifficultyForHash(currentBlock.getHash())) == 0); Assert.assertTrue(String.format("Total difficulty, count %s == %s genesis", curTotalDiff, currentBlock.getDifficultyBI()), curTotalDiff.compareTo(currentBlock.getDifficultyBI()) == 0); testLogger.info("Checking blocks successful, ended on block: {}", blockNumber + 1); } catch (Exception | AssertionError ex) { testLogger.error(String.format("Block validation error on block #%s", blockNumber), ex); fatalErrors.incrementAndGet(); } } public static void checkTransactions(Ethereum ethereum, AtomicInteger fatalErrors) { int blockNumber = (int) ethereum.getBlockchain().getBestBlock().getHeader().getNumber(); testLogger.info("Checking block transactions from best block: {}", blockNumber); try { while (blockNumber > 0) { Block currentBlock = ethereum.getBlockchain().getBlockByNumber(blockNumber); List<TransactionReceipt> receipts = new ArrayList<>(); for (Transaction tx : currentBlock.getTransactionsList()) { TransactionInfo txInfo = ((BlockchainImpl) ethereum.getBlockchain()).getTransactionInfo(tx.getHash()); assert txInfo != null; receipts.add(txInfo.getReceipt()); } Bloom logBloom = new Bloom(); for (TransactionReceipt receipt : receipts) { logBloom.or(receipt.getBloomFilter()); } assert FastByteComparisons.equal(currentBlock.getLogBloom(), logBloom.getData()); assert FastByteComparisons.equal(currentBlock.getReceiptsRoot(), calcReceiptsTrie(receipts)); blockNumber--; } testLogger.info("Checking block transactions successful, ended on block: {}", blockNumber + 1); } catch (Exception | AssertionError ex) { testLogger.error(String.format("Transaction validation error on block #%s", blockNumber), ex); fatalErrors.incrementAndGet(); } } public static void fullCheck(Ethereum ethereum, CommonConfig commonConfig, AtomicInteger fatalErrors) { // nodes testLogger.info("Validating nodes: Start"); BlockchainValidation.checkNodes(ethereum, commonConfig, fatalErrors); testLogger.info("Validating nodes: End"); // headers testLogger.info("Validating block headers: Start"); BlockchainValidation.checkHeaders(ethereum, fatalErrors); testLogger.info("Validating block headers: End"); // blocks testLogger.info("Validating blocks: Start"); BlockchainValidation.checkBlocks(ethereum, fatalErrors); testLogger.info("Validating blocks: End"); // receipts testLogger.info("Validating transaction receipts: Start"); BlockchainValidation.checkTransactions(ethereum, fatalErrors); testLogger.info("Validating transaction receipts: End"); } }
11,259
45.337449
157
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/longrun/TrieTraversal.java
package org.ethereum.longrun; import org.ethereum.core.AccountState; import org.ethereum.crypto.HashUtil; import org.ethereum.datasource.NodeKeyCompositor; import org.ethereum.datasource.Source; import org.ethereum.datasource.SourceCodec; import org.ethereum.trie.SecureTrie; import org.ethereum.trie.TrieImpl; import org.ethereum.util.FastByteComparisons; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static java.lang.Runtime.getRuntime; /** * @author Mikhail Kalinin * @since 16.01.2018 */ public abstract class TrieTraversal { protected static final Logger logger = LoggerFactory.getLogger("TestLogger"); final byte[] root; final Source<byte[], byte[]> src; final TraversalStats stats; final AtomicInteger nodesCount = new AtomicInteger(0); protected TrieTraversal(final Source<byte[], byte[]> src, final byte[] root, final TraversalStats stats) { this.src = src; this.root = root; this.stats = stats; } private static class TraversalStats { long startedAt = System.currentTimeMillis(); long updatedAt = System.currentTimeMillis(); int checkpoint = 0; int passed = 0; } public static TrieTraversal ofState(final Source<byte[], byte[]> src, final byte[] root, boolean includeAccounts) { return new StateTraversal(src, root, includeAccounts); } public static TrieTraversal ofStorage(final Source<byte[], byte[]> src, final byte[] stateRoot, final byte[] address) { TrieImpl stateTrie = new SecureTrie(src, stateRoot); byte[] encoded = stateTrie.get(address); if (encoded == null) { logger.error("Account {} does not exist", Hex.toHexString(address)); throw new RuntimeException("Account does not exist"); } AccountState state = new AccountState(encoded); if (FastByteComparisons.equal(state.getStateRoot(), HashUtil.EMPTY_TRIE_HASH)) { logger.error("Storage of account {} is empty", Hex.toHexString(address)); throw new RuntimeException("Account storage is empty"); } final NodeKeyCompositor nodeKeyCompositor = new NodeKeyCompositor(address); return new StorageTraversal( new SourceCodec.KeyOnly<>(src, nodeKeyCompositor), state.getStateRoot(), new TraversalStats(), address, true ); } public int go() { onStartImpl(); stats.startedAt = System.currentTimeMillis(); SecureTrie trie = new SecureTrie(src, root); trie.scanTree(new TrieImpl.ScanAction() { @Override public void doOnNode(byte[] hash, TrieImpl.Node node) { nodesCount.incrementAndGet(); ++stats.passed; onNodeImpl(hash, node); } @Override public void doOnValue(byte[] nodeHash, TrieImpl.Node node, byte[] key, byte[] value) { if (nodeHash == null) { // other value nodes are counted in doOnNode call nodesCount.incrementAndGet(); ++stats.passed; } onValueImpl(nodeHash, node, key, value); } }); onEndImpl(); return nodesCount.get(); } protected abstract void onNodeImpl(byte[] hash, TrieImpl.Node node); protected abstract void onValueImpl(byte[] nodeHash, TrieImpl.Node node, byte[] key, byte[] value); protected abstract void onStartImpl(); protected abstract void onEndImpl(); static class StateTraversal extends TrieTraversal { final boolean includeAccounts; private Thread statsLogger; private static final int MAX_THREADS = 20; private BlockingQueue<Runnable> traversalQueue; private ThreadPoolExecutor traversalExecutor; private final Object mutex = new Object(); private void setupAsyncGroup() { traversalQueue = new LinkedBlockingQueue<>(); traversalExecutor = new ThreadPoolExecutor(MAX_THREADS, MAX_THREADS, 0L, TimeUnit.MILLISECONDS, traversalQueue); } private void shutdownAsyncGroup() { traversalQueue.clear(); traversalExecutor.shutdownNow(); try { traversalExecutor.awaitTermination(60, TimeUnit.MINUTES); } catch (InterruptedException e) { logger.error("Validating nodes: traversal has been interrupted", e); throw new RuntimeException("Traversal has been interrupted", e); } } private void waitForAsyncJobs() { try { synchronized (mutex) { while (traversalExecutor.getActiveCount() > 0 || traversalQueue.size() > 0) { logger.info("Validating nodes: waiting for incomplete jobs: running {}, pending {}", traversalExecutor.getActiveCount(), traversalQueue.size()); mutex.wait(); } } } catch (InterruptedException e) { logger.error("Validating nodes: traversal has been interrupted", e); throw new RuntimeException("Traversal has been interrupted", e); } } private StateTraversal(final Source<byte[], byte[]> src, final byte[] root, boolean includeAccounts) { super(src, root, new TraversalStats()); this.includeAccounts = includeAccounts; } @Override protected void onNodeImpl(byte[] hash, TrieImpl.Node node) { } @Override protected void onValueImpl(byte[] nodeHash, TrieImpl.Node node, byte[] key, byte[] value) { if (includeAccounts) { final AccountState accountState = new AccountState(value); if (!FastByteComparisons.equal(accountState.getCodeHash(), HashUtil.EMPTY_DATA_HASH)) { nodesCount.incrementAndGet(); ++stats.passed; assert (null != src.get(NodeKeyCompositor.compose(accountState.getCodeHash(), key))); } if (!FastByteComparisons.equal(accountState.getStateRoot(), HashUtil.EMPTY_TRIE_HASH)) { logger.trace("Validating nodes: new storage discovered {}", HashUtil.shortHash(key)); final NodeKeyCompositor nodeKeyCompositor = new NodeKeyCompositor(key); final StorageTraversal storage = new StorageTraversal(new SourceCodec.KeyOnly<>(src, nodeKeyCompositor), accountState.getStateRoot(), stats, key); synchronized (mutex) { try { while (traversalExecutor.getActiveCount() > maxThreads()) mutex.wait(); } catch (InterruptedException e) { logger.error("Validating nodes: traversal has been interrupted", e); throw new RuntimeException("Traversal has been interrupted", e); } traversalExecutor.submit(() -> { nodesCount.addAndGet(storage.go()); synchronized (mutex) { mutex.notifyAll(); } }); } } } } private int maxThreads() { double freeMemRatio = freeMemRatio(); if (freeMemRatio < 0.1) { return MAX_THREADS / 8; } else if (freeMemRatio < 0.2) { return MAX_THREADS / 4; } else { return MAX_THREADS; } } private double freeMemRatio() { long free = getRuntime().freeMemory(); long total = getRuntime().totalMemory(); long max = getRuntime().maxMemory(); if ((double) total / max < 0.9) { return 1; } else { return (double) free / total; } } @Override protected void onStartImpl() { runStatsLogger(); setupAsyncGroup(); } private void runStatsLogger() { statsLogger = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(30000); long cur = System.currentTimeMillis(); logger.info("Validating nodes: running for " + ((cur - stats.startedAt) / 1000) + " sec, " + stats.passed + " passed, " + String.format("%.2f nodes/sec", (double) (stats.passed - stats.checkpoint) / (cur - stats.updatedAt) * 1000) + ", storage threads " + (traversalExecutor != null ? traversalExecutor.getActiveCount() : 0) + "/" + maxThreads()); stats.checkpoint = stats.passed; stats.updatedAt = cur; } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); statsLogger.start(); } @Override protected void onEndImpl() { waitForAsyncJobs(); shutdownAsyncGroup(); statsLogger.interrupt(); logger.info("Validating nodes: traversal completed in " + ((System.currentTimeMillis() - stats.startedAt) / 1000) + " sec, " + stats.passed + " nodes passed"); } } static class StorageTraversal extends TrieTraversal { final byte[] stateAddressOrHash; boolean logStats = false; private StorageTraversal(final Source<byte[], byte[]> src, final byte[] root, TraversalStats stats, final byte[] stateAddressOrHash) { super(src, root, stats); this.stateAddressOrHash = stateAddressOrHash; } private StorageTraversal(final Source<byte[], byte[]> src, final byte[] root, TraversalStats stats, final byte[] stateAddressOrHash, boolean logStats) { super(src, root, stats); this.stateAddressOrHash = stateAddressOrHash; this.logStats = logStats; } @Override protected void onNodeImpl(byte[] hash, TrieImpl.Node node) { logStatsImpl(); } @Override protected void onValueImpl(byte[] nodeHash, TrieImpl.Node node, byte[] key, byte[] value) { logStatsImpl(); } private void logStatsImpl() { if (!logStats) return; if (stats.passed % 10000 == 0 && stats.passed > stats.checkpoint) { long cur = System.currentTimeMillis(); logger.info("Validating storage " + HashUtil.shortHash(stateAddressOrHash) + ": running for " + ((cur - stats.startedAt) / 1000) + " sec, " + stats.passed + " passed, " + String.format("%.2f nodes/sec", (double) (stats.passed - stats.checkpoint) / (cur - stats.updatedAt) * 1000)); stats.checkpoint = stats.passed; stats.updatedAt = cur; } } @Override protected void onStartImpl() { logger.trace("Validating nodes: start traversing {} storage", stateAddressOrHash != null ? HashUtil.shortHash(stateAddressOrHash) : "unknown"); } @Override protected void onEndImpl() { logger.trace("Validating nodes: end traversing {} storage", stateAddressOrHash != null ? HashUtil.shortHash(stateAddressOrHash) : "unknown"); if (logStats) logger.info("Validating storage " + HashUtil.shortHash(stateAddressOrHash) + ": completed in " + ((System.currentTimeMillis() - stats.startedAt) / 1000) + " sec, " + stats.passed + " nodes passed"); } } }
12,508
38.711111
146
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/longrun/SyncWithLoadTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.longrun; import com.typesafe.config.ConfigFactory; import org.apache.commons.lang3.mutable.MutableObject; import org.ethereum.config.CommonConfig; import org.ethereum.config.SystemProperties; import org.ethereum.core.AccountState; import org.ethereum.core.Block; import org.ethereum.core.BlockSummary; import org.ethereum.core.Repository; import org.ethereum.core.Transaction; import org.ethereum.core.TransactionExecutor; import org.ethereum.core.TransactionReceipt; import org.ethereum.db.ContractDetails; import org.ethereum.db.RepositoryImpl; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListener; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.sync.SyncManager; import org.ethereum.util.FastByteComparisons; import org.ethereum.vm.program.invoke.ProgramInvokeFactory; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import static java.lang.Thread.sleep; /** * Regular sync with load * Loads ethereumJ during sync with various onBlock/repo track/callback usages * * Runs sync with defined config for 1-30 minutes * - checks State Trie is not broken * - checks whether all blocks are in blockstore, validates parent connection and bodies * - checks and validate transaction receipts * Stopped, than restarts in 1 minute, syncs and pass all checks again. * Repeats forever or until first error occurs * * Run with '-Dlogback.configurationFile=longrun/logback.xml' for proper logging * Also following flags are available: * -Dreset.db.onFirstRun=true * -Doverride.config.res=longrun/conf/live.conf */ @Ignore public class SyncWithLoadTest { private Ethereum regularNode; private final static CountDownLatch errorLatch = new CountDownLatch(1); private static AtomicBoolean isRunning = new AtomicBoolean(true); private static AtomicBoolean firstRun = new AtomicBoolean(true); private static final Logger testLogger = LoggerFactory.getLogger("TestLogger"); private static final MutableObject<String> configPath = new MutableObject<>("longrun/conf/ropsten-noprune.conf"); private static final MutableObject<Boolean> resetDBOnFirstRun = new MutableObject<>(null); // Timer stops while not syncing private static final AtomicLong lastImport = new AtomicLong(); private static final int LAST_IMPORT_TIMEOUT = 10 * 60 * 1000; public SyncWithLoadTest() throws Exception { String resetDb = System.getProperty("reset.db.onFirstRun"); String overrideConfigPath = System.getProperty("override.config.res"); if (Boolean.parseBoolean(resetDb)) { resetDBOnFirstRun.setValue(true); } else if (resetDb != null && resetDb.equalsIgnoreCase("false")) { resetDBOnFirstRun.setValue(false); } if (overrideConfigPath != null) configPath.setValue(overrideConfigPath); statTimer.scheduleAtFixedRate(() -> { // Adds error if no successfully imported blocks for LAST_IMPORT_TIMEOUT long currentMillis = System.currentTimeMillis(); if (lastImport.get() != 0 && currentMillis - lastImport.get() > LAST_IMPORT_TIMEOUT) { testLogger.error("No imported block for {} seconds", LAST_IMPORT_TIMEOUT / 1000); fatalErrors.incrementAndGet(); } try { if (fatalErrors.get() > 0) { statTimer.shutdownNow(); errorLatch.countDown(); } } catch (Throwable t) { SyncWithLoadTest.testLogger.error("Unhandled exception", t); } if (lastImport.get() == 0 && isRunning.get()) lastImport.set(currentMillis); if (lastImport.get() != 0 && !isRunning.get()) lastImport.set(0); }, 0, 15, TimeUnit.SECONDS); } /** * Spring configuration class for the Regular peer */ private static class RegularConfig { @Bean public RegularNode node() { return new RegularNode(); } /** * Instead of supplying properties via config file for the peer * we are substituting the corresponding bean which returns required * config for this instance. */ @Bean public SystemProperties systemProperties() { SystemProperties props = new SystemProperties(); props.overrideParams(ConfigFactory.parseResources(configPath.getValue())); if (firstRun.get() && resetDBOnFirstRun.getValue() != null) { props.setDatabaseReset(resetDBOnFirstRun.getValue()); } return props; } } /** * Just regular EthereumJ node */ static class RegularNode extends BasicNode { @Autowired ProgramInvokeFactory programInvokeFactory; @Autowired SyncManager syncManager; /** * The main EthereumJ callback. */ EthereumListener blockListener = new EthereumListenerAdapter() { @Override public void onBlock(BlockSummary blockSummary) { lastImport.set(System.currentTimeMillis()); } @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { for (TransactionReceipt receipt : receipts) { // Getting contract details byte[] contractAddress = receipt.getTransaction().getContractAddress(); if (contractAddress != null) { ContractDetails details = ((Repository) ethereum.getRepository()).getContractDetails(contractAddress); assert FastByteComparisons.equal(details.getAddress(), contractAddress); } // Getting AccountState for sender in the past Random rnd = new Random(); Block bestBlock = ethereum.getBlockchain().getBestBlock(); Block randomBlock = ethereum.getBlockchain().getBlockByNumber(rnd.nextInt((int) bestBlock.getNumber())); byte[] sender = receipt.getTransaction().getSender(); AccountState senderState = ((Repository) ethereum.getRepository()).getSnapshotTo(randomBlock.getStateRoot()).getAccountState(sender); if (senderState != null) senderState.getBalance(); // Getting receiver's nonce somewhere in the past Block anotherRandomBlock = ethereum.getBlockchain().getBlockByNumber(rnd.nextInt((int) bestBlock.getNumber())); byte[] receiver = receipt.getTransaction().getReceiveAddress(); if (receiver != null) { ((Repository) ethereum.getRepository()).getSnapshotTo(anotherRandomBlock.getStateRoot()).getNonce(receiver); } } } @Override public void onPendingTransactionsReceived(List<Transaction> transactions) { Random rnd = new Random(); Block bestBlock = ethereum.getBlockchain().getBestBlock(); for (Transaction tx : transactions) { Block block = ethereum.getBlockchain().getBlockByNumber(rnd.nextInt((int) bestBlock.getNumber())); Repository repository = ((Repository) ethereum.getRepository()) .getSnapshotTo(block.getStateRoot()) .startTracking(); try { TransactionExecutor executor = new TransactionExecutor (tx, block.getCoinbase(), repository, ethereum.getBlockchain().getBlockStore(), programInvokeFactory, block) .withCommonConfig(commonConfig) .setLocalCall(true); executor.init(); executor.execute(); executor.go(); executor.finalization(); executor.getReceipt(); } finally { repository.rollback(); } } } }; public RegularNode() { super("sampleNode"); } @Override public void run() { try { ethereum.addListener(blockListener); // Run 1-30 minutes Random generator = new Random(); int i = generator.nextInt(30) + 1; testLogger.info("Running for {} minutes until stop and check", i); sleep(i * 60_000); // Stop syncing syncPool.close(); syncManager.close(); } catch (Exception ex) { testLogger.error("Error occurred during run: ", ex); } if (syncComplete) { testLogger.info("[v] Sync complete! The best block: " + bestBlock.getShortDescr()); } fullSanityCheck(ethereum, commonConfig); isRunning.set(false); } } private final static AtomicInteger fatalErrors = new AtomicInteger(0); private static ScheduledExecutorService statTimer = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "StatTimer")); private static boolean logStats() { testLogger.info("---------====---------"); testLogger.info("fatalErrors: {}", fatalErrors); testLogger.info("---------====---------"); return fatalErrors.get() == 0; } private static void fullSanityCheck(Ethereum ethereum, CommonConfig commonConfig) { BlockchainValidation.fullCheck(ethereum, commonConfig, fatalErrors); logStats(); firstRun.set(false); } @Test public void testDelayedCheck() throws Exception { runEthereum(); new Thread(() -> { try { while(firstRun.get()) { sleep(1000); } testLogger.info("Stopping first run"); while(true) { while(isRunning.get()) { sleep(1000); } regularNode.close(); testLogger.info("Run stopped"); sleep(10_000); testLogger.info("Starting next run"); runEthereum(); isRunning.set(true); } } catch (Throwable e) { e.printStackTrace(); } }).start(); errorLatch.await(); if (!logStats()) assert false; } public void runEthereum() throws Exception { testLogger.info("Starting EthereumJ regular instance!"); this.regularNode = EthereumFactory.createEthereum(RegularConfig.class); } }
12,408
38.022013
153
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/mine/MinerTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import com.typesafe.config.ConfigFactory; import org.apache.commons.lang3.tuple.Pair; import org.ethereum.config.NoAutoscan; import org.ethereum.config.SystemProperties; import org.ethereum.core.*; import org.ethereum.crypto.ECKey; import org.ethereum.db.ByteArrayWrapper; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.net.eth.handler.Eth62; import org.ethereum.net.eth.message.*; import org.ethereum.util.ByteUtil; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.FileNotFoundException; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Long running test * * Creates an instance * * Created by Anton Nashatyrev on 13.10.2015. */ @Ignore public class MinerTest { @Configuration @NoAutoscan public static class SysPropConfig1 { static Eth62 testHandler = null; static SystemProperties props = new SystemProperties();; @Bean public SystemProperties systemProperties() { return props; } } @Configuration @NoAutoscan public static class SysPropConfig2 { static Eth62 testHandler = null; static SystemProperties props = new SystemProperties();; @Bean public SystemProperties systemProperties() { return props; } } @BeforeClass public static void setup() { // Constants.MINIMUM_DIFFICULTY = BigInteger.valueOf(1); } @Test public void startMiningConsumer() throws Exception { SysPropConfig2.props.overrideParams(ConfigFactory.parseString( "peer.listen.port = 30336 \n" + "peer.privateKey = 3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c \n" + "peer.networkId = 555 \n" + "peer.active = [" + "{ url = \"enode://b23b3b9f38f1d314b27e63c63f3e45a6ea5f82c83f282e2d38f2f01c22165e897656fe2e5f9f18616b81f41cbcf2e9100fc9f8dad099574f3d84cf9623de2fc9@localhost:20301\" }," + "{ url = \"enode://26ba1aadaf59d7607ad7f437146927d79e80312f026cfa635c6b2ccf2c5d3521f5812ca2beb3b295b14f97110e6448c1c7ff68f14c5328d43a3c62b44143e9b1@localhost:30335\" }" + "] \n" + "sync.enabled = true \n" + "genesis = genesis-harder.json \n" + // "genesis = frontier.json \n" + "database.dir = testDB-1 \n")); Ethereum ethereum2 = EthereumFactory.createEthereum(SysPropConfig2.props, SysPropConfig2.class); final CountDownLatch semaphore = new CountDownLatch(1); ethereum2.addListener(new EthereumListenerAdapter() { @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { System.err.println("=== New block: " + blockInfo(block)); System.err.println(block); for (Transaction tx : block.getTransactionsList()) { // Pair<Transaction, Long> remove = submittedTxs.remove(new ByteArrayWrapper(tx.getHash())); // if (remove == null) { // System.err.println("===== !!! Unknown Tx: " + tx); // } else { // System.out.println("===== Tx included in " + (System.currentTimeMillis() - remove.getRight()) / 1000 // + " sec: " + tx); // } } // for (Pair<Transaction, Long> pair : submittedTxs.values()) { // if (System.currentTimeMillis() - pair.getRight() > 60 * 1000) { // System.err.println("==== !!! Lost Tx: " + (System.currentTimeMillis() - pair.getRight()) / 1000 // + " sec: " + pair.getLeft()); // } // } } @Override public void onPendingTransactionsReceived(List<Transaction> transactions) { System.err.println("=== Tx: " + transactions); } @Override public void onSyncDone(SyncState state) { semaphore.countDown(); System.err.println("=== Sync Done!"); } }); System.out.println("Waiting for sync..."); semaphore.await(); // ECKey senderKey = ECKey.fromPrivate(Hex.decode("3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c")); // byte[] receiverAddr = Hex.decode("31e2e1ed11951c7091dfba62cd4b7145e947219c"); ECKey senderKey = ECKey.fromPrivate(Hex.decode("6ef8da380c27cea8fdf7448340ea99e8e2268fc2950d79ed47cbf6f85dc977ec")); byte[] receiverAddr = Hex.decode("5db10750e8caff27f906b41c71b3471057dd2004"); for (int i = ethereum2.getRepository().getNonce(senderKey.getAddress()).intValue(), j = 0; j < 200; i++, j++) { { Transaction tx = new Transaction(ByteUtil.intToBytesNoLeadZeroes(i), ByteUtil.longToBytesNoLeadZeroes(50_000_000_000L), ByteUtil.longToBytesNoLeadZeroes(0xfffff), receiverAddr, new byte[]{77}, new byte[0]); tx.sign(senderKey); System.out.println("=== Submitting tx: " + tx); ethereum2.submitTransaction(tx); submittedTxs.put(new ByteArrayWrapper(tx.getHash()), Pair.of(tx, System.currentTimeMillis())); } Thread.sleep(7000); } Thread.sleep(100000000L); } Map<ByteArrayWrapper, Pair<Transaction, Long>> submittedTxs = Collections.synchronizedMap( new HashMap<ByteArrayWrapper, Pair<Transaction, Long>>()); static String blockInfo(Block b) { boolean ours = Hex.toHexString(b.getExtraData()).startsWith("cccccccccc"); String txs = "Tx["; for (Transaction tx : b.getTransactionsList()) { txs += ByteUtil.byteArrayToLong(tx.getNonce()) + ", "; } txs = txs.substring(0, txs.length() - 2) + "]"; return (ours ? "##" : " ") + b.getShortDescr() + " " + txs; } @Test public void startMiningTest() throws FileNotFoundException, InterruptedException { SysPropConfig1.props.overrideParams(ConfigFactory.parseString( "peer.listen.port = 30335 \n" + "peer.privateKey = 6ef8da380c27cea8fdf7448340ea99e8e2268fc2950d79ed47cbf6f85dc977ec \n" + "peer.networkId = 555 \n" + "peer.active = [{ url = \"enode://b23b3b9f38f1d314b27e63c63f3e45a6ea5f82c83f282e2d38f2f01c22165e897656fe2e5f9f18616b81f41cbcf2e9100fc9f8dad099574f3d84cf9623de2fc9@localhost:20301\" }] \n" + "sync.enabled = true \n" + "genesis = genesis-harder.json \n" + // "genesis = frontier.json \n" + "database.dir = testDB-2 \n" + "mine.extraDataHex = cccccccccccccccccccc \n" + "mine.cpuMineThreads = 2")); // SysPropConfig2.props.overrideParams(ConfigFactory.parseString( // "peer.listen.port = 30336 \n" + // "peer.privateKey = 3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c \n" + // "peer.networkId = 555 \n" + // "peer.active = [{ url = \"enode://b23b3b9f38f1d314b27e63c63f3e45a6ea5f82c83f282e2d38f2f01c22165e897656fe2e5f9f18616b81f41cbcf2e9100fc9f8dad099574f3d84cf9623de2fc9@localhost:20301\" }] \n" + // "sync.enabled = true \n" + // "genesis = genesis-light.json \n" + //// "genesis = frontier.json \n" + // "database.dir = testDB-1 \n")); Ethereum ethereum1 = EthereumFactory.createEthereum(SysPropConfig1.props, SysPropConfig1.class); // Ethereum ethereum2 = EthereumFactory.createEthereum(SysPropConfig2.props, SysPropConfig2.class); final CountDownLatch semaphore = new CountDownLatch(1); ethereum1.addListener(new EthereumListenerAdapter() { @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { System.out.println("=== New block: " + blockInfo(block)); } @Override public void onSyncDone(SyncState state) { semaphore.countDown(); } }); // ethereum2.addListener(new EthereumListenerAdapter() { // @Override // public void onBlock(Block block, List<TransactionReceipt> receipts) { // System.err.println("=== New block: " + block); // } // // @Override // public void onPendingStateChanged(List<Transaction> transactions) { // System.err.println("=== Tx: " + transactions); // } // }); System.out.println("=== Waiting for sync ..."); semaphore.await(600, TimeUnit.SECONDS); System.out.println("=== Sync done."); BlockMiner blockMiner = ethereum1.getBlockMiner(); blockMiner.addListener(new MinerListener() { @Override public void miningStarted() { System.out.println("=== MinerTest.miningStarted"); } @Override public void miningStopped() { System.out.println("=== MinerTest.miningStopped"); } @Override public void blockMiningStarted(Block block) { System.out.println("=== MinerTest.blockMiningStarted " + blockInfo(block)); } @Override public void blockMined(Block block) { // boolean validate = Ethash.getForBlock(block.getNumber()).validate(block.getHeader()); System.out.println("=== MinerTest.blockMined " + blockInfo(block)); // System.out.println("=== MinerTest.blockMined: " + validate); } @Override public void blockMiningCanceled(Block block) { System.out.println("=== MinerTest.blockMiningCanceled " + blockInfo(block)); } }); Ethash.fileCacheEnabled = true; blockMiner.setFullMining(true); blockMiner.startMining(); // System.out.println("======= Waiting for block #4"); // semaphore.await(60, TimeUnit.SECONDS); // if(semaphore.getCount() > 0) { // throw new RuntimeException("4 blocks were not imported."); // } // // System.out.println("======= Sending forked block without parent..."); ECKey senderKey = ECKey.fromPrivate(Hex.decode("3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c")); byte[] receiverAddr = Hex.decode("31e2e1ed11951c7091dfba62cd4b7145e947219c"); for (int i = ethereum1.getRepository().getNonce(senderKey.getAddress()).intValue(), j = 0; j < 20000; i++, j++) { { Transaction tx = new Transaction(ByteUtil.intToBytesNoLeadZeroes(i), ByteUtil.longToBytesNoLeadZeroes(50_000_000_000L), ByteUtil.longToBytesNoLeadZeroes(0xfffff), receiverAddr, new byte[]{77}, new byte[0]); tx.sign(senderKey); System.out.println("=== Submitting tx: " + tx); ethereum1.submitTransaction(tx); submittedTxs.put(new ByteArrayWrapper(tx.getHash()), Pair.of(tx, System.currentTimeMillis())); } Thread.sleep(5000); } Thread.sleep(1000000000); ethereum1.close(); System.out.println("Passed."); } public static void main(String[] args) throws Exception { ECKey k = ECKey.fromPrivate(Hex.decode("6ef8da380c27cea8fdf7448340ea99e8e2268fc2950d79ed47cbf6f85dc977ec")); System.out.println(Hex.toHexString(k.getPrivKeyBytes())); System.out.println(Hex.toHexString(k.getAddress())); System.out.println(Hex.toHexString(k.getNodeId())); } @Test public void blockTest() { String rlp = "f90498f90490f90217a0887405e8cf98cfdbbf5ab4521d45a0803e397af61852d94dc46ca077787088bfa0d6d234f05ac90931822b7b6f244cef81" + "83e5dd3080483273d6c2fcc02399216294ee0250c19ad59305b2bdb61f34b45b72fe37154fa0caa558a47a66b975426c6b963c46bb83d969787cfedc09fd2cab8ab83155568da07c970ab3f2004e2aa0" + "7d7b3dda348a3a4f8f4ab98b3504c46c1ffae09ef5bd23a077007d3a4c7c88823e9f80b1ba48ec74f88f40e9ec9c5036235fc320fe8a29ffb90100000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008311fc6782" + "02868508cc8cac48825208845682c3479ad983010302844765746887676f312e352e318777696e646f7773a020269a7f434e365b012659d1b190aa1586c22d7bbf0ed7fad73ca7d2b60f623c8841c814" + "3ae845fb3df867f8656e850ba43b7400830fffff9431e2e1ed11951c7091dfba62cd4b7145e947219c4d801ba0ad82686ee482723f88d9760b773e7b8234f126271e53369b928af0cbab302baea04fe3" + "dd2e0dbcc5d53123fe49f3515f0844c7e4c6dd3752f0cf916f4bb5cbe80bf9020af90207a08752c2c47c96537cf695bdecc9696a8ea35b6bfdc1389a134b47ad63fea38c2ca01dcc4de8dec75d7aab85" + "b567b6ccd41ad312451b948a7413f0a142fd40d493479450b8f981ce93fd5b81b844409169148428400bf3a05bff1dc620da4d3a123f8e08536434071281d64fc106105fb3bc94b6b1b8913ba0b59542" + "42bb4483396ae474b02651b40d4a9d61ab99a7455e57ef31f2688bdf81a03068c58706501d3059f40a5366debf4bf1cad48439d19f00154076c5d96c26d6b90100000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + "008311f7ea8202848508d329637f825208845682c3438acccccccccccccccccccca0216ef6369d46fe0ad70d2b7f9aa0785f33cbb8894733859136b5143c0ed8b09f88bc45a9ac8c1cea67842b0113c6"; NewBlockMessage msg = new NewBlockMessage(Hex.decode(rlp)); Block b = msg.getBlock(); System.out.println(b); System.out.println(msg.getDifficultyAsBigInt().toString(16)); } @Test public void blockTest1() { String rlp = "f90214a0a9c93d6bcd5dbcc94e0f467c88c59851b0951990c1c340c7b20aa967758ecd87a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794ee0250c19ad59305b2bdb61f34b45b72fe37154fa0ed230be6c9531d27a387fa5ca2cb2e70848d5de33636ae2a28d5e9e623a3089da056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000831116b881d9850ec4a4290b8084567406d39ad983010302844765746887676f312e352e318777696e646f7773a09a518a25af220fb8afe23bcafd71e4a0dba0da38972e962b07ed89dab34ac2748872311081e40c488a | f90214a01e479ea9dc53e675780469952ea87d531eb3d47808e2b57339055bdc6e61ae57a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794ee0250c19ad59305b2bdb61f34b45b72fe37154fa0ea92e8c9e36ffe81be59f06af1a3b4b18b778838d4fac19f4dfeb08a5a1046dfa056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000831118da81da850ec0f300028084567406dd9ad983010302844765746887676f312e352e318777696e646f7773a056bacad6b399e5e39f5168080941d54807f25984544f6bc885bbf1a0ffd0a0298856ceeb676b74d420 | " + "f90214a0b7992b18db1b3514b90376fe96235bc73db9eba3cb21ecb190d34e9c680c914fa06ab8465069b6d6a758c73894d6fbd2ad98f9c551a7a99672aedba3b12d1e76f594ee0250c19ad59305b2bdb61f34b45b72fe37154fa0499179489d7c04a781c3fd8b8b0f0a04030fd2057a11e86e6a12e4baa07dfdd6a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083111afd81db850ebd42c3438084567406e19ad983010302844765746887676f312e352e318777696e646f7773a04d78ab8e21ea8630f52a60ed60d945c7bbb8267777d28a98612b77a673663430886b676858a8d6b99a | f90204a08680005ea64540a769286d281cb931a97e7abed2611f00f2c6f47a7aaad5faa8a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d493479450b8f981ce93fd5b81b844409169148428400bf3a0bf55a6e82564fb532316e694838dae38d21fa80bc8af1867e418cb26bcdf0e61a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000831118da81dc850ebd42c3438084567406f58acccccccccccccccccccca04c2135ea0bb1f148303b201141df207898fa0897e3fb48fe661cda3ba2880da388b4ce6cb5535077af | f90204a05897e0e01ed54cf189751c6dd7b0107b2b3b1c841cb7d9bdb6f2aca6ff770c17a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d493479450b8f981ce93fd5b81b844409169148428400bf3a01ad754d90de6789c4fa5708992d9f089165e5047d52e09abc22cf49428af23cda056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000831116b781dd850ebd42c3438084567407048acccccccccccccccccccca0b314fab93d91a0adea632fd58027cb39857a0ad188c473f41a640052a6a0141d88d64656f7bb5f1066"; for (String s : rlp.split("\\|")) { BlockHeader blockHeader = new BlockHeader(Hex.decode(s)); System.out.println(Hex.toHexString(blockHeader.getHash()).substring(0, 6)); System.out.println(blockHeader); } } }
21,837
62.298551
3,171
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/mine/SyncDoneTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import org.ethereum.config.NoAutoscan; import org.ethereum.config.SystemProperties; import org.ethereum.config.net.MainNetConfig; import org.ethereum.core.Block; import org.ethereum.core.BlockSummary; import org.ethereum.core.Blockchain; import org.ethereum.core.ImportResult; import org.ethereum.core.Transaction; import org.ethereum.crypto.ECKey; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.facade.EthereumImpl; import org.ethereum.facade.SyncStatus; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.net.eth.handler.Eth62; import org.ethereum.net.rlpx.Node; import org.ethereum.net.server.Channel; import org.ethereum.util.FastByteComparisons; import org.ethereum.util.blockchain.EtherUtil; import org.ethereum.util.blockchain.StandaloneBlockchain; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static java.util.concurrent.TimeUnit.SECONDS; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.FileUtil.recursiveDelete; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.spongycastle.util.encoders.Hex.decode; /** * If Miner is started manually, sync status is not changed in any manner, * so if miner is started while the peer is in Long Sync mode, miner creates * new blocks but ignores any txs, because they are dropped by {@link org.ethereum.core.PendingStateImpl} * While automatic detection of long sync works correctly in any live network * with big number of peers, automatic detection of Short Sync condition in * detached or small private networks looks not doable. * * To resolve this and any other similar issues manual switch to Short Sync mode * was added: {@link EthereumImpl#switchToShortSync()} * This test verifies that manual switching to Short Sync works correctly * and solves miner issue. */ @Ignore("Long network tests") public class SyncDoneTest { private static Node nodeA; private static List<Block> mainB1B10; private Ethereum ethereumA; private Ethereum ethereumB; private String testDbA; private String testDbB; private final static int MAX_SECONDS_WAIT = 60; @BeforeClass public static void setup() throws IOException, URISyntaxException { nodeA = new Node("enode://3973cb86d7bef9c96e5d589601d788370f9e24670dcba0480c0b3b1b0647d13d0f0fffed115dd2d4b5ca1929287839dcd4e77bdc724302b44ae48622a8766ee6@localhost:30334"); SysPropConfigA.props.overrideParams( "peer.listen.port", "30334", "peer.privateKey", "3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c", "genesis", "genesis-light-old.json", "sync.enabled", "true", "mine.fullDataSet", "false" ); SysPropConfigB.props.overrideParams( "peer.listen.port", "30335", "peer.privateKey", "6ef8da380c27cea8fdf7448340ea99e8e2268fc2950d79ed47cbf6f85dc977ec", "genesis", "genesis-light-old.json", "sync.enabled", "true", "mine.fullDataSet", "false" ); mainB1B10 = loadBlocks("sync/main-b1-b10.dmp"); } private static List<Block> loadBlocks(String path) throws URISyntaxException, IOException { URL url = ClassLoader.getSystemResource(path); File file = new File(url.toURI()); List<String> strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); List<Block> blocks = new ArrayList<>(strData.size()); for (String rlp : strData) { blocks.add(new Block(decode(rlp))); } return blocks; } @AfterClass public static void cleanup() { SystemProperties.getDefault().setBlockchainConfig(MainNetConfig.INSTANCE); } @Before public void setupTest() throws InterruptedException { testDbA = "test_db_" + new BigInteger(32, new Random()); testDbB = "test_db_" + new BigInteger(32, new Random()); SysPropConfigA.props.setDataBaseDir(testDbA); SysPropConfigB.props.setDataBaseDir(testDbB); } @After public void cleanupTest() { recursiveDelete(testDbA); recursiveDelete(testDbB); SysPropConfigA.eth62 = null; } // positive gap, A on main, B on main // expected: B downloads missed blocks from A => B on main @Test public void test1() throws InterruptedException { setupPeers(); // A == B == genesis Blockchain blockchainA = (Blockchain) ethereumA.getBlockchain(); for (Block b : mainB1B10) { ImportResult result = blockchainA.tryToConnect(b); System.out.println(result.isSuccessful()); } long loadedBlocks = blockchainA.getBestBlock().getNumber(); // Check that we are synced and on the same block assertTrue(loadedBlocks > 0); final CountDownLatch semaphore = new CountDownLatch(1); ethereumB.addListener(new EthereumListenerAdapter() { @Override public void onBlock(BlockSummary blockSummary) { if (blockSummary.getBlock().getNumber() == loadedBlocks) { semaphore.countDown(); } } }); semaphore.await(MAX_SECONDS_WAIT, SECONDS); Assert.assertEquals(0, semaphore.getCount()); assertEquals(loadedBlocks, ethereumB.getBlockchain().getBestBlock().getNumber()); ethereumA.getBlockMiner().startMining(); final CountDownLatch semaphore2 = new CountDownLatch(2); ethereumB.addListener(new EthereumListenerAdapter() { @Override public void onBlock(BlockSummary blockSummary) { if (blockSummary.getBlock().getNumber() == loadedBlocks + 2) { semaphore2.countDown(); ethereumA.getBlockMiner().stopMining(); } } }); ethereumA.addListener(new EthereumListenerAdapter(){ @Override public void onBlock(BlockSummary blockSummary) { if (blockSummary.getBlock().getNumber() == loadedBlocks + 2) { semaphore2.countDown(); } } }); semaphore2.await(MAX_SECONDS_WAIT, SECONDS); Assert.assertEquals(0, semaphore2.getCount()); assertFalse(ethereumA.getSyncStatus().getStage().equals(SyncStatus.SyncStage.Complete)); assertTrue(ethereumB.getSyncStatus().getStage().equals(SyncStatus.SyncStage.Complete)); // Receives NEW_BLOCKs from EthereumA // Trying to include txs while miner is on long sync // Txs should be dropped as peer is not on short sync ECKey sender = ECKey.fromPrivate(Hex.decode("3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c")); Transaction tx = Transaction.create( Hex.toHexString(ECKey.fromPrivate(sha3("cow".getBytes())).getAddress()), EtherUtil.convert(1, EtherUtil.Unit.ETHER), BigInteger.ZERO, BigInteger.valueOf(ethereumA.getGasPrice()), new BigInteger("3000000"), null ); tx.sign(sender); final CountDownLatch txSemaphore = new CountDownLatch(1); ethereumA.addListener(new EthereumListenerAdapter(){ @Override public void onBlock(BlockSummary blockSummary) { if (!blockSummary.getBlock().getTransactionsList().isEmpty() && FastByteComparisons.equal(blockSummary.getBlock().getTransactionsList().get(0).getSender(), sender.getAddress()) && blockSummary.getReceipts().get(0).isSuccessful()) { txSemaphore.countDown(); } } }); ethereumB.submitTransaction(tx); final CountDownLatch semaphore3 = new CountDownLatch(2); ethereumB.addListener(new EthereumListenerAdapter() { @Override public void onBlock(BlockSummary blockSummary) { if (blockSummary.getBlock().getNumber() == loadedBlocks + 5) { semaphore3.countDown(); } } }); ethereumA.addListener(new EthereumListenerAdapter(){ @Override public void onBlock(BlockSummary blockSummary) { if (blockSummary.getBlock().getNumber() == loadedBlocks + 5) { semaphore3.countDown(); ethereumA.getBlockMiner().stopMining(); } } }); ethereumA.getBlockMiner().startMining(); semaphore3.await(MAX_SECONDS_WAIT, SECONDS); Assert.assertEquals(0, semaphore3.getCount()); Assert.assertEquals(loadedBlocks + 5, ethereumA.getBlockchain().getBestBlock().getNumber()); Assert.assertEquals(loadedBlocks + 5, ethereumB.getBlockchain().getBestBlock().getNumber()); assertFalse(ethereumA.getSyncStatus().getStage().equals(SyncStatus.SyncStage.Complete)); // Tx was not included, because miner is on long sync assertFalse(txSemaphore.getCount() == 0); ethereumA.getBlockMiner().startMining(); try { ethereumA.switchToShortSync().get(1, TimeUnit.SECONDS); } catch (ExecutionException | TimeoutException e) { e.printStackTrace(); } assertTrue(ethereumA.getSyncStatus().getStage().equals(SyncStatus.SyncStage.Complete)); Transaction tx2 = Transaction.create( Hex.toHexString(ECKey.fromPrivate(sha3("cow".getBytes())).getAddress()), EtherUtil.convert(1, EtherUtil.Unit.ETHER), BigInteger.ZERO, BigInteger.valueOf(ethereumA.getGasPrice()).add(BigInteger.TEN), new BigInteger("3000000"), null ); tx2.sign(sender); ethereumB.submitTransaction(tx2); final CountDownLatch semaphore4 = new CountDownLatch(2); ethereumB.addListener(new EthereumListenerAdapter() { @Override public void onBlock(BlockSummary blockSummary) { if (blockSummary.getBlock().getNumber() == loadedBlocks + 9) { semaphore4.countDown(); ethereumA.getBlockMiner().stopMining(); } } }); ethereumA.addListener(new EthereumListenerAdapter(){ @Override public void onBlock(BlockSummary blockSummary) { if (blockSummary.getBlock().getNumber() == loadedBlocks + 9) { semaphore4.countDown(); } } }); semaphore4.await(MAX_SECONDS_WAIT, SECONDS); Assert.assertEquals(0, semaphore4.getCount()); Assert.assertEquals(loadedBlocks + 9, ethereumA.getBlockchain().getBestBlock().getNumber()); Assert.assertEquals(loadedBlocks + 9, ethereumB.getBlockchain().getBestBlock().getNumber()); assertTrue(ethereumA.getSyncStatus().getStage().equals(SyncStatus.SyncStage.Complete)); assertTrue(ethereumB.getSyncStatus().getStage().equals(SyncStatus.SyncStage.Complete)); // Tx is included! assertTrue(txSemaphore.getCount() == 0); } private void setupPeers() throws InterruptedException { ethereumA = EthereumFactory.createEthereum(SysPropConfigA.props, SysPropConfigA.class); ethereumB = EthereumFactory.createEthereum(SysPropConfigB.props, SysPropConfigB.class); final CountDownLatch semaphore = new CountDownLatch(1); ethereumB.addListener(new EthereumListenerAdapter() { @Override public void onPeerAddedToSyncPool(Channel peer) { semaphore.countDown(); } }); ethereumB.connect(nodeA); semaphore.await(10, SECONDS); if(semaphore.getCount() > 0) { fail("Failed to set up peers"); } } @Configuration @NoAutoscan public static class SysPropConfigA { static SystemProperties props = new SystemProperties(); static Eth62 eth62 = null; @Bean public SystemProperties systemProperties() { props.setBlockchainConfig(StandaloneBlockchain.getEasyMiningConfig()); return props; } @Bean @Scope("prototype") public Eth62 eth62() throws IllegalAccessException, InstantiationException { if (eth62 != null) return eth62; return new Eth62(); } } @Configuration @NoAutoscan public static class SysPropConfigB { static SystemProperties props = new SystemProperties(); @Bean public SystemProperties systemProperties() { props.setBlockchainConfig(StandaloneBlockchain.getEasyMiningConfig()); return props; } } }
14,679
38.146667
181
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/mine/EthashValidationHelperTest.java
package org.ethereum.mine; import org.junit.Test; import static org.ethereum.mine.EthashValidationHelper.CacheOrder.direct; import static org.ethereum.mine.EthashValidationHelper.CacheOrder.reverse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; /** * @author Mikhail Kalinin * @since 11.07.2018 */ public class EthashValidationHelperTest { static class EthashAlgoMock extends org.ethereum.mine.EthashAlgo { @Override public int[] makeCache(long cacheSize, byte[] seed) { return new int[0]; } } @Test // sequential direct caching public void testRegularFlow() { EthashValidationHelper ethash = new EthashValidationHelper(direct); ethash.ethashAlgo = new EthashAlgoMock(); // init on block 193, 0 and 1st epochs are cached ethash.preCache(193); assertNotNull(ethash.getCachedFor(193)); assertNotNull(ethash.getCachedFor(30_000)); assertEquals(ethash.caches.size(), 2); ethash = new EthashValidationHelper(direct); ethash.ethashAlgo = new EthashAlgoMock(); // genesis ethash.preCache(0); assertNotNull(ethash.getCachedFor(0)); assertEquals(ethash.caches.size(), 1); assertNull(ethash.getCachedFor(30_000)); // block 100, nothing has changed ethash.preCache(100); assertNotNull(ethash.getCachedFor(100)); assertEquals(ethash.caches.size(), 1); // block 193, next epoch must be added ethash.preCache(193); assertNotNull(ethash.getCachedFor(193)); assertNotNull(ethash.getCachedFor(30_000)); assertEquals(ethash.caches.size(), 2); // block 30_192, nothing has changed ethash.preCache(30_192); assertNotNull(ethash.getCachedFor(30_192)); assertNotNull(ethash.getCachedFor(192)); assertEquals(ethash.caches.size(), 2); // block 30_193, two epochs are kept: 1st and 2nd ethash.preCache(30_193); assertNotNull(ethash.getCachedFor(30_193)); assertNotNull(ethash.getCachedFor(60_000)); assertNull(ethash.getCachedFor(193)); assertEquals(ethash.caches.size(), 2); } @Test // sequential direct caching with gap between 0 and K block, K and N block public void testRegularFlowWithGap() { EthashValidationHelper ethash = new EthashValidationHelper(direct); ethash.ethashAlgo = new EthashAlgoMock(); // genesis ethash.preCache(0); assertNotNull(ethash.getCachedFor(0)); assertEquals(ethash.caches.size(), 1); assertNull(ethash.getCachedFor(30_000)); // block 100_000, cache must have been reset ethash.preCache(100_000); assertNotNull(ethash.getCachedFor(100_000)); assertNotNull(ethash.getCachedFor(120_000)); assertNull(ethash.getCachedFor(0)); assertEquals(ethash.caches.size(), 2); // block 120_193, caches shifted by one epoch ethash.preCache(120_193); assertNotNull(ethash.getCachedFor(120_000)); assertNotNull(ethash.getCachedFor(150_000)); assertNull(ethash.getCachedFor(100_000)); assertEquals(ethash.caches.size(), 2); // block 300_000, caches have been reset once again ethash.preCache(300_000); assertNotNull(ethash.getCachedFor(300_000)); assertNotNull(ethash.getCachedFor(299_000)); assertNull(ethash.getCachedFor(120_000)); assertNull(ethash.getCachedFor(150_000)); assertEquals(ethash.caches.size(), 2); } @Test // sequential reverse flow, like a flow that is used in reverse header downloading public void testReverseFlow() { EthashValidationHelper ethash = new EthashValidationHelper(reverse); ethash.ethashAlgo = new EthashAlgoMock(); // init on 15_000 block, 0 and 1st epochs are cached ethash.preCache(15_000); assertNotNull(ethash.getCachedFor(15_000)); assertNotNull(ethash.getCachedFor(30_000)); assertEquals(ethash.caches.size(), 2); ethash = new EthashValidationHelper(reverse); ethash.ethashAlgo = new EthashAlgoMock(); // init on 14_999 block, only 0 epoch is cached ethash.preCache(14_999); assertNotNull(ethash.getCachedFor(14_999)); assertNull(ethash.getCachedFor(30_000)); assertEquals(ethash.caches.size(), 1); ethash = new EthashValidationHelper(reverse); ethash.ethashAlgo = new EthashAlgoMock(); // init on 100_000 block, 2nd and 3rd epochs are cached ethash.preCache(100_000); assertNotNull(ethash.getCachedFor(100_000)); assertNotNull(ethash.getCachedFor(80_000)); assertNull(ethash.getCachedFor(120_000)); assertEquals(ethash.caches.size(), 2); // block 75_000, nothing has changed ethash.preCache(75_000); assertNotNull(ethash.getCachedFor(100_000)); assertNotNull(ethash.getCachedFor(75_000)); assertNull(ethash.getCachedFor(120_000)); assertNull(ethash.getCachedFor(59_000)); assertEquals(ethash.caches.size(), 2); // block 74_999, caches are shifted by 1 epoch toward 0 epoch ethash.preCache(74_999); assertNotNull(ethash.getCachedFor(74_999)); assertNotNull(ethash.getCachedFor(59_000)); assertNull(ethash.getCachedFor(100_000)); assertEquals(ethash.caches.size(), 2); // block 44_999, caches are shifted by 1 epoch toward 0 epoch ethash.preCache(44_999); assertNotNull(ethash.getCachedFor(44_999)); assertNotNull(ethash.getCachedFor(19_000)); assertNull(ethash.getCachedFor(80_000)); assertEquals(ethash.caches.size(), 2); // block 14_999, caches are shifted by 1 epoch toward 0 epoch ethash.preCache(14_999); assertNotNull(ethash.getCachedFor(14_999)); assertNotNull(ethash.getCachedFor(0)); assertNotNull(ethash.getCachedFor(30_000)); assertEquals(ethash.caches.size(), 2); // block 1, nothing has changed ethash.preCache(1); assertNotNull(ethash.getCachedFor(1)); assertNotNull(ethash.getCachedFor(0)); assertNotNull(ethash.getCachedFor(30_000)); assertEquals(ethash.caches.size(), 2); // block 0, nothing has changed ethash.preCache(0); assertNotNull(ethash.getCachedFor(0)); assertNotNull(ethash.getCachedFor(30_000)); assertEquals(ethash.caches.size(), 2); } @Test // sequential reverse flow with gap public void testReverseFlowWithGap() { EthashValidationHelper ethash = new EthashValidationHelper(reverse); ethash.ethashAlgo = new EthashAlgoMock(); // init on 300_000 block ethash.preCache(300_000); assertNotNull(ethash.getCachedFor(300_000)); assertNotNull(ethash.getCachedFor(275_000)); assertNull(ethash.getCachedFor(330_000)); assertEquals(ethash.caches.size(), 2); // jump to 100_000 block, 2nd and 3rd epochs are cached ethash.preCache(100_000); assertNotNull(ethash.getCachedFor(100_000)); assertNotNull(ethash.getCachedFor(80_000)); assertNull(ethash.getCachedFor(120_000)); assertEquals(ethash.caches.size(), 2); // block 74_999, caches are shifted by 1 epoch toward 0 epoch ethash.preCache(74_999); assertNotNull(ethash.getCachedFor(74_999)); assertNotNull(ethash.getCachedFor(59_000)); assertNull(ethash.getCachedFor(100_000)); assertEquals(ethash.caches.size(), 2); // jump to 14_999, caches are shifted by 1 epoch toward 0 epoch ethash.preCache(14_999); assertNotNull(ethash.getCachedFor(14_999)); assertNotNull(ethash.getCachedFor(0)); assertEquals(ethash.caches.size(), 1); } }
7,996
36.721698
92
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/mine/EthashTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import org.apache.commons.lang3.tuple.Pair; import org.ethereum.TestUtils; import org.ethereum.config.SystemProperties; import org.ethereum.core.Block; import org.ethereum.util.ByteUtil; import org.ethereum.util.FastByteComparisons; import org.ethereum.util.blockchain.StandaloneBlockchain; import org.junit.*; import org.spongycastle.util.encoders.Hex; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.*; import static org.junit.Assert.assertArrayEquals; /** * Created by Anton Nashatyrev on 02.12.2015. */ public class EthashTest { @BeforeClass public static void setup() { SystemProperties.getDefault().setBlockchainConfig(StandaloneBlockchain.getEasyMiningConfig()); } @AfterClass public static void cleanup() { SystemProperties.resetToDefault(); } @Test // check exact values public void test_0() { byte[] rlp = Hex.decode("f9021af90215a0809870664d9a43cf1827aa515de6374e2fad1bf64290a9f261dd49c525d6a0efa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794f927a40c8b7f6e07c5af7fa2155b4864a4112b13a010c8ec4f62ecea600c616443bcf527d97e5b1c5bb4a9769c496d1bf32636c95da056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000086015a1c28ae5e82bf958302472c808455c4e47b99476574682f76312e302e312f6c696e75782f676f312e342e32a0788ac534cb2f6a226a01535e29b11a96602d447aed972463b5cbcc7dd5d633f288e2ff1b6435006517c0c0"); Block b = new Block(rlp); EthashAlgo ethash = new EthashAlgo(); long cacheSize = ethash.getParams().getCacheSize(b.getNumber()); long fullSize = ethash.getParams().getFullSize(b.getNumber()); byte[] seedHash = ethash.getSeedHash(b.getNumber()); int[] cache = ethash.makeCache(cacheSize, seedHash); byte[] blockTrunkHash = sha3(b.getHeader().getEncodedWithoutNonce()); long nonce = ByteUtil.byteArrayToLong(b.getNonce()); long timeSum = 0; for (int i = 0; i < 100; i++) { long s = System.currentTimeMillis(); Pair<byte[], byte[]> pair = ethash.hashimotoLight(fullSize, cache, blockTrunkHash, longToBytes(nonce)); timeSum += System.currentTimeMillis() - s; System.out.println("Time: " + (System.currentTimeMillis() - s)); nonce++; } Assert.assertTrue("hashimotoLigt took > 500ms in avrg", timeSum / 100 < 500); Pair<byte[], byte[]> pair = ethash.hashimotoLight(fullSize, cache, blockTrunkHash, b.getNonce()); System.out.println(Hex.toHexString(pair.getLeft())); System.out.println(Hex.toHexString(pair.getRight())); byte[] boundary = b.getHeader().getPowBoundary(); byte[] pow = b.getHeader().calcPowValue(); assertArrayEquals(Hex.decode("0000000000bd59a74a8619f14c3d793747f1989a29ed6c83a5a488bac185679b"), boundary); assertArrayEquals(Hex.decode("000000000017f78925469f2f18fe7866ef6d3ed28d36fb013bc93d081e05809c"), pow); assertArrayEquals(pow, pair.getRight()); } @Test public void cacheTest() { EthashAlgo ethash = new EthashAlgo(); byte[] seed = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~".getBytes(); long cacheSize = 1024; long fullSize = 1024 * 32; int[] cache = ethash.makeCache(cacheSize, seed); Assert.assertArrayEquals(intsToBytes(cache, false), Hex.decode("2da2b506f21070e1143d908e867962486d6b0a02e31d468fd5e3a7143aafa76a14201f63374314e2a6aaf84ad2eb57105dea3378378965a1b3873453bb2b78f9a8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995ca8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995ca8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995c259440b89fa3481c2c33171477c305c8e1e421f8d8f6d59585449d0034f3e421808d8da6bbd0b6378f567647cc6c4ba6c434592b198ad444e7284905b7c6adaf70bf43ec2daa7bd5e8951aa609ab472c124cf9eba3d38cff5091dc3f58409edcc386c743c3bd66f92408796ee1e82dd149eaefbf52b00ce33014a6eb3e50625413b072a58bc01da28262f42cbe4f87d4abc2bf287d15618405a1fe4e386fcdafbb171064bd99901d8f81dd6789396ce5e364ac944bbbd75a7827291c70b42d26385910cd53ca535ab29433dd5c5714d26e0dce95514c5ef866329c12e958097e84462197c2b32087849dab33e88b11da61d52f9dbc0b92cc61f742c07dbbf751c49d7678624ee60dfbe62e5e8c47a03d8247643f3d16ad8c8e663953bcda1f59d7e2d4a9bf0768e789432212621967a8f41121ad1df6ae1fa78782530695414c6213942865b2730375019105cae91a4c17a558d4b63059661d9f108362143107babe0b848de412e4da59168cce82bfbff3c99e022dd6ac1e559db991f2e3f7bb910cefd173e65ed00a8d5d416534e2c8416ff23977dbf3eb7180b75c71580d08ce95efeb9b0afe904ea12285a392aff0c8561ff79fca67f694a62b9e52377485c57cc3598d84cac0a9d27960de0cc31ff9bbfe455acaa62c8aa5d2cce96f345da9afe843d258a99c4eaf3650fc62efd81c7b81cd0d534d2d71eeda7a6e315d540b4473c80f8730037dc2ae3e47b986240cfc65ccc565f0d8cde0bc68a57e39a271dda57440b3598bee19f799611d25731a96b5dbbbefdff6f4f656161462633030d62560ea4e9c161cf78fc96a2ca5aaa32453a6c5dea206f766244e8c9d9a8dc61185ce37f1fc804459c5f07434f8ecb34141b8dcae7eae704c950b55556c5f40140c3714b45eddb02637513268778cbf937a33e4e33183685f9deb31ef54e90161e76d969587dd782eaa94e289420e7c2ee908517f5893a26fdb5873d68f92d118d4bcf98d7a4916794d6ab290045e30f9ea00ca547c584b8482b0331ba1539a0f2714fddc3a0b06b0cfbb6a607b8339c39bcfd6640b1f653e9d70ef6c985b")); int[] bytes = ethash.calcDatasetItem(cache, 0); Assert.assertArrayEquals(intsToBytes(bytes, false), Hex.decode("b1698f829f90b35455804e5185d78f549fcb1bdce2bee006d4d7e68eb154b596be1427769eb1c3c3e93180c760af75f81d1023da6a0ffbe321c153a7c0103597")); byte[] blockHash = "~~~X~~~~~~~~~~~~~~~~~~~~~~~~~~~~".getBytes(); long nonce = 0x7c7c597cL; Pair<byte[], byte[]> pair = ethash.hashimotoLight(fullSize, cache, blockHash, longToBytes(nonce)); // comparing mix hash Assert.assertArrayEquals(pair.getLeft(), Hex.decode("d7b668b90c2f26961d98d7dd244f5966368165edbce8cb8162dd282b6e5a8eae")); // comparing the final hash Assert.assertArrayEquals(pair.getRight(), Hex.decode("b8cb1cb3ac1a7a6e12c4bc90f2779ef97e661f7957619e677636509d2f26055c")); System.out.println(Hex.toHexString(pair.getLeft())); System.out.println(Hex.toHexString(pair.getRight())); } @Test public void cacheTestFast() { EthashAlgo ethash = new EthashAlgo(); byte[] seed = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~".getBytes(); long cacheSize = 1024; long fullSize = 1024 * 32; int[] cache = ethash.makeCache(cacheSize, seed); Assert.assertArrayEquals(intsToBytes(cache, false), Hex.decode("2da2b506f21070e1143d908e867962486d6b0a02e31d468fd5e3a7143aafa76a14201f63374314e2a6aaf84ad2eb57105dea3378378965a1b3873453bb2b78f9a8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995ca8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995ca8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995c259440b89fa3481c2c33171477c305c8e1e421f8d8f6d59585449d0034f3e421808d8da6bbd0b6378f567647cc6c4ba6c434592b198ad444e7284905b7c6adaf70bf43ec2daa7bd5e8951aa609ab472c124cf9eba3d38cff5091dc3f58409edcc386c743c3bd66f92408796ee1e82dd149eaefbf52b00ce33014a6eb3e50625413b072a58bc01da28262f42cbe4f87d4abc2bf287d15618405a1fe4e386fcdafbb171064bd99901d8f81dd6789396ce5e364ac944bbbd75a7827291c70b42d26385910cd53ca535ab29433dd5c5714d26e0dce95514c5ef866329c12e958097e84462197c2b32087849dab33e88b11da61d52f9dbc0b92cc61f742c07dbbf751c49d7678624ee60dfbe62e5e8c47a03d8247643f3d16ad8c8e663953bcda1f59d7e2d4a9bf0768e789432212621967a8f41121ad1df6ae1fa78782530695414c6213942865b2730375019105cae91a4c17a558d4b63059661d9f108362143107babe0b848de412e4da59168cce82bfbff3c99e022dd6ac1e559db991f2e3f7bb910cefd173e65ed00a8d5d416534e2c8416ff23977dbf3eb7180b75c71580d08ce95efeb9b0afe904ea12285a392aff0c8561ff79fca67f694a62b9e52377485c57cc3598d84cac0a9d27960de0cc31ff9bbfe455acaa62c8aa5d2cce96f345da9afe843d258a99c4eaf3650fc62efd81c7b81cd0d534d2d71eeda7a6e315d540b4473c80f8730037dc2ae3e47b986240cfc65ccc565f0d8cde0bc68a57e39a271dda57440b3598bee19f799611d25731a96b5dbbbefdff6f4f656161462633030d62560ea4e9c161cf78fc96a2ca5aaa32453a6c5dea206f766244e8c9d9a8dc61185ce37f1fc804459c5f07434f8ecb34141b8dcae7eae704c950b55556c5f40140c3714b45eddb02637513268778cbf937a33e4e33183685f9deb31ef54e90161e76d969587dd782eaa94e289420e7c2ee908517f5893a26fdb5873d68f92d118d4bcf98d7a4916794d6ab290045e30f9ea00ca547c584b8482b0331ba1539a0f2714fddc3a0b06b0cfbb6a607b8339c39bcfd6640b1f653e9d70ef6c985b")); int[] i = ethash.calcDatasetItem(cache, 0); Assert.assertArrayEquals(intsToBytes(i, false), Hex.decode("b1698f829f90b35455804e5185d78f549fcb1bdce2bee006d4d7e68eb154b596be1427769eb1c3c3e93180c760af75f81d1023da6a0ffbe321c153a7c0103597")); // byte[] blockHash = "~~~X~~~~~~~~~~~~~~~~~~~~~~~~~~~~".getBytes(); long nonce = 0x7c7c597cL; Pair<byte[], byte[]> pair = ethash.hashimotoLight(fullSize, cache, blockHash, longToBytes(nonce)); // comparing mix hash Assert.assertArrayEquals(pair.getLeft(), Hex.decode("d7b668b90c2f26961d98d7dd244f5966368165edbce8cb8162dd282b6e5a8eae")); // comparing the final hash Assert.assertArrayEquals(pair.getRight(), Hex.decode("b8cb1cb3ac1a7a6e12c4bc90f2779ef97e661f7957619e677636509d2f26055c")); System.out.println(Hex.toHexString(pair.getLeft())); System.out.println(Hex.toHexString(pair.getRight())); } @Test public void realBlockValidateTest1() { byte[] rlp = Hex.decode("f9021af90215a0809870664d9a43cf1827aa515de6374e2fad1bf64290a9f261dd49c525d6a0efa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794f927a40c8b7f6e07c5af7fa2155b4864a4112b13a010c8ec4f62ecea600c616443bcf527d97e5b1c5bb4a9769c496d1bf32636c95da056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000086015a1c28ae5e82bf958302472c808455c4e47b99476574682f76312e302e312f6c696e75782f676f312e342e32a0788ac534cb2f6a226a01535e29b11a96602d447aed972463b5cbcc7dd5d633f288e2ff1b6435006517c0c0"); Block b = new Block(rlp); EthashAlgo ethash = new EthashAlgo(); long cacheSize = ethash.getParams().getCacheSize(b.getNumber()); long fullSize = ethash.getParams().getFullSize(b.getNumber()); byte[] seedHash = ethash.getSeedHash(b.getNumber()); long s = System.currentTimeMillis(); int[] cache = ethash.makeCache(cacheSize, seedHash); System.out.println("Cache generation took: " + (System.currentTimeMillis() - s) + " ms"); byte[] blockTruncHash = sha3(b.getHeader().getEncodedWithoutNonce()); Pair<byte[], byte[]> pair = ethash.hashimotoLight(fullSize, cache, blockTruncHash, b.getNonce()); System.out.println(Hex.toHexString(pair.getLeft())); System.out.println(Hex.toHexString(pair.getRight())); byte[] boundary = b.getHeader().getPowBoundary(); Assert.assertTrue(FastByteComparisons.compareTo(pair.getRight(), 0, 32, boundary, 0, 32) < 0); } @Test public void realBlockValidateTest2() { byte[] rlp = Hex.decode("f9021af90215a06b42cf11dbb8a448a118939d1a68773f3deca05f8063d26113dac5f9f8ce6713a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d493479452bc44d5378309ee2abf1539bf71de1b7d7be3b5a037b5b65861017992bd33375bb71e0752d57eb94972a9496177f056aa340a2843a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008606b6e75611ca830a2ace832fefd880845668803198d783010203844765746887676f312e342e32856c696e7578a08eddfce4ba14ac38363b0534d12ed7ad4c224897dd443730256f04c6f835449f88108919adc0f2952bc0c0"); Block b = new Block(rlp); System.out.println(b); boolean valid = Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).validate(b.getHeader()); Assert.assertTrue(valid); } @Test public void realBlockValidateTest3() { String blocks = "f9021af90215a0cc395ced01d7af387640ac1258ab8819b84ca3e59ff476d933441c3800c63928a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794738db714c08b8a32a29e0e68af00215079aa9c5ca03665d3f9edac25c8a8cdad22945e0fb2e6812f679bea3445639b3890f310ced9a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008606b4637b26e7830a2ac9832fefd8808456687ffc98d783010203844765746887676f312e352e31856c696e7578a0a64edb0df18caa7d36fcb8ca740fee12d4d82b39883ddb3d729414122ba7410688524d07ed4c40ab09c0c0\n" + "f9021af90215a0c49ccf0465b0222c815aed70ec9a8317ffe2cfe3539e9340c6bbeb06699a80dea01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347942a65aca4d5fc5b5c859090a6c34d164135398226a00a550ad67f02eeb6030abf46f9c88435a05b058374ea1ee4c177ef28c4d2f475a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008606b53a07965b830a2aca832fefd880845668800198d783010302844765746887676f312e352e31856c696e7578a035f6b345260d8c3807bb0e805f23866c5ba9431a9e9a5e240101f541990f47f5886796ab8d23f3c3c2c0c0\n" + "f9021af90215a076e41437e45099f2a0872a8df8623a644ead1136afe751358c56781513ecb74ea01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d493479452bc44d5378309ee2abf1539bf71de1b7d7be3b5a09b0dcb614329b921c4ef22eb4f8a913539806da3cbe43c1eafa37cfa3943a845a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008606b610aed75d830a2acb832fefd880845668800598d783010203844765746887676f312e342e32856c696e7578a056ac10c8b2378f46b610db89631968bc5f409f32934f287b95d5cfbe12cefd05886ba4adf9b970445ec0c0\n" + "f902fdf90217a09daf27b854a6e1272c2f3070f7729ba5f4891a9dc324c360a0ad32d1d62419f7a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794790b8a3ce86e707ed0ed32bf89b3269692a23cc1a02b7e61e61837adb79b36eee4e1589b2c2140852bb105dc034d5cfa052c6ef5b8a0b36ebb69537e04d3bcd94a20bebcb12a8ef4715eb26fc1d19382392cc98db9b1a0c86bea989ed46040c5d1cbc39da108fb249bb9bf0804a5889e897f7e0c710864b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008606b539ecc193830a2acc832fefd882a410845668801a98d783010302844765746887676f312e352e31856c696e7578a0d82d30ce9d68e733738eee0c6f37c95968622878334f4f010e95acae000bb40188b34e28af786cc323f8e0f86f82d65e850ba43b740083015f9094ff45159c63fb01f45cd86767a020406f06faa8528820d3ff69fe230800801ba0d0ea8a650bf50b61b421e8275a79219988889c3e86460b323fb3d4d60bd80d3ca05a653410e7fd97786b3b503936127ece61ed3dcfabdbcbe8d7f06066f4a41687f86d822a3b850ba43b740082520894c47aaa860008be6f65b58c6c6e02a84e666efe318742087a56e84c00801ca0bc2b89b75b68e7ad8eb1db4de4aa550db79df3bd6430f2258fe55805ca7d7fe7a07d8b53c48f24788f21e3a26cfbd007cdab71a8ef7f28f6f6fae6ed4dcd4a0df1c0\n" + "f9021af90215a07cda9a6543dfcafccba0aa0a1a78156ecc7f4b679b8401aec57472294db63a06a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d493479452bc44d5378309ee2abf1539bf71de1b7d7be3b5a0ac89cd6a0d58b13786cef698cfeda1f21edbfbd00b67db034cf2f62497b95359a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008606b61093ff3b830a2acd832fefd880845668802598d783010203844765746887676f312e342e32856c696e7578a0b969e4528849b36fc9c019e83e53cee58e5ef6c3fb3b00105570e602b2a39f1f88aabdc28bdf9e4799c0c0\n" + "f9021af90215a06b42cf11dbb8a448a118939d1a68773f3deca05f8063d26113dac5f9f8ce6713a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d493479452bc44d5378309ee2abf1539bf71de1b7d7be3b5a037b5b65861017992bd33375bb71e0752d57eb94972a9496177f056aa340a2843a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008606b6e75611ca830a2ace832fefd880845668803198d783010203844765746887676f312e342e32856c696e7578a08eddfce4ba14ac38363b0534d12ed7ad4c224897dd443730256f04c6f835449f88108919adc0f2952bc0c0\n" + "f9036ef90217a0cb927dc709468a107fac77151c6dff1ab73eabcccc57d82d238a7b5554f6db51a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794580992b51e3925e23280efb93d3047c82f17e038a03a68272caba0b4a825667d3d223bb8c18f6f793bd8151822b27798716c0b23cba01e360dfc633f5d2edad4e75cfa36555ae480ce346dcce8f253bb0d298e043dcaa0644b51189a7f9d4287e78fb923ced0b8b30edee234d6756fd06b45abc7ec12bdb90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008606b7be32fc9c830a2acf832fefd882f618845668803a98d783010400844765746887676f312e352e31856c696e7578a09a1a1cb1182fa1c8baeb7f2abd3f109d85b136f5968c76c3c26977dad5dba1ec88de7908cc14f57037f90150f86e82b609850ba43b740083015f909454cec426307c1acaa63b25aa48fade5df9e5d418872fe2475ad71000801ba0884206762dfebbdc69d5fb92ca1c33999a419f9c9ec116e02594f9535a30c9a0a05daf584f1b480ff599e4ed62278bac9c9d4c4f16af1d65504c13dbb713aa3539f86f82b60a850ba43b740083015f9094f442c4ab4d8cf106bcda6b1f7994485f3f4291a9880df897c536bccc00801ba0a7c7855917b5f8319651d241f3ca2ac5d728a76c83c43cb9e60adc9af1988051a009f117ce8cdfccc762d7a221abc19eb8773176c6f56b75c8ce2a1b907e0a3babf86d81d6850ba43b740082562294fbb1b73c4f0bda4f67dca266ce6ef42f520fbb988820d04471d11f6800801ba065586cc9545ea639580de624574644c34ea9bd0d2e7bfd8bab8f5ed3de572d86a0431d8fc8fcc803413f9f0ded6eaf267cb072bfed75fff97286623dd78e0e3d40c0"; for (String s : blocks.split("\\n")) { Block b = new Block(Hex.decode(s)); System.out.println(b); boolean valid = Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).validate(b.getHeader()); Assert.assertTrue(valid); } System.out.println("OK"); } @Test public void blockMineTest()throws Exception { byte[] rlp = Hex.decode("f9021af90215a0809870664d9a43cf1827aa515de6374e2fad1bf64290a9f261dd49c525d6a0efa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794f927a40c8b7f6e07c5af7fa2155b4864a4112b13a010c8ec4f62ecea600c616443bcf527d97e5b1c5bb4a9769c496d1bf32636c95da056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008600000000010082bf958302472c808455c4e47b99476574682f76312e302e312f6c696e75782f676f312e342e32a0788ac534cb2f6a226a01535e29b11a96602d447aed972463b5cbcc7dd5d633f288e2ff1b6435006517c0c0"); Block b = new Block(rlp); System.out.println(b); long nonce = Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).mineLight(b).get().nonce; b.setNonce(longToBytes(nonce)); Assert.assertTrue(Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).validate(b.getHeader())); } @Test public void changeEpochTestLight()throws Exception { List<Block> blocks = TestUtils.getRandomChain(new byte[32], 29999, 3); for (Block b : blocks) { b.getHeader().setDifficulty(ByteUtil.intToBytes(100)); b.setNonce(new byte[0]); long nonce = Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).mineLight(b).get().nonce; b.setNonce(longToBytes(nonce)); Assert.assertTrue(Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).validate(b.getHeader())); } } @Ignore // takes ~20 min @Test public void changeEpochTest()throws Exception { List<Block> blocks = TestUtils.getRandomChain(new byte[32], 29999, 3); for (Block b : blocks) { b.getHeader().setDifficulty(ByteUtil.intToBytes(100)); b.setNonce(new byte[0]); long nonce = Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).mine(b).get().nonce; b.setNonce(longToBytes(nonce)); Assert.assertTrue(Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).validate(b.getHeader())); } } @Test public void mineCancelTest() throws Exception { byte[] rlp = Hex.decode("f9021af90215a0809870664d9a43cf1827aa515de6374e2fad1bf64290a9f261dd49c525d6a0efa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794f927a40c8b7f6e07c5af7fa2155b4864a4112b13a010c8ec4f62ecea600c616443bcf527d97e5b1c5bb4a9769c496d1bf32636c95da056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008600000000010082bf958302472c808455c4e47b99476574682f76312e302e312f6c696e75782f676f312e342e32a0788ac534cb2f6a226a01535e29b11a96602d447aed972463b5cbcc7dd5d633f288e2ff1b6435006517c0c0"); // small difficulty Block b = new Block(rlp); // large difficulty Block difficultBlock = new Block(Hex.decode("f9021af90215a0809870664d9a43cf1827aa515de6374e2fad1bf64290a9f261dd49c525d6a0efa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794f927a40c8b7f6e07c5af7fa2155b4864a4112b13a010c8ec4f62ecea600c616443bcf527d97e5b1c5bb4a9769c496d1bf32636c95da056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008600000001000082bf958302472c808455c4e47b99476574682f76312e302e312f6c696e75782f676f312e342e32a0788ac534cb2f6a226a01535e29b11a96602d447aed972463b5cbcc7dd5d633f288e2ff1b6435006517c0c0")); // first warming up for the cache to be created System.out.println("Warming..."); long res = Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).mineLight(b).get().nonce; System.out.println("Submitting..."); Future<MinerIfc.MiningResult> light = Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).mineLight(difficultBlock, 8); Thread.sleep(200); long s = System.nanoTime(); boolean cancel = light.cancel(true); try { System.out.println("Waiting"); light.get(); Assert.assertTrue(false); } catch (InterruptedException|ExecutionException|CancellationException e) { System.out.println("Exception: ok"); } long t = System.nanoTime() - s; System.out.println("Time: " + (t / 1000) + " usec"); Assert.assertTrue(cancel); Assert.assertTrue(t < 500_000_000); Assert.assertTrue(light.isCancelled()); b.setNonce(new byte[0]); Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).mineLight(b, 8).get(); boolean validate = Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).validate(b.getHeader()); Assert.assertTrue(validate); } @Test @Ignore public void fullDagTime() { EthashAlgo ethashAlgo = new EthashAlgo(); System.out.println("Calculating cache..."); int[] cache = ethashAlgo.makeCache(16_000_000, ethashAlgo.getSeedHash(0)); long s = System.currentTimeMillis(); System.out.println("Calculating full DAG..."); // ethashAlgo.calcDataset(1_000_000_000, cache); int[][] ret = new int[(1_000_000_000 / ethashAlgo.getParams().getHASH_BYTES())][]; long ss = 0; for (int i = 0; i < ret.length; i++) { ret[i] = ethashAlgo.calcDatasetItem(cache, i); if (i % 10000 == 0 && i > 0) { System.out.println("Calculated " + i + " of " + ret.length + " in "+ (System.currentTimeMillis() - s) / 1000 + " sec " + "Speed: " + (i - 100000) / ((System.currentTimeMillis() - ss) / 1000d) + " items/sec"); if (i == 100000) ss = System.currentTimeMillis(); } } System.out.println("Calculated in " + (System.currentTimeMillis() - s) / 1000 + " sec"); } @Test @Ignore public void fullDagMineTime() throws ExecutionException, InterruptedException { Ethash.fileCacheEnabled = true; byte[] rlp = Hex.decode("f9021af90215a0809870664d9a43cf1827aa515de6374e2fad1bf64290a9f261dd49c525d6a0efa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794f927a40c8b7f6e07c5af7fa2155b4864a4112b13a010c8ec4f62ecea600c616443bcf527d97e5b1c5bb4a9769c496d1bf32636c95da056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008600000000010082bf958302472c808455c4e47b99476574682f76312e302e312f6c696e75782f676f312e342e32a0788ac534cb2f6a226a01535e29b11a96602d447aed972463b5cbcc7dd5d633f288e2ff1b6435006517c0c0"); // small difficulty Block b = new Block(rlp); b.getHeader().setDifficulty(longToBytesNoLeadZeroes(0x20000)); b.setExtraData(new byte[] {}); Ethash ethash = Ethash.getForBlock(SystemProperties.getDefault(), 0); System.out.println("Generating DAG..."); ethash.mine(b).get(); System.out.println("DAG generated..."); System.out.println("Mining block with diff: " + b.getDifficultyBI()); long s = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { b.setExtraData(intToBytes(i)); ethash.mine(b, 8).get(); if (!ethash.validate(b.getHeader())) { throw new RuntimeException("Not validated: " + b); } System.out.print("."); } System.out.println(); System.out.println("Mined 100 blocks in " + (System.currentTimeMillis() - s) / 1000 + " sec"); } }
33,792
100.786145
2,124
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/mine/FutureTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.junit.Test; import java.util.concurrent.*; /** * Created by Anton Nashatyrev on 17.12.2015. */ public class FutureTest { @Test public void interruptTest() throws InterruptedException { ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()); final ListenableFuture<Object> future = executor.submit(() -> { // try { System.out.println("Waiting"); Thread.sleep(10000); System.out.println("Complete"); return null; // } catch (Exception e) { // e.printStackTrace(); // throw e; // } }); future.addListener(() -> { System.out.println("Listener: " + future.isCancelled() + ", " + future.isDone()); try { future.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } }, MoreExecutors.directExecutor()); Thread.sleep(1000); future.cancel(true); } @Test public void guavaExecutor() throws ExecutionException, InterruptedException { // ListeningExecutorService executor = MoreExecutors.listeningDecorator( // new ThreadPoolExecutor(2, 16, 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>())); ExecutorService executor = new ThreadPoolExecutor(16, 16, 1L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1)); Future<Object> future = null; for (int i = 0; i < 4; i++) { final int ii = i; future = executor.submit(() -> { try { System.out.println("Waiting " + ii); Thread.sleep(5000); System.out.println("Complete " + ii); return null; } catch (Exception e) { e.printStackTrace(); throw e; } }); } future.get(); } @Test public void anyFutureTest() throws ExecutionException, InterruptedException { ListeningExecutorService executor = MoreExecutors.listeningDecorator( new ThreadPoolExecutor(16, 16, 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<>())); AnyFuture<Integer> anyFuture = new AnyFuture<Integer>() { @Override protected void postProcess(Integer integer) { System.out.println("FutureTest.postProcess:" + "integer = [" + integer + "]"); } }; for (int i = 0; i < 4; i++) { final int ii = i; ListenableFuture<Integer> future = executor.submit(() -> { System.out.println("Waiting " + ii); Thread.sleep(5000 - ii * 500); System.out.println("Complete " + ii); return ii; }); anyFuture.add(future); } Thread.sleep(1000); anyFuture.cancel(true); System.out.println("Getting anyFuture..."); System.out.println("anyFuture: " + anyFuture.isCancelled() + ", " + anyFuture.isDone()); anyFuture = new AnyFuture<Integer>() { @Override protected void postProcess(Integer integer) { System.out.println("FutureTest.postProcess:" + "integer = [" + integer + "]"); } }; for (int i = 0; i < 4; i++) { final int ii = i; ListenableFuture<Integer> future = executor.submit(() -> { System.out.println("Waiting " + ii); Thread.sleep(5000 - ii * 500); System.out.println("Complete " + ii); return ii; }); anyFuture.add(future); } System.out.println("Getting anyFuture..."); System.out.println("anyFuture.get(): " + anyFuture.get() + ", " + anyFuture.isCancelled() + ", " + anyFuture.isDone()); } }
5,117
38.369231
127
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/mine/MineBlock.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import org.ethereum.config.SystemProperties; import org.ethereum.config.blockchain.FrontierConfig; import org.ethereum.core.*; import org.ethereum.core.genesis.GenesisLoader; import org.ethereum.crypto.ECKey; import org.ethereum.db.PruneManager; import org.ethereum.util.ByteUtil; import org.ethereum.util.blockchain.StandaloneBlockchain; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.spongycastle.util.encoders.Hex; import javax.annotation.Resource; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Created by Anton Nashatyrev on 10.12.2015. */ public class MineBlock { @Mock PruneManager pruneManager; @InjectMocks @Resource BlockchainImpl blockchain = ImportLightTest.createBlockchain(GenesisLoader.loadGenesis( getClass().getResourceAsStream("/genesis/genesis-light.json"))); @BeforeClass public static void setup() { SystemProperties.getDefault().setBlockchainConfig(StandaloneBlockchain.getEasyMiningConfig()); } @AfterClass public static void cleanup() { SystemProperties.resetToDefault(); } @Before public void setUp() throws Exception { // Initialize mocks created above MockitoAnnotations.initMocks(this); } @Test public void mine1() throws Exception { blockchain.setMinerCoinbase(Hex.decode("ee0250c19ad59305b2bdb61f34b45b72fe37154f")); Block parent = blockchain.getBestBlock(); List<Transaction> pendingTx = new ArrayList<>(); ECKey senderKey = ECKey.fromPrivate(Hex.decode("3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c")); byte[] receiverAddr = Hex.decode("31e2e1ed11951c7091dfba62cd4b7145e947219c"); Transaction tx = new Transaction(new byte[] {0}, new byte[] {1}, ByteUtil.longToBytesNoLeadZeroes(0xfffff), receiverAddr, new byte[] {77}, new byte[0]); tx.sign(senderKey); pendingTx.add(tx); Block b = blockchain.createNewBlock(parent, pendingTx, Collections.EMPTY_LIST); System.out.println("Mining..."); Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).mineLight(b).get(); System.out.println("Validating..."); boolean valid = Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).validate(b.getHeader()); Assert.assertTrue(valid); System.out.println("Connecting..."); ImportResult importResult = blockchain.tryToConnect(b); Assert.assertTrue(importResult == ImportResult.IMPORTED_BEST); System.out.println(Hex.toHexString(blockchain.getRepository().getRoot())); } }
3,696
34.548077
124
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/mine/ExternalMinerTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.mine; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import org.ethereum.config.SystemProperties; import org.ethereum.config.blockchain.FrontierConfig; import org.ethereum.core.Block; import org.ethereum.core.BlockHeader; import org.ethereum.core.BlockchainImpl; import org.ethereum.core.ImportResult; import org.ethereum.db.PruneManager; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumImpl; import org.ethereum.listener.CompositeEthereumListener; import org.ethereum.util.ByteUtil; import org.ethereum.util.blockchain.LocalBlockchain; import org.ethereum.util.blockchain.StandaloneBlockchain; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.Resource; import java.math.BigInteger; import java.util.Collection; import static java.util.Collections.*; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; /** * Creates an instance */ public class ExternalMinerTest { private StandaloneBlockchain bc = new StandaloneBlockchain().withAutoblock(false); private CompositeEthereumListener listener = new CompositeEthereumListener(); @Mock private EthereumImpl ethereum; @InjectMocks @Resource private BlockMiner blockMiner = new BlockMiner(SystemProperties.getDefault(), listener, bc.getBlockchain(), bc.getBlockchain().getBlockStore(), bc.getPendingState());; @Before public void setup() { SystemProperties.getDefault().setBlockchainConfig(new FrontierConfig(new FrontierConfig.FrontierConstants() { @Override public BigInteger getMINIMUM_DIFFICULTY() { return BigInteger.ONE; } })); // Initialize mocks created above MockitoAnnotations.initMocks(this); when(ethereum.addNewMinedBlock(any(Block.class))).thenAnswer(new Answer<ImportResult>() { @Override public ImportResult answer(InvocationOnMock invocation) throws Throwable { Block block = (Block) invocation.getArguments()[0]; return bc.getBlockchain().tryToConnect(block); } }); } @Test public void externalMiner_shouldWork() throws Exception { final Block startBestBlock = bc.getBlockchain().getBestBlock(); final SettableFuture<MinerIfc.MiningResult> futureBlock = SettableFuture.create(); blockMiner.setExternalMiner(new MinerIfc() { @Override public ListenableFuture<MiningResult> mine(Block block) { // System.out.print("Mining requested"); return futureBlock; } @Override public boolean validate(BlockHeader blockHeader) { return true; } @Override public void setListeners(Collection<MinerListener> listeners) {} }); Block b = bc.getBlockchain().createNewBlock(startBestBlock, EMPTY_LIST, EMPTY_LIST); Ethash.getForBlock(SystemProperties.getDefault(), b.getNumber()).mineLight(b).get(); futureBlock.set(new MinerIfc.MiningResult(ByteUtil.byteArrayToLong(b.getNonce()), b.getMixHash(), b)); assertThat(bc.getBlockchain().getBestBlock().getNumber(), is(startBestBlock.getNumber() + 1)); } }
4,498
35.877049
117
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/PeerTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import org.ethereum.net.client.Capability; import org.ethereum.net.p2p.Peer; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; public class PeerTest { /* PEER */ @Test public void testPeer() { //Init InetAddress address = InetAddress.getLoopbackAddress(); List<Capability> capabilities = new ArrayList<>(); int port = 1010; String peerId = "1010"; Peer peerCopy = new Peer(address, port, peerId); //Peer Peer peer = new Peer(address, port, peerId); //getAddress assertEquals("127.0.0.1", peer.getAddress().getHostAddress()); //getPort assertEquals(port, peer.getPort()); //getPeerId assertEquals(peerId, peer.getPeerId()); //getCapabilities assertEquals(capabilities, peer.getCapabilities()); //getEncoded assertEquals("CC847F0000018203F2821010C0", Hex.toHexString(peer.getEncoded()).toUpperCase()); //toString assertEquals("[ip=" + address.getHostAddress() + " port=" + Integer.toString(port) + " peerId=" + peerId + "]", peer.toString()); //equals assertEquals(true, peer.equals(peerCopy)); assertEquals(false, peer.equals(null)); //hashCode assertEquals(-1218913009, peer.hashCode()); } }
2,285
28.307692
137
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/HelloMessageTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import org.ethereum.net.client.Capability; import org.ethereum.net.eth.EthVersion; import org.ethereum.net.p2p.HelloMessage; import org.ethereum.net.p2p.P2pHandler; import org.ethereum.net.p2p.P2pMessageCodes; import org.ethereum.net.shh.ShhHandler; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; public class HelloMessageTest { /* HELLO_MESSAGE */ private static final Logger logger = LoggerFactory.getLogger("test"); //Parsing from raw bytes @Test public void test1() { String helloMessageRaw = "f87902a5457468657265756d282b2b292f76302e372e392f52656c656173652f4c696e75782f672b2bccc58365746827c583736868018203e0b8401fbf1e41f08078918c9f7b6734594ee56d7f538614f602c71194db0a1af5a77f9b86eb14669fe7a8a46a2dd1b7d070b94e463f4ecd5b337c8b4d31bbf8dd5646"; byte[] payload = Hex.decode(helloMessageRaw); HelloMessage helloMessage = new HelloMessage(payload); logger.info(helloMessage.toString()); assertEquals(P2pMessageCodes.HELLO, helloMessage.getCommand()); assertEquals(2, helloMessage.getP2PVersion()); assertEquals("Ethereum(++)/v0.7.9/Release/Linux/g++", helloMessage.getClientId()); assertEquals(2, helloMessage.getCapabilities().size()); assertEquals(992, helloMessage.getListenPort()); assertEquals( "1fbf1e41f08078918c9f7b6734594ee56d7f538614f602c71194db0a1af5a77f9b86eb14669fe7a8a46a2dd1b7d070b94e463f4ecd5b337c8b4d31bbf8dd5646", helloMessage.getPeerId()); } //Instantiate from constructor @Test public void test2() { //Init byte version = 2; String clientStr = "Ethereum(++)/v0.7.9/Release/Linux/g++"; List<Capability> capabilities = Arrays.asList( new Capability(Capability.ETH, EthVersion.UPPER), new Capability(Capability.SHH, ShhHandler.VERSION), new Capability(Capability.P2P, P2pHandler.VERSION)); int listenPort = 992; String peerId = "1fbf1e41f08078918c9f7b6734594ee56d7f538614f602c71194db0a1af5a"; HelloMessage helloMessage = new HelloMessage(version, clientStr, capabilities, listenPort, peerId); logger.info(helloMessage.toString()); assertEquals(P2pMessageCodes.HELLO, helloMessage.getCommand()); assertEquals(version, helloMessage.getP2PVersion()); assertEquals(clientStr, helloMessage.getClientId()); assertEquals(3, helloMessage.getCapabilities().size()); assertEquals(listenPort, helloMessage.getListenPort()); assertEquals(peerId, helloMessage.getPeerId()); } //Fail test @Test public void test3() { //Init byte version = -1; //invalid version String clientStr = ""; //null id List<Capability> capabilities = Arrays.asList( new Capability(null, (byte) 0), new Capability(null, (byte) 0), null, //null here causes NullPointerException when using toString new Capability(null, (byte) 0)); //encoding null capabilities int listenPort = 99999; //invalid port String peerId = ""; //null id HelloMessage helloMessage = new HelloMessage(version, clientStr, capabilities, listenPort, peerId); assertEquals(P2pMessageCodes.HELLO, helloMessage.getCommand()); assertEquals(version, helloMessage.getP2PVersion()); assertEquals(clientStr, helloMessage.getClientId()); assertEquals(4, helloMessage.getCapabilities().size()); assertEquals(listenPort, helloMessage.getListenPort()); assertEquals(peerId, helloMessage.getPeerId()); } }
4,637
40.410714
282
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/NewBlockMessageTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import org.ethereum.net.eth.message.NewBlockMessage; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; public class NewBlockMessageTest { private static final Logger logger = LoggerFactory.getLogger("test"); /* NEW_BLOCK */ @Test public void test_1() { byte[] payload = Hex.decode("f90144f9013Bf90136a0d8faffbc4c4213d35db9007de41cece45d95db7fd6c0f129e158baa888c48eefa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4934794baedba0480e1b882b606cd302d8c4f5701cabac7a0c7d4565fb7b3d98e54a0dec8b76f8c001a784a5689954ce0aedcc1bbe8d13095a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b8400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083063477825fc88609184e72a0008301e8488084543ffee680a00de0b9d4a0f0c23546d31f1f70db00d25cf6a7af79365b4e058e4a6a3b69527bc0c0850177ddbebe"); NewBlockMessage newBlockMessage = new NewBlockMessage(payload); logger.trace("{}", newBlockMessage); } }
1,991
41.382979
694
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/MessageRoundtripTest.java
package org.ethereum.net; import org.ethereum.net.p2p.P2pMessage; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; /** * @author alexbraz * @since 29/03/2019 */ public class MessageRoundtripTest { @Test public void testMessageNotAnswered(){ P2pMessage message = mock(P2pMessage.class); MessageRoundtrip messageRoundtrip = new MessageRoundtrip(message); assertFalse(messageRoundtrip.isAnswered()); } @Test public void testMessageRetryTimes(){ P2pMessage message = mock(P2pMessage.class); MessageRoundtrip messageRoundtrip = new MessageRoundtrip(message); messageRoundtrip.incRetryTimes(); assertEquals(1L, messageRoundtrip.retryTimes); } @Test public void testMessageAnswered(){ P2pMessage message = mock(P2pMessage.class); MessageRoundtrip messageRoundtrip = new MessageRoundtrip(message); messageRoundtrip.answer(); assertTrue(messageRoundtrip.isAnswered()); } @Test public void testHasToRetry(){ P2pMessage message = mock(P2pMessage.class); MessageRoundtrip messageRoundtrip = new MessageRoundtrip(message); messageRoundtrip.saveTime(); assertFalse(messageRoundtrip.hasToRetry()); } }
1,330
27.319149
78
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/TransactionsMessageTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import org.ethereum.core.Transaction; import org.ethereum.crypto.ECKey; import org.ethereum.crypto.HashUtil; import org.ethereum.net.eth.message.EthMessageCodes; import org.ethereum.net.eth.message.TransactionsMessage; import org.ethereum.util.ByteUtil; import org.junit.Ignore; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import java.math.BigInteger; import java.util.*; import static org.junit.Assert.*; public class TransactionsMessageTest { /* TRANSACTIONS */ @Ignore @Test /* Transactions message 1 */ public void test_1() { String txsPacketRaw = "f86e12f86b04648609184e72a00094cd2a3d9f938e13cd947ec05abc7fe734df8dd826" + "881bc16d674ec80000801ba05c89ebf2b77eeab88251e553f6f9d53badc1d800" + "bbac02d830801c2aa94a4c9fa00b7907532b1f29c79942b75fff98822293bf5f" + "daa3653a8d9f424c6a3265f06c"; byte[] payload = Hex.decode(txsPacketRaw); TransactionsMessage transactionsMessage = new TransactionsMessage(payload); System.out.println(transactionsMessage); assertEquals(EthMessageCodes.TRANSACTIONS, transactionsMessage.getCommand()); assertEquals(1, transactionsMessage.getTransactions().size()); Transaction tx = transactionsMessage.getTransactions().iterator().next(); assertEquals("5d2aee0490a9228024158433d650335116b4af5a30b8abb10e9b7f9f7e090fd8", Hex.toHexString(tx.getHash())); assertEquals("04", Hex.toHexString(tx.getNonce())); assertEquals("1bc16d674ec80000", Hex.toHexString(tx.getValue())); assertEquals("cd2a3d9f938e13cd947ec05abc7fe734df8dd826", Hex.toHexString(tx.getReceiveAddress())); assertEquals("64", Hex.toHexString(tx.getGasPrice())); assertEquals("09184e72a000", Hex.toHexString(tx.getGasLimit())); assertEquals("", ByteUtil.toHexString(tx.getData())); assertEquals("1b", Hex.toHexString(new byte[]{tx.getSignature().v})); assertEquals("5c89ebf2b77eeab88251e553f6f9d53badc1d800bbac02d830801c2aa94a4c9f", Hex.toHexString(tx.getSignature().r.toByteArray())); assertEquals("0b7907532b1f29c79942b75fff98822293bf5fdaa3653a8d9f424c6a3265f06c", Hex.toHexString(tx.getSignature().s.toByteArray())); } @Ignore @Test /* Transactions message 2 */ public void test_2() { String txsPacketRaw = "f9025012f89d8080940000000000000000000000000000000000000000860918" + "4e72a000822710b3606956330c0d630000003359366000530a0d630000003359" + "602060005301356000533557604060005301600054630000000c588433606957" + "1ca07f6eb94576346488c6253197bde6a7e59ddc36f2773672c849402aa9c402" + "c3c4a06d254e662bf7450dd8d835160cbb053463fed0b53f2cdd7f3ea8731919" + "c8e8ccf901050180940000000000000000000000000000000000000000860918" + "4e72a000822710b85336630000002e59606956330c0d63000000155933ff3356" + "0d63000000275960003356576000335700630000005358600035560d63000000" + "3a590033560d63000000485960003356573360003557600035335700b84a7f4e" + "616d655265670000000000000000000000000000000000000000000000000030" + "57307f4e616d6552656700000000000000000000000000000000000000000000" + "00000057336069571ba04af15a0ec494aeac5b243c8a2690833faa74c0f73db1" + "f439d521c49c381513e9a05802e64939be5a1f9d4d614038fbd5479538c48795" + "614ef9c551477ecbdb49d2f8a6028094ccdeac59d35627b7de09332e819d5159" + "e7bb72508609184e72a000822710b84000000000000000000000000000000000" + "000000000000000000000000000000000000000000000000000000002d0aceee" + "7e5ab874e22ccf8d1a649f59106d74e81ba0d05887574456c6de8f7a0d172342" + "c2cbdd4cf7afe15d9dbb8b75b748ba6791c9a01e87172a861f6c37b5a9e3a5d0" + "d7393152a7fbe41530e5bb8ac8f35433e5931b"; byte[] payload = Hex.decode(txsPacketRaw); TransactionsMessage transactionsMessage = new TransactionsMessage(payload); System.out.println(transactionsMessage); assertEquals(EthMessageCodes.TRANSACTIONS, transactionsMessage.getCommand()); assertEquals(3, transactionsMessage.getTransactions().size()); Iterator<Transaction> txIter = transactionsMessage.getTransactions().iterator(); Transaction tx1 = txIter.next(); txIter.next(); // skip one Transaction tx3 = txIter.next(); assertEquals("1b9d9456293cbcbc2f28a0fdc67028128ea571b033fb0e21d0ee00bcd6167e5d", Hex.toHexString(tx3.getHash())); assertEquals("00", Hex.toHexString(tx3.getNonce())); assertEquals("2710", Hex.toHexString(tx3.getValue())); assertEquals("09184e72a000", Hex.toHexString(tx3.getReceiveAddress())); assertNull(tx3.getGasPrice()); assertEquals("0000000000000000000000000000000000000000", Hex.toHexString(tx3.getGasLimit())); assertEquals("606956330c0d630000003359366000530a0d630000003359602060005301356000533557604060005301600054630000000c58", Hex.toHexString(tx3.getData())); assertEquals("33", Hex.toHexString(new byte[]{tx3.getSignature().v})); assertEquals("1c", Hex.toHexString(tx3.getSignature().r.toByteArray())); assertEquals("7f6eb94576346488c6253197bde6a7e59ddc36f2773672c849402aa9c402c3c4", Hex.toHexString(tx3.getSignature().s.toByteArray())); // Transaction #2 assertEquals("dde9543921850f41ca88e5401322cd7651c78a1e4deebd5ee385af8ac343f0ad", Hex.toHexString(tx1.getHash())); assertEquals("02", Hex.toHexString(tx1.getNonce())); assertEquals("2710", Hex.toHexString(tx1.getValue())); assertEquals("09184e72a000", Hex.toHexString(tx1.getReceiveAddress())); assertNull(tx1.getGasPrice()); assertEquals("ccdeac59d35627b7de09332e819d5159e7bb7250", Hex.toHexString(tx1.getGasLimit())); assertEquals ("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000002d0aceee7e5ab874e22ccf8d1a649f59106d74e8", Hex.toHexString(tx1.getData())); assertEquals("1b", Hex.toHexString(new byte[]{tx1.getSignature().v})); assertEquals("00d05887574456c6de8f7a0d172342c2cbdd4cf7afe15d9dbb8b75b748ba6791c9", Hex.toHexString(tx1.getSignature().r.toByteArray())); assertEquals("1e87172a861f6c37b5a9e3a5d0d7393152a7fbe41530e5bb8ac8f35433e5931b", Hex.toHexString(tx1.getSignature().s.toByteArray())); } @Test /* Transactions msg encode */ public void test_3() throws Exception { String expected = "f872f870808b00d3c21bcecceda10000009479b08ad8787060333663d19704909ee7b1903e588609184e72a000824255801ca00f410a70e42b2c9854a8421d32c87c370a2b9fff0a27f9f031bb4443681d73b5a018a7dc4c4f9dee9f3dc35cb96ca15859aa27e219a8e4a8547be6bd3206979858"; BigInteger value = new BigInteger("1000000000000000000000000"); byte[] privKey = HashUtil.sha3("cat".getBytes()); ECKey ecKey = ECKey.fromPrivate(privKey); byte[] gasPrice = Hex.decode("09184e72a000"); byte[] gas = Hex.decode("4255"); Transaction tx = new Transaction(null, value.toByteArray(), ecKey.getAddress(), gasPrice, gas, null); tx.sign(privKey); tx.getEncoded(); TransactionsMessage transactionsMessage = new TransactionsMessage(Collections.singletonList(tx)); assertEquals(expected, Hex.toHexString(transactionsMessage.getEncoded())); } @Test public void test_4() { String msg = "f872f87083011a6d850ba43b740083015f9094ec210ec3715d5918b37cfa4d344a45d177ed849f881b461c1416b9d000801ba023a3035235ca0a6f80f08a1d4bd760445d5b0f8a25c32678fe18a451a88d6377a0765dde224118bdb40a67f315583d542d93d17d8637302b1da26e1013518d3ae8"; TransactionsMessage tmsg = new TransactionsMessage(Hex.decode(msg)); assertEquals(1, tmsg.getTransactions().size()); } }
9,079
42.864734
256
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/PingPongMessageTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import org.ethereum.net.p2p.P2pMessageCodes; import org.ethereum.net.p2p.PingMessage; import org.ethereum.net.p2p.PongMessage; import org.junit.Test; import static org.junit.Assert.assertEquals; public class PingPongMessageTest { /* PING_MESSAGE & PONG_MESSAGE */ @Test /* PingMessage */ public void testPing() { PingMessage pingMessage = new PingMessage(); System.out.println(pingMessage); assertEquals(PongMessage.class, pingMessage.getAnswerMessage()); assertEquals(P2pMessageCodes.PING, pingMessage.getCommand()); } @Test /* PongMessage */ public void testPong() { PongMessage pongMessage = new PongMessage(); System.out.println(pongMessage); assertEquals(P2pMessageCodes.PONG, pongMessage.getCommand()); assertEquals(null, pongMessage.getAnswerMessage()); } }
1,686
30.240741
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/NettyTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.handler.codec.MessageToMessageCodec; import io.netty.handler.codec.MessageToMessageDecoder; import io.netty.handler.codec.MessageToMessageEncoder; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.util.List; /** * Created by Anton Nashatyrev on 16.10.2015. */ public class NettyTest { @Test public void pipelineTest() { final int[] int2 = new int[1]; final boolean[] exception = new boolean[1]; final ByteToMessageDecoder decoder2 = new ByteToMessageDecoder() { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { int i = in.readInt(); System.out.println("decoder2 read int (4 bytes): " + Integer.toHexString(i)); int2[0] = i; if (i == 0) out.add("aaa"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("Decoder2 exception: " + cause); } }; final MessageToMessageCodec decoder3 = new MessageToMessageCodec<Object, Object>() { @Override protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception { System.out.println("NettyTest.decode: msg = [" + msg + "]"); if (msg == "aaa") { throw new RuntimeException("Test exception 3"); } } @Override protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception { throw new RuntimeException("Test exception 4"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("Decoder3 exception: " + cause); exception[0] = true; } }; final ByteToMessageDecoder decoder1 = new ByteToMessageDecoder() { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { int i = in.readInt(); System.out.println("decoder1 read int (4 bytes). Needs no more: " + Integer.toHexString(i)); ctx.pipeline().addAfter("decoder1", "decoder2", decoder2); ctx.pipeline().addAfter("decoder2", "decoder3", decoder3); ctx.pipeline().remove(this); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("Decoder1 exception: " + cause); } }; ChannelInboundHandlerAdapter initiator = new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addFirst("decoder1", decoder1); System.out.println("NettyTest.channelActive"); } }; EmbeddedChannel channel0 = new EmbeddedChannel(new ChannelOutboundHandlerAdapter() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { throw new RuntimeException("Test"); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("Exception caught: " + cause); } }); EmbeddedChannel channel = new EmbeddedChannel(initiator); ByteBuf buffer = Unpooled.buffer(); buffer.writeInt(0x12345678); buffer.writeInt(0xabcdefff); channel.writeInbound(buffer); Assert.assertEquals(0xabcdefff, int2[0]); channel.writeInbound(Unpooled.buffer().writeInt(0)); Assert.assertTrue(exception[0]); // Need the following for the exception in outbound handler to be fired // ctx.writeAndFlush(msg).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); // exception[0] = false; // channel.writeOutbound("outMsg"); // Assert.assertTrue(exception[0]); } }
5,356
39.278195
111
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/UdpTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.Channel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.DatagramPacket; import io.netty.channel.socket.nio.NioDatagramChannel; import org.apache.commons.lang3.RandomStringUtils; import org.ethereum.crypto.ECKey; import org.ethereum.net.rlpx.FindNodeMessage; import org.ethereum.net.rlpx.Message; import org.ethereum.net.rlpx.discover.DiscoveryEvent; import org.ethereum.net.rlpx.discover.PacketDecoder; import org.junit.Ignore; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import static org.ethereum.util.ByteUtil.longToBytesNoLeadZeroes; /** * Not for regular run, but just for testing UDP client/server communication * * For running server with gradle: * - adjust constants * - remove @Ignore from server() method * - > ./gradlew -Dtest.single=UdpTest test * * Created by Anton Nashatyrev on 28.12.2016. */ public class UdpTest { private static final String clientAddr = bindIp(); private static final int clientPort = 8888; private static final String serverAddr = bindIp(); private static final int serverPort = 30321; private static final String privKeyStr = "abb51256c1324a1350598653f46aa3ad693ac3cf5d05f36eba3f495a1f51590f"; private static final ECKey privKey = ECKey.fromPrivate(Hex.decode(privKeyStr)); private static final int MAX_LENGTH = 4096; private final SimpleNodeManager nodeManager = new SimpleNodeManager(); private class SimpleMessageHandler extends SimpleChannelInboundHandler<DiscoveryEvent> implements Consumer<DiscoveryEvent> { Channel channel; SimpleNodeManager nodeManager; public SimpleMessageHandler(Channel channel, SimpleNodeManager nodeManager) { this.channel = channel; this.nodeManager = nodeManager; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress(); System.out.printf("Channel initialized on %s:%s%n", localAddress.getHostString(), localAddress.getPort()); } @Override protected void channelRead0(ChannelHandlerContext ctx, DiscoveryEvent msg) throws Exception { InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress(); System.out.printf("Message received on %s:%s%n", localAddress.getHostString(), localAddress.getPort()); nodeManager.handleInbound(msg); } @Override public void accept(DiscoveryEvent discoveryEvent) { InetSocketAddress address = discoveryEvent.getAddress(); sendPacket(discoveryEvent.getMessage().getPacket(), address); } private void sendPacket(byte[] payload, InetSocketAddress address) { DatagramPacket packet = new DatagramPacket(Unpooled.copiedBuffer(payload), address); System.out.println("Sending message from " + clientAddr + ":" + clientPort + " to " + address.getHostString() + ":" + address.getPort()); channel.writeAndFlush(packet); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); } } private class SimpleNodeManager { SimpleMessageHandler messageSender; public void setMessageSender(SimpleMessageHandler messageSender) { this.messageSender = messageSender; } public SimpleMessageHandler getMessageSender() { return messageSender; } public void handleInbound(DiscoveryEvent discoveryEvent) { Message m = discoveryEvent.getMessage(); if (!(m instanceof FindNodeMessage)) { return; } String msg = new String(((FindNodeMessage) m).getTarget()); System.out.printf("Inbound message \"%s\" from %s:%s%n", msg, discoveryEvent.getAddress().getHostString(), discoveryEvent.getAddress().getPort()); if (msg.endsWith("+1")) { messageSender.channel.close(); } else { FindNodeMessage newMsg = FindNodeMessage.create((msg + "+1").getBytes(), privKey); messageSender.sendPacket(newMsg.getPacket(), discoveryEvent.getAddress()); } } } public Channel create(String bindAddr, int port) throws InterruptedException { NioEventLoopGroup group = new NioEventLoopGroup(1); Bootstrap b = new Bootstrap(); b.group(group) .channel(NioDatagramChannel.class) .handler(new ChannelInitializer<NioDatagramChannel>() { @Override public void initChannel(NioDatagramChannel ch) throws Exception { ch.pipeline().addLast(new PacketDecoder()); SimpleMessageHandler messageHandler = new SimpleMessageHandler(ch, nodeManager); nodeManager.setMessageSender(messageHandler); ch.pipeline().addLast(messageHandler); } }); return b.bind(bindAddr, port).sync().channel(); } public void startServer() throws InterruptedException { create(serverAddr, serverPort).closeFuture().sync(); } public void startClient() throws InterruptedException { String defaultMessage = RandomStringUtils.randomAlphanumeric(MAX_LENGTH); for (int i = defaultMessage.length() - 1; i >= 0 ; i--) { int sendAttempts = 0; boolean ok = false; while (sendAttempts < 3) { Channel channel = create(clientAddr, clientPort); String sendMessage = defaultMessage.substring(i, defaultMessage.length()); FindNodeMessage msg = FindNodeMessage.create(sendMessage.getBytes(), privKey); System.out.printf("Sending message with string payload of size %s, packet size %s, attempt %s%n", sendMessage.length(), msg.getPacket().length, sendAttempts + 1); nodeManager.getMessageSender().sendPacket(msg.getPacket(), new InetSocketAddress(serverAddr, serverPort)); ok = channel.closeFuture().await(1, TimeUnit.SECONDS); if (ok) break; sendAttempts++; channel.close().sync(); } if (!ok) { System.out.println("ERROR: Timeout waiting for response after all attempts"); assert false; } else { System.out.println("OK"); } } } @Ignore @Test public void server() throws Exception { startServer(); } @Ignore @Test public void client() throws Exception { startClient(); } public static String bindIp() { String bindIp; try (Socket s = new Socket("www.google.com", 80)) { bindIp = s.getLocalAddress().getHostAddress(); System.out.printf("UDP local bound to: %s%n", bindIp); } catch (IOException e) { System.out.printf("Can't get bind IP. Fall back to 0.0.0.0: " + e); bindIp = "0.0.0.0"; } return bindIp; } }
8,457
38.339535
178
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/TwoPeerTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import com.typesafe.config.ConfigFactory; import org.ethereum.config.NoAutoscan; import org.ethereum.config.SystemProperties; import org.ethereum.core.*; import org.ethereum.crypto.ECKey; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.mine.Ethash; import org.ethereum.net.eth.handler.Eth62; import org.ethereum.net.eth.message.*; import org.ethereum.net.server.Channel; import org.ethereum.util.RLP; import org.junit.Ignore; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static java.lang.Math.max; import static java.lang.Math.min; import static org.ethereum.crypto.HashUtil.sha3; /** * Created by Anton Nashatyrev on 13.10.2015. */ @Ignore public class TwoPeerTest { @Configuration @NoAutoscan public static class SysPropConfig1 { static Eth62 testHandler = null; @Bean @Scope("prototype") public Eth62 eth62() { return testHandler; // return new Eth62(); } static SystemProperties props = new SystemProperties(); @Bean public SystemProperties systemProperties() { return props; } } @Configuration @NoAutoscan public static class SysPropConfig2 { static SystemProperties props= new SystemProperties(); @Bean public SystemProperties systemProperties() { return props; } } public Block createNextBlock(Block parent, String stateRoot, String extraData) { Block b = new Block(parent.getHash(), sha3(RLP.encodeList()), parent.getCoinbase(), parent.getLogBloom(), parent.getDifficulty(), parent.getNumber() + 1, parent.getGasLimit(), parent.getGasUsed(), System.currentTimeMillis() / 1000, new byte[0], new byte[0], new byte[0], parent.getReceiptsRoot(), parent.getTxTrieRoot(), Hex.decode(stateRoot), // Hex.decode("7c22bebbe3e6cf5af810bef35ad7a7b8172e0a247eaeb44f63fffbce87285a7a"), Collections.<Transaction>emptyList(), Collections.<BlockHeader>emptyList()); // b.getHeader().setDifficulty(b.getHeader().calcDifficulty(bestBlock.getHeader()).toByteArray()); if (extraData != null) { b.getHeader().setExtraData(extraData.getBytes()); } return b; } public Block addNextBlock(BlockchainImpl blockchain1, Block parent, String extraData) { Block b = createNextBlock(parent, "00", extraData); System.out.println("Adding block."); // blockchain1.add(b, new Miner() { // @Override // public long mine(BlockHeader header) { // return Ethash.getForBlock(header.getNumber()).mineLight(header); // } // // @Override // public boolean validate(BlockHeader header) { // return true; // } // }); return b; } @Test public void testTest() throws FileNotFoundException, InterruptedException { SysPropConfig1.props.overrideParams( "peer.listen.port", "30334", "peer.privateKey", "3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c", // nodeId: 3973cb86d7bef9c96e5d589601d788370f9e24670dcba0480c0b3b1b0647d13d0f0fffed115dd2d4b5ca1929287839dcd4e77bdc724302b44ae48622a8766ee6 "genesis", "genesis-light.json", "database.dir", "testDB-1"); SysPropConfig2.props.overrideParams(ConfigFactory.parseString( "peer.listen.port = 30335 \n" + "peer.privateKey = 6ef8da380c27cea8fdf7448340ea99e8e2268fc2950d79ed47cbf6f85dc977ec \n" + "peer.active = [{ url = \"enode://3973cb86d7bef9c96e5d589601d788370f9e24670dcba0480c0b3b1b0647d13d0f0fffed115dd2d4b5ca1929287839dcd4e77bdc724302b44ae48622a8766ee6@localhost:30334\" }] \n" + "sync.enabled = true \n" + "genesis = genesis-light.json \n" + "database.dir = testDB-2 \n")); final List<Block> alternativeFork = new ArrayList<>(); SysPropConfig1.testHandler = new Eth62() { @Override protected void processGetBlockHeaders(GetBlockHeadersMessage msg) { if (msg.getBlockHash() != null) { System.out.println("=== (1)"); for (int i = 0; i < alternativeFork.size(); i++) { if (Arrays.equals(msg.getBlockHash(), alternativeFork.get(i).getHash())) { System.out.println("=== (2)"); int endIdx = max(0, i - msg.getSkipBlocks()); int startIdx = max(0, i - msg.getMaxHeaders()); if (!msg.isReverse()) { startIdx = min(alternativeFork.size() - 1, i + msg.getSkipBlocks()); endIdx = min(alternativeFork.size() - 1, i + msg.getMaxHeaders()); } List<BlockHeader> headers = new ArrayList<>(); for (int j = startIdx; j <= endIdx; j++) { headers.add(alternativeFork.get(j).getHeader()); } if (msg.isReverse()) { Collections.reverse(headers); } sendMessage(new BlockHeadersMessage(headers)); return; } } } super.processGetBlockHeaders(msg); } @Override protected void processGetBlockBodies(GetBlockBodiesMessage msg) { List<byte[]> bodies = new ArrayList<>(msg.getBlockHashes().size()); for (byte[] hash : msg.getBlockHashes()) { Block block = null; for (Block b : alternativeFork) { if (Arrays.equals(b.getHash(), hash)) { block = b; break; } } if (block == null) { block = blockchain.getBlockByHash(hash); } bodies.add(block.getEncodedBody()); } sendMessage(new BlockBodiesMessage(bodies)); } }; Ethereum ethereum1 = EthereumFactory.createEthereum(SysPropConfig1.props, SysPropConfig1.class); BlockchainImpl blockchain = (BlockchainImpl) ethereum1.getBlockchain(); Block bGen = blockchain.getBestBlock(); Block b1 = addNextBlock(blockchain, bGen, "chain A"); Block b2 = addNextBlock(blockchain, b1, null); Block b3 = addNextBlock(blockchain, b2, null); Block b4 = addNextBlock(blockchain, b3, null); List<BlockHeader> listOfHeadersStartFrom = blockchain.getListOfHeadersStartFrom(new BlockIdentifier(null, 3), 0, 100, true); // Block b1b = addNextBlock(blockchain, bGen, "chain B"); Block b1b = createNextBlock(bGen, "7c22bebbe3e6cf5af810bef35ad7a7b8172e0a247eaeb44f63fffbce87285a7a", "chain B"); Ethash.getForBlock(SystemProperties.getDefault(), b1b.getNumber()).mineLight(b1b); Block b2b = createNextBlock(b1b, Hex.toHexString(b2.getStateRoot()), "chain B"); Ethash.getForBlock(SystemProperties.getDefault(), b2b.getNumber()).mineLight(b2b); alternativeFork.add(bGen); alternativeFork.add(b1b); alternativeFork.add(b2b); // byte[] root = ((RepositoryImpl) ethereum.getRepository()).getRoot(); // ((RepositoryImpl) ethereum.getRepository()).syncToRoot(root); // byte[] root1 = ((RepositoryImpl) ethereum.getRepository()).getRoot(); // Block b2b = addNextBlock(blockchain, b1, "chain B"); System.out.println("Blocks added"); Ethereum ethereum2 = EthereumFactory.createEthereum(SysPropConfig2.props, SysPropConfig2.class); final CountDownLatch semaphore = new CountDownLatch(1); final Channel[] channel1 = new Channel[1]; ethereum1.addListener(new EthereumListenerAdapter() { @Override public void onEthStatusUpdated(Channel channel, StatusMessage statusMessage) { channel1[0] = channel; System.out.println("==== Got the Channel: " + channel); } }); ethereum2.addListener(new EthereumListenerAdapter() { @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { if (block.getNumber() == 4) { semaphore.countDown(); } } }); System.out.println("======= Waiting for block #4"); semaphore.await(60, TimeUnit.SECONDS); if(semaphore.getCount() > 0) { throw new RuntimeException("4 blocks were not imported."); } System.out.println("======= Sending forked block without parent..."); // ((EthHandler) channel1[0].getEthHandler()).sendNewBlock(b2b); // Block b = b4; // for (int i = 0; i < 10; i++) { // Thread.sleep(3000); // System.out.println("===== Adding next block..."); // b = addNextBlock(blockchain, b, null); // } Thread.sleep(10000000); ethereum1.close(); ethereum2.close(); System.out.println("Passed."); } public static void main(String[] args) throws Exception { ECKey k = ECKey.fromPrivate(Hex.decode("6ef8da380c27cea8fdf7448340ea99e8e2268fc2950d79ed47cbf6f85dc977ec")); System.out.println(Hex.toHexString(k.getPrivKeyBytes())); System.out.println(Hex.toHexString(k.getAddress())); System.out.println(Hex.toHexString(k.getNodeId())); } }
11,278
40.164234
213
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/DisconnectMessageTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import org.ethereum.net.message.ReasonCode; import org.ethereum.net.p2p.DisconnectMessage; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import static org.junit.Assert.*; public class DisconnectMessageTest { private static final Logger logger = LoggerFactory.getLogger("test"); /* DISCONNECT_MESSAGE */ @Test /* DisconnectMessage 1 - Requested */ public void test_1() { byte[] payload = Hex.decode("C100"); DisconnectMessage disconnectMessage = new DisconnectMessage(payload); logger.trace("{}" + disconnectMessage); assertEquals(disconnectMessage.getReason(), ReasonCode.REQUESTED); } @Test /* DisconnectMessage 2 - TCP Error */ public void test_2() { byte[] payload = Hex.decode("C101"); DisconnectMessage disconnectMessage = new DisconnectMessage(payload); logger.trace("{}" + disconnectMessage); assertEquals(disconnectMessage.getReason(), ReasonCode.TCP_ERROR); } @Test /* DisconnectMessage 2 - from constructor */ public void test_3() { DisconnectMessage disconnectMessage = new DisconnectMessage(ReasonCode.NULL_IDENTITY); logger.trace("{}" + disconnectMessage); String expected = "c107"; assertEquals(expected, Hex.toHexString(disconnectMessage.getEncoded())); assertEquals(ReasonCode.NULL_IDENTITY, disconnectMessage.getReason()); } @Test //handling boundary-high public void test_4() { byte[] payload = Hex.decode("C180"); DisconnectMessage disconnectMessage = new DisconnectMessage(payload); logger.trace("{}" + disconnectMessage); assertEquals(disconnectMessage.getReason(), ReasonCode.UNKNOWN); //high numbers are zeroed } @Test //handling boundary-low minus 1 (error) public void test_6() { String disconnectMessageRaw = "C19999"; byte[] payload = Hex.decode(disconnectMessageRaw); try { DisconnectMessage disconnectMessage = new DisconnectMessage(payload); disconnectMessage.toString(); //throws exception assertTrue("Valid raw encoding for disconnectMessage", false); } catch (RuntimeException e) { assertTrue("Invalid raw encoding for disconnectMessage", true); } } @Test //handling boundary-high plus 1 (error) public void test_7() { String disconnectMessageRaw = "C28081"; byte[] payload = Hex.decode(disconnectMessageRaw); try { DisconnectMessage disconnectMessage = new DisconnectMessage(payload); disconnectMessage.toString(); //throws exception assertTrue("Valid raw encoding for disconnectMessage", false); } catch (RuntimeException e) { assertTrue("Invalid raw encoding for disconnectMessage", true); } } }
3,746
32.455357
98
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/NewBlockHashesMessageTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import org.ethereum.core.BlockIdentifier; import org.ethereum.net.eth.message.EthMessageCodes; import org.ethereum.net.eth.message.NewBlockHashesMessage; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.spongycastle.util.encoders.Hex.decode; import static org.spongycastle.util.encoders.Hex.toHexString; /** * @author Mikhail Kalinin * @since 20.08.2015 */ public class NewBlockHashesMessageTest { @Test /* NewBlockHashesMessage 1 from new */ public void test_1() { List<BlockIdentifier> identifiers = Arrays.asList( new BlockIdentifier(decode("4ee6424d776b3f59affc20bc2de59e67f36e22cc07897ff8df152242c921716b"), 1), new BlockIdentifier(decode("7d2fe4df0dbbc9011da2b3bf177f0c6b7e71a11c509035c5d751efa5cf9b4817"), 2) ); NewBlockHashesMessage newBlockHashesMessage = new NewBlockHashesMessage(identifiers); System.out.println(newBlockHashesMessage); String expected = "f846e2a04ee6424d776b3f59affc20bc2de59e67f36e22cc07897ff8df152242c921716b01e2a07d2fe4df0dbbc9011da2b3bf177f0c6b7e71a11c509035c5d751efa5cf9b481702"; assertEquals(expected, toHexString(newBlockHashesMessage.getEncoded())); assertEquals(EthMessageCodes.NEW_BLOCK_HASHES, newBlockHashesMessage.getCommand()); assertEquals(2, newBlockHashesMessage.getBlockIdentifiers().size()); assertEquals(null, newBlockHashesMessage.getAnswerMessage()); } }
2,336
39.293103
173
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/StatusMessageTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net; import org.ethereum.net.eth.message.StatusMessage; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import static org.junit.Assert.assertEquals; public class StatusMessageTest { /* STATUS_MESSAGE */ private static final Logger logger = LoggerFactory.getLogger("test"); @Test // Eth 60 public void test1() { byte[] payload = Hex.decode("f84927808425c60144a0832056d3c93ff2739ace7199952e5365aa29f18805be05634c4db125c5340216a0955f36d073ccb026b78ab3424c15cf966a7563aa270413859f78702b9e8e22cb"); StatusMessage statusMessage = new StatusMessage(payload); logger.info(statusMessage.toString()); assertEquals(39, statusMessage.getProtocolVersion()); assertEquals("25c60144", Hex.toHexString(statusMessage.getTotalDifficulty())); assertEquals("832056d3c93ff2739ace7199952e5365aa29f18805be05634c4db125c5340216", Hex.toHexString(statusMessage.getBestHash())); } }
1,854
34.673077
190
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/eth/MessagesTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth; import org.ethereum.net.eth.message.NodeDataMessage; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import static org.junit.Assert.assertArrayEquals; /** * Testing different kind of net messages objects, * for example, to clarify encode/parse reversal match */ public class MessagesTest { @Test public void testNodeDataMessage() { byte[] data = Hex.decode("f93228b90214f90211a07d303f0cb6b53aa51e03134b72f7447a938e3d69d2a1e2951e88af415cfc54bfa0aa37b7de2b35faba0c2c1d328a39e6976631bd91db766e9532b62232c5fea3e9a0d6a6930b51581cc8a6aaab9ba9baa8d297384c9be589acc4a38c1965b2ff460ca05a7b32211d014144e075a338074b1613013818a489ba644d407c387260efac7da03280b01c75a2b8a4fd820bf2671d999174083213500e9bef74f309c378803216a0ac99b656d4ecfe0a7478a7e196784ca6336fec066b9f1960e718d596c72bbf5da03a2c00bb9601c0875e3dc575126679a73d495e17f295be86c1edfbb94441b123a06045ce199c13095165961db9b5e25965614b4c22dfc932d48e545096758b6393a0d60d70c8eec63dc4b20c5615f48e26ebad476f544cd649a66274048fb83ba4c0a096d9dd5c0a7b4a1b009d53d5df94fc4bb165f4b8bb0998942ce0cba9439e170da0a8c743996990a573ae5a8792e08e1b96c44cc0e039374114473b891a25fdded2a0af554afd269d8e1362d792aab0d74c774e7d708a4c94f230aed495389b6a9b68a02d2569b97a69cd4c48db74410e8d7fcca8b103f96fff417de645d3a46b5d5055a07cf48a75c0ea55d3e1ce5d4e43e2c65eb963f81f8c4a79e668156a87b6a15199a01bccb2cb8464b166543b2ff7a9d6f23ff3c397b342e735a631e93badeaeb6f1fa0e809a6ddd5ba566a0202ff53adcd92bc36562aa7f25fee25bffda90c4043e69980b90214f90211a07f228060d35e8517981a6bf48de0cd70adc218183fc1040a6136f8a244000c19a0f4c1cb083074fa68d85ab2507ab46844c2c3d5b4a1cb461190a5472935030570a0124af13bc8c6690d169faaa12b4f77edf34c79ea40955543990ca2fedd3641d8a046eed198f80c1b57bd425e42311016aa49707e5ab26f85a72ee21b2731f51d9fa0f61f057121208af1b642157132296d961002c52c74ecfed11a2a1faab514bae3a0a0b4bf520598f82ea43ee480532adca5c3d36607d56e0ac2428a7918de3c7da8a03fbdc59c5b4c46a0147aff6616ec0f573873523a14b75d7e0beff5015a850742a03d6a13d4627b24561f5e34c9716f7725450aa75214231cd41a42a8ce6017d8dca0e8f7fd0acaf7a0fda7f4ec57213e48f284b9865fd34c39acd73c57d7bd363ea2a013b78164e09324c237aae690974b2bb9410a395263e1b3d8cfbd510df2136860a0b6f0d6bb4218ca4e2499d813895af21fe80afabde38fdab1b9930f5f38fd20e6a0eed4626964447c8e9ce41441fccee2dc9e7154ce8e24dda9bfa0e40292907e9da048ead94ed97b7b0ba8b5673520124046c7bfa9086c7a1a1632e201f35976b25da07a0f8d3c8c2587f2e2cff32e5a21eff284acf6e84c6af592f7db63c2555547eda08dc68f59b02dfc8f5405951948906615b3df77b192e96c945fe3cdfe235b5b1ba0d0c2a883f786349861f76fe5f8a573ffc6b039f8effe1db0479ff57d00a6ff1080b90214f90211a09ffb85b047fd0d70603792e1871291ba8959ad9ba38f6f3f996d701cae14293aa08cd707c87b413b32f7a4133c40ddca9dd0c94fc20d0a4957fa76cea45a04512fa01900e10a8a120f78a52471e6e60a3a882328a051dae508e16d9315a552c1ae20a03c56a9cb58c180ed7320351f21eca3aa88603dea4b32ffa08f703ad694791475a03632993a16501e50253ae47734305addeea31b05640f780de8eb525866e7f2c2a047d7e79e61197742aab166440d1060a8bae928f9c4a4d72cecbeed2dfdc1d5e9a0f7196328f97e5835f9a80808d5dd7d43a9b702dd12f8815700ba89645485856ca0c80c1df1a8e18bcffca5774456774372be138e0be79f9b6d5c174ceb940989b3a0280d2a31d1407cb73ff590eeb9c9c20e60d79a21a99d50a6fbf2d07dbe25112aa0abdf6514623195ee5c17af43e18b0819931567a75b9e76325c86934f4a8cb39ca0e2b5e99c4a7473abfc21e1c00eece6936fb7f39eea94ee0eeae381553f33007ba058b39222b273ceba9fd317e2db88e1773324e8689a56aa0d22dbf0f20daeeabca02daafb2b82cc58f04972783123b291466034b90b0cfcbfa4d46958f8289dcf44a0e035cc41ea4095525ac75a0d96282b9e9b66dd858cebd34bc7f8f456fbd41159a0778aeabebd19c15afeaadf00a16c729079aad3404ab474022b96fdad4d0aedfaa08da34aece7cdf813b1559d4e958ed6add676bf251132711d8c0b46484a02d1bf80b90214f90211a0b29265f3668c7c4195a9b2e0c1a97fda3a9a920ee99e67dced31c7295615319ba0aaec178596b7cd8ae5f8708362e62c7fed9cb34843ae83a238959ec7d6800200a07472b9efe8ac40dc95f09f92d4e74065cb344874824d882c0a10126315784364a05c00c65daceb0bd26382845eff953099022d5a2377259530145753a14b87be16a0bdb04f816249b663ff1cea12123fe2f2612348d5d33816a0aea016e473c5132da04942bf1cf9a79a18a4ba0b2228539d6e5fa6c213c66bb028e567a68e311d4ddda0e98b5fbab8fe6b9123588c7ad46f958fb79527c1c695a5060eaee14ead1c2a2ea0ba7a2303df43f2fe558ce599e7e470c3d1b447252d019010532453599db2b10ba0951867684672973e0901bfde8baab90c093293f807cfb68722ab08eebce921dfa0d520633a15034d22f12b2d04d9b5c6cc1fffbf7d3b52170e092a511a18fca999a0ca85ec566b4eb8aee3c7496d742706b85121e8f1e3d950707faf46762f868e40a06d091294b7e94f52fb54ba7ca7f182e24623033526b1ab9502fc885263bf4672a0d7bc486600fc5cb5e1376807cd7e66725e7761e028386e7463748b9e2aa2ce9ba0b51a3197d51bcad183a1667a437a5666cab90ced7870cbaad65870452f041a1ba0359fa26fc937a5a65ff6d6fba23a9213d86f8c9b5481991fc4b8bf714fd55048a0b674ef300d5955c149e2de3aba1fa228c0d148674523bddd586cd6b7360f4fd780b90214f90211a0790eaabb9dee7eb1aaf2af28f594eeb4a7f467f329b4fa01d5b617d15f40a5bba067eec836cb9d4a4793137bbe8ba2c8b9db91d46d2e3b4bffb30d290a58ea6ea3a0172f0b889aefdc2495f2e00b5eedbe948ec4776df299bc2b0b058bf6a72bf197a03533a9d57193053bdfaa3c097ca0b49e5cca8501e9d37c229762937ed27f6d06a0f9f2eb5a0538a2ea5552e8858d3798309c8c3c13b30fdb02a1d5d65b5d432caaa05b99ff9a8a0e15b948496039dc92bbf5aa67c56f9ce6c8ff19963179d8481d44a0d1bb632d1bd3879f4a00a1cf8c9e904e58e637f087bf8e5d4813d84ff089bc7aa09ca07525f6184961f5b7e195b78f580c5428862103c7fd6aac36db0a3108c075a09e2bdf35a3a11427810c048ce43c8a8699aed99e4b5f1e809251d68a91b4a45ca0a8c5baed3016ff5d11ce39f4c81a223f499cf1f238ea225d52dc8f5bad705ea9a0598d38a92711979c69fba8633724bb50c3fa05b6c12897732d5a483696b3967ea064a5601e5fdc1bdecbdf258d5f5d1b71d54e89f48fe4228240eec07e831d42cda0f5245301cc91d72b1a659078e59b0650722a7de7410f96a682c9e331ad524040a0d0f7504488cd19c08fefc6290f66cdc7fe50968b54804d1a6aabfb09907865eba07cc361cd333675088d372d2a1b62ef7c4f3e5c0df75b9348fd39e259a4c7cba7a061dd5cb5648074c5d0f15370f1d96f5499d458212419a966558f1f2426f87c7180b90214f90211a08d92bcd188b0f7450933496d343e1f0f71796d0db0e833668dff9261b9933b50a0a46386c7de7332708c1d74efe1c394837e12f7dea7954474028fc816aa754077a003888289efbb5202d5be23810bf14f35573f91c71254d0125dfd46320dc69709a0e6a2e4fb43a1b3a4ac841daeb2c7284a8618738be0b2d368b221b951b59ee629a0ae9b2db6a4177c7a9df77d6d1d606e6825a53f811bc1bd94772c5e130c80fa41a0ee368ffc3d5f6746d78f8da2639d12d2aceaa37b4546578ea7d6523d41b0af2ca01eee9a54c7a9e31631926306c9dcd1f3f3464960860facefc8413ae1fe0beb0ea0c3981ef7fbab1ac978aef52d28ef8026da8c3d97c339a89058fabdbfb2f0ec0aa076e5b49d3c2d578732dc429abcb3b8a0e282d541c01f465aca752574851c6869a07d68b3b2df3e1500ee4b2530a2b936e6fed9be2d5bcd77e4ecec52786bdf6a72a052fafe97bd9025c2e08011b3036b771c98577d1e2a7245f3c7aa93c183239a20a0f78075a14bca20652a33c9c8e90932852558fa47991632c68a3f2d93f5b25823a0fb2a4581ad9fa79c68ea5eb73b296143894478091790ef8bf5f26e4964fc81dea0813d838d9f00d69c3167d1679659b17e4f44806842111fcabe3cf2441c8f4981a0070f83d8cb645c7d055a54eaab2f536c02fd93384d79d050bc0779ad3561e01fa0825ba72c1d04a0e03e9201879f6f7e2d11be24bfe93f4152ca57e1e07b93716480b90214f90211a0daf446f6aefe7a4c85f7a61414fdb247fa23ba640c0321abcae97eae1420948aa059c7ba791300a633da935c1070e6719c2979e8540c8ee56403ca68460fb088b4a0d286d661656c927126dcdd49c7c4e7da37e3d9e3bd963813e171f0b673257e0da0643f7412235550772f49fb8aa58330dccff9553b4a501521e7feddb71e5e26c8a092fbcba3021bc2c0f1360179df91e3f52fd5e507abcd5426b6c2dd637ad92843a060a1a4294b260613b5fbdd8a8f6e3cddd7f061feca667d8c9f62931d813bca44a0ba9c1e6d2a4c02a90e5bccaa67a59db3916f5b8dc4ab099921546d7e712003a2a0483d07371d08ba671c357b38a09f920dce09fa7638e5d5200f5df05e8322d9eba000443f99d2394329e38a7ef407629784bbcc1e30341d13517b8e5035486a4740a0c12b6206a18a4bae50aed7570ed41db9d1c8acd100fe2e83f781d2d5ebab54bda05c177f138645abc22a6caaec5f81a5ab8501bfce3b35ce0bbb45d2ea9e476da9a00577616999a95b9cfd950b47b6f81dd1abc48066d063cdd8408b019df7bc6a6ca0c580d7b33cf8612a7d3ec0780b93bd6b6792d69adc5f615dc1997f954a479bfda02a6f0b50ee406091c5b2f4812d7fe50c010d72696e7a43644a27cc8fab8826cfa046014d6e17f59c2fec43538ede5c1d8c9437556c987c922488240f5aa321b5f9a07d722390054c0b15b4deb8399907bf2bcbe20837de0c4ff88cf8774afb78627f80b90214f90211a06cf39d020b1f1aad34330f8a4af94881c6f76b5f562eac95d555c54a4444659ea043a043317a9925440933093bcc239f4bbd555ec7d8a5d5f4909f5928f9f0bcf3a099c5edc3f8481360a917b66603d510eece53f50b26f581487ea511f2377fa7a0a058cb0d9208ad696ed5c1a48407b2fe53d93499932a15bec72452115b58b10f31a0dbaa5d44ed8351dac170d77a704d5cdf5f82aad38c37f82cd50ddec97408b0e8a00c7ea7dd5e15a62e5899d6e8771602affad1cf06caeb61df2a07f2ac63b6dfe6a0eedc9934dbbbd785ae9bc86fca46fef075a5aeed70a1397e3fd819053c04c92aa046302203393c116d5e24b09347a3f7524ad3d5b608334180d5f9903bfe5d9750a098e523ececb1ab617dd2981bbcceac4d4bc2e3df2427f86e5b7b3b8b0ad0c214a01a64e73d23772312515a58281703b3e2031445d26a61e98d20d7bb3ea471c57aa0e7262b834c14f9a10f0fe4d8a0acdee29cf3fda9a21d2395fba8e32984112847a0683aa9c85aff5ca22ffbf95302b675e53a55ffc25433a3492c05977dbcbadb8ea0c09f64a37c8164e9c44485f0a11fb2849c21ea5c7d8ce9c49d1eef38e5fb2ebca084befff1e422326ec61749e2d0a49335adf437b73cb17eccd8f6fd2a4c6a3e2aa0c0e95224af20aa75a4b27097745d16cafa93212787eeeb80359c00f80b1cc4cfa0bf655947225c8206ce32f61213ad6a34d21f50ddd269dc054e9886a1f3489e6580b90214f90211a01535995cf60848a1bfbe5c1bf129b67acea44f2dfa59f29d46d845aa92b0168da0d0b5e1bb1518e52cb8ec76345732c892031ea839ade813fbf0cc24dc77bddfdca070c6c45a8fc589483449cc0209933aec60eff26b043fdf658b37ec451f9cdd4da0bee75da3ee07b013b87bc7b6f61bf4146f4a8bbaf8feb7001f331b575e746e96a0967e3588baca3c782e96e5d964f14feacb082e5c143505d1e478cd63da2761c1a0b0687dd7f95f53466f070282f6c55f8250c9273ec3b5473e1ae83a4c1db7b200a0fde2a38a83aaad2aceddac17aeef1b57bb3a722aadba64ad14213b077eae6f33a06bafb757b6e4c57f25e8619028da69218ae173f12f4a3f77c362ff51b0844e67a0e927ecac726657dd33f1fad32d0994eab19c337a5d9ee966efddba6a4fb08ecca0a2e2e825ac35f9f5679dd0792493bee77116fd3437609c7a1a9e5e414e2143b6a03f90cee4f455a05dcd9215adc85f8ff8a50933fb953f8a84d5d1208c5161131da0adb4b45686d5b0e6586f3b36201feeb052f6b4fd989a4edb288c4b037f305d92a0706d04c66a9a65eeb37ecf32e79c17a30774a072c08a45e2b3d332130cb83818a03f329a00a746f6b6cb8a16c8da6c90860ab7b9815a838972f6ffd6c470503ae3a0886d7fd9d9b9edcb715819d442038970761d1981e884490dbc9b54bfb5e2d2e8a0f9c4f005de7df9bad735c1aff2d52bdf66f24b26c2fe7be6e9d6803ebf0d6a2d80b90214f90211a0bcce77aa2e1cc56548ea5f26ad90ab495453a770ca7961426ad18a2141bf80dda0fb5fd9fd456f31de21a0cd1c7f94f4781717a6008b3cff19f2e9967c23eb9350a0590ac6baa1a7a57c53948bf52f6ff6e8bbed700deeb402d51b0971b20d56e57ca0b77f947ddb37faf6274793e3a256abfb3a3a8ffed1ee0c8727d8723ed3e02df2a05419d8a089850f7ebaa57244806992888e13d3231f36796f2617638c9478bb03a0b67b3c29989884a30101fde67c1e4982cf6a354ebc594709fb1113e03c923ad5a00c2f238746335f03c7dfcc4ad95db75dee1a3a3f06a0579e898f3624a6fc8e65a0b92b7336a1b13e885893b1013472c22acdcb034a73dfadf40a72493b448a7c7ca06c1d5e1e4a442834450073e7abf9a7f5dfa68102c08ad4865d703455339758d4a0e9b3d0e64e74f2c6d5811a0f4d5bc476e0c0d648d97fdaf1372baf999b2a9982a0d128a21efc00fb47a57d0295f3d4155fa44e22a4e92758b604d160ee9f93002ca0c3ea80e9fbbf40d76374b63dada5c2e027cf6c3c5c06b420593531251122fd7ca0a2d72d22872ab9af578c10e0b7cb4c6a2cc993ff7ccfb513674845a35175264aa0b50a3c51fd1f74a88835b992263970e8b8ac78dad10058ee976b2097c5333762a091d4f826a8c6d5d4810961c5b130a8e6130772c8e4295c564b32a940ca031428a056e70dd5341cf0ffa4118ead82639bca43ce6742389037852a100d99b09c496580b90214f90211a0c53085531fc32a4355590c51d1da2e06e4485d7fac8370f081b87b263a7f1dffa05cd64c7fc178739fb035d272754b4aa02dd4a4c5fb139b16ed456274759ff281a07fd325669da905f482be278ff3c4c88eb5e4ca9a166af98c2eab5e170e6c643ea080539b3792634c7e75f202208a09b04d3c6de04960ccdab6b437bc033f14ea1ea06cba2d47d37c1db0cf84d8983a33a7e9d0cde76ae58994b1b64bbc29185bd0afa08e8c938b1da36a8d7141300d3096bea4232b3f3c40b385a504fa839f385c8b3ea0d81b80ef2e2bf0794a47371272e75a158c854e2f4412335f4d456269fbf65393a0c0d31104eac7a5e5b2e21808a0dc226aeb24bcab225de220be27e453f82e0ccca0622973d814235f18baf132812358e4299e5cae36d05d2f20a4990059f93c17a6a02a6adf03f3bb6b441e1eb946693885b608fe83cc1b482b6ad7d1dab4a1e22d24a0378af1df25ea36180ef1ecb2b2ae398927bf602ff89d5849b97476a1b5d4105ba061e19078218fd45e0119d2b9527b61d84a6053ea1c87880e3b1d9da4820ad534a08a87e96f453e07d2981fe127f88c256a1e476678081f1015e2dcfd05cbf5af33a0fe4a0564c6ad3714431c0ffc70f6fb6b7fdd55aab20b8dd36220923e123383d5a0b15088dd6b55d64e186e4f647c9effb39d24074544ae319f2010304ec6d0452ba0caaf4375ece81920948bee4a28d83c42ffc7b764cfa15a1bf9198b38fb7b603880b90214f90211a0519e50ecbb144b94f6e2bfe3b26995d7030ec4b4a0ed8055f31e82bd5e42ccb7a0f5596b86791bbc21f813554850592ece83efa2582d7867ed8faad7cf68cfcc30a09ab3b6894b705c178c2728150ea633adcb39d4192886d1335bcb37bbee3b9319a0dec19f675b23a32333d2079743db133931d7c4d819a6743725ad27e197219534a0cbcd41ab8a69e3c6f53fa18d964b7969b8ebce1fe5f01921bb31a8df83dcca52a0c1a7b1ceab13579e962e299fa0e95cb08999f9fb55086aea35c0ea3919450d33a068d04132744b2b807e6ee133efbf57683c21c79c3690d2905a326730bfcf1ef4a05db703056fa80dc3f41fc89613a18159a9caa876b2259a7f40b52f44399e976ca09d0ba10ae5ecbeafc046e8ce7b68909f28f7664f4e35a07df0831f1a080cf870a034ae6bf3f2ac51d1e2a3164c9f6d1aac8566a4eb2c4a6fbfd65d3c247cb7cca5a0bfd3708415951be5c2d36159d8120eae73eb83491f20c892d34d2b4dc3f7285ea0d1d5aaa464d7e086660cfab62da07e8aeb91ec8b9d179d3889868c90b64b6969a0bd86c170c5e05332ed2287a3360831313eadc9a44eec508625d4d4c184a300efa0bf5864ddbb3d5df12e583d91eb8fa6c783e7e71e2a3aa5bc84b36645c81a0224a0000aa6a49e07a2daa7b4cc1410cbf171bf813ecc29a01cbc6e1fab2c1adc07e1a07c3180e026262363bd6812e98ec3bdc4a2529c697fb9399de8b4ac280a3421ef80b90214f90211a0df620495988e0d6bf37924f0b27760d72dd13247e52be4f385c71b5ad68c8c01a04b38c4915e1767acab09925579c0f1c038a18528836bf88b65a69b13e7745adda0c4233e35236b19fefc984c55b8da459ab820f9a27f7d7ef0847d2d837881117ba0a8739cc31943c91611689fc617ddda7dbdf565aae47ef7b2f02e3a20c1150204a09fb34f35e2cfe0737d7e227f0b0e813768de03da537622416525af71de72126ca05bf43b0b6d6538309e2cc7f97c980a8ebcb23b28f480d9e82b013192ff30d964a01bc45340f94f9423cd1e60dfd4be9cf187f280362ea852aec4ffd5af7f64b043a04e283b36bdec0eb61884bde97e0a2b19bd03a10dce88fc92a7f52e30b86f4ebaa021a1c754b3c3bcbbb7ea0dfa40f9f07a731819075e503de9f62d661196d19432a00d7e799cfa76d57b335137e5e5f87a761ea4c8d929db8a452d5d5f61c309e415a0a22bf2ff3d3705f6246d79078d828b0d93367afde8e70ab8f342a5279d80b132a092fe9c18e7437494d6033f39c7af3177de8b75b328a87f18aee8518045802fe1a0fcacd6a66f09c520db855d7b66c45a379ac0f80418d322ad039efb7ae6c79419a0b30c28009c661cec7478e5cc0582e23ab50463ab094aabc2da09a9d6507c54e5a071dac0f503e43eae74fb8acc66d6026eec7d537563d5db62653d9f97be4fbfd1a0c4195b0ec9cc846b0c9ea0d8e934ca28047aa70e684f3021ad925ddde27fbd7380b90214f90211a0e62b34c602549e0d2537b869fcd80ba937ed4eab20fe630c3a008d030682467ca0107dbebbc041654b5485effdd7585356c50b821aa44aa443c8aaffc493887fc9a03cf4f05885a495d4d1ec70f46eea09b001b066dc6ce7dc88bad26b36e2474289a082b7abb3f626fa2c3f5f32fd7323f538bf691c1c5a549c43d3b6a818865cc1bca07d2f57d940be8c73332534cb773f2e3433bbf0f34063fa44b72da69ac389b2a3a0f9e1a36fe4b7dd7f2ac5d5ad7a38aeda38b998debae9d3d1ce9167c705875ec3a019f430d8293eca48d7c309cc62aa20c8e7220f4bb5efe0424403bbb30e56ef76a0789bddba918171f9d918618978c7df31456f7b34b9c5aa14cc33274184f349fba0eca70410cee4b7de856e8a704d72dabd2dc51e6bb866859ea549646ebf154687a04f5063c9ab039ac16450a8c0ec98d6aaca7ead5e46df5b799d72642aa45d71c3a08ad6412e3dcdef56c471ff7d96600cdacf8ca5321c4d3cd265a8d8e5981db153a05ffda09715d6e6276242fd5b501e9e038aaa48fbab8d6757eeace07f5ed97cc0a008a3d4612fabbb512ae0e553700d16f9d488c1eb86c95c8122f86d59038af5cca0285ded4f9195579adb4409304241a06bff40d91d1c0b0b923f6bade605d148cfa0b9bb0b147ccdb1a3517936b0791c8f6d9989c2db5f9fe5fbe9a1ccc5d1f96e76a06ef4685c31c0b9ea0157b0fd7f7f335a4f4771b5abd3dea3b12570962130a83080b90214f90211a063df6a0c5f3355b31f6ca985183bab8cfa99071795d4f546848c3d4381faa048a046989783fa4e37cd04f7a55a762b2f5ae010d9098887fc3d4e667d8a685a8424a0518d105caf3bc5fdbcaf1e70c195562c634dc224a31acda6159d8ae07bdf1eaaa0d38ba36b4609188f27d5b7d01a29421e36cfd114b50c6f500dd58ddd49273a13a072a97336bc4005c20d708bc40331a843f472ed2652006b4bab3515f797534467a044017b8207927cad145d4a13e863f074ac34f5e079e2331e5a7c73d1012b4b5ca0183aa0e3eb18193ebec3e6bb524bc2a9b6164e6385108525404b7425c309cefea01720723132fa880c138afd13bb56928b2c5c03dcbecfafd2a716c3ceae59bb03a0a988a8b774f01c51e77ec47fa79faf06e11c296e6196bfe8904eabac2e8b21a4a0f55e51f1972c350443066ae8b91d6dce430073c567b22b47c8ce2cbbe1b4d5d1a020a99db9a56f0cece01c235d3817637ea57985d8ad0a9f1bbec9ecc4d1cd55eca0b2b94ca3f92e8519ff64c8b0767d20f17cdd337fd3bb230f6739c6967915853ba0f1badb8cd5fceba2d445251b329daf9455091f66a571b698cceaed73672347e1a05b2bb7144350c35d5ff663d4ccd7a9f76d2e4816981a05e0d59c773836aebdc6a00b7074b75d12000d7602a7f4aaceee9d772c16126c1fbdf42ff981600daafb23a0a61171fa68eb450a4218969ad699883a084aee8aa7d3c46ccd95fc1ad2dbe0ce80b90214f90211a051c51aa0073f05e932df75af481d2cde83e86fcb16f267e27fdbb94dbdbea508a0532e9ef84fd5e0a784b761b7c8593021738e07860321896a8804465777b96d22a0e2ecc9660e412f9f72bb3dbe0f2df9d426fc1476b5b9f84e917ae07d5a8aed0da09d559c3e97e2508db1fda8df5f7b6d3f92ce209dbd743706a1b14fe0dc4b87dba097912a92bb6d97faad42453b71bfd900f3e9b120fb9cd597b47fcaaf5af771d3a089c73b620645de9c0b3435eda42a3c63cd035eb1f7aee6a22992326785bd02f4a0bc22e340a3e467989c1ae2d8d96daebbf612ff1b1269e5b761ebe9833f83828ba057d4130a933b961fca263500c7ce7df0fa0522fb07615f1b6eeb9627575521cfa0c3e67d0333dd2b6bc32f92e3a09a368e71517de41e168e833ac1b829010e45e1a06483dc6326f52c10c57aed477c53b83bcae2f37db7074100a53f4aeeed930996a0eda92a8682840b924990b289daa52d6987be148f0517fe340e622a75feabac0aa01fd9e5069e2ae89646a3e85e6fc63a14070992e9196029bce4ea6737b2ccb582a0b665930ce712933eec2bce24eff8593b07a2be23bb1fee56cb0c58b9385b7f0ea0fa661e4b169c16a778938b9d80dc1a3aaffec57441de5086ba44a78ed3e1a1c4a0affd8a2662dd8576ed2339e00195d6ca75c67a805f55436cecc7de9e149a7a4fa0cf97e8a84017aa4ec509db2afe7b926bbab83b1e63e43b4c3fd5a13d20c3c2a580b90214f90211a0a4823c1b2ace6e9b0951662ebfa2330a6e8403cd67a54a6e74d05bcff21bd9fba0e775f21d473c8354c8bb70e5ea2e4339d1383aa1c31ed574632f53019bb9c27ea066aa3df101bdac4f5f9eddbf4718e27c36cdf2eba147c5ba79ffbb249023ecdea02c8a4e078c9d4b955a5e2bdadaefb91652b170802f489e9d73ac3b7d5aef722ea0599458e68f8821dc4b4747efcb451e5bb63c39f86d5ae2dceccc3b642a1b2065a03cbee948f53025368d047076cd6ff2b2f0a218c0ccd10c637e4abe22121a2067a039e1dc89ead629b6460cd49aa05b7921557abf3e04d9990f239b84ccb0155b05a052702930120fe255e4b24923b8a3c865f4bbaad50d13712c6e8a64f1802b97b8a0374710d55d164e417221148ab6f34aa0e090b3d3b5e3080347dfbaf44abea053a0c83880d65345437ae11c5217df7fb9a3ee8b3054c94424b93afbb79bbd0d81bfa0561d415e31798ae6e447275dab3afb3edf37d9d5eee655b7cd622240d13dec72a00f6d2dc43a193ba4e7bd0885959a927a067cb393fe8cd74cf9540ae76142dfd2a0e8f4fcc6fd04ac7f159bf9d674fef9f4cf3ccf76ec5c2eac53a5c209fc5dc03da053e838c8e6770ad4133de92eb6dd7e2f08f0fc5cc60fe55c68a9bab7dca9528ba038c1c632ab1058083ceecdb00bc6d13a1e457afb166b411551555126914b1522a0ec2e10b30b861899a819c9be179c25d17d2618f21ea483f6cef1048685866f6280b90214f90211a04a8437f5c35d03bb0f8a741dd35165a3ba132ee4d92c701ae3c8d4f3d65e3e49a00bd6904465fd8035357a63750cae05707e844a1acb5cc0b25468c20c90871e4fa0f320d73efaaf4c6a68ad6167118b549bef6844feb1762ea89e8758b967755f33a0fbe27008eb14d98c309125f47854636e1ef033fa0d5c37ccce89771f6ab7f582a0c74e46c4c62619a09a045ad57adb4ec3de037d029dcdb18d2678d4072d243997a017ff8546a33be106018e5fc483fd7e8585bd2ea126fa22a8a6f6904ae38c334fa0db17377119d9809a4ee6e957077fe57898cabb89e3a162e9c81b21cb50c0ab2ca0ffc816f07157a6683c583e7a277ddbd420597cdc88e2702ebf5ccef530e7a784a01d532e49c4212a4ba56346708347489ebf8569fdf5d9aee201a100a1f03d0c7ca020012a52d3dc1f650a6b5982e5ef496d4fd0dcfebddf987abfb245797a885226a0d89e27e7afbe451339afbb0ab8dda61ff272eebc961fae9aebf8efeb02e76caea0bada48b96bc636c5409fe8671d3674948dcd5551121e219590e9a97067dd1950a04791e8c4db73ba380a6db843bde19109c14aa54ebafcc8788fcf70811808a44ba0fbb127d6d3a4942c9c1a274c4b17f397fcc7637a00e7c72504f1141259ab464fa0760ffccd967a3c281e3f4e6a663ad2aa4fe9b1ad684ef0e7cbf57b9153419c0aa08b5bddc52a031d21e215aaddcd6f750457a121c8d33d25aebe85007fa28410d980b90214f90211a0ab7f9777fee3fef04803a2659346a83e975f2bb4b29233b1135d6974531424a2a087b6be7fa8c65601f0458fa21ab2f46e4ba6b04480616e136a206373f203d65ca003d038b1a4609cc7d325a6d7f851c29e491f2b1a67832eb2a317322a010511d5a03930bd18e66580c73cc5926cc57deab76b04857c5ab63c6a9b30f6e8fc82b0f5a0343a2761a59a0e40148b94bc2df522b24983d71bf440fd570cb470beebdd2db1a00901f2c4aa4bab6fb3f04869adc2aa42b8c864d99e90d508d0d8f875c430f67da08e30cf6fa8512d687a8dc31c6ce02ab9227100a8e63fb9cea9bb9cb524dab03da064d53dcabbc6477b41f2f581bfc4e72bb097c805e1b81662f689a821cfcbfe25a05cff2284c06a2206660ecf684cedfe1e46eaf8d93b02818bd852996460e79175a098c2465d4c6ab5818167931acf7d8458a6868e44c875a8a957bc3bd302d33a0da05ddc7f1a63c24ef3aabfbbdad6f9c8ee5782faa554c2ec5da629508ff0252e2ca026887eec68c07a32d428ea8753cc12c8ac9eb8884a68dd89ba90e99c528c4e10a000a145035505187db0fb013cf4664a3d83e9197d30da170c2779615325beabe2a0411c1a6582428012cbc575a8a5e62819bc644f0c925cfd8d9f692889d41cc38ba02e68ba05db68da35dfbe9bc6af88b44aa49cc0b2dd5f2925fd2dd007bdfda7f7a0e85c87ca7f7b42d43d418798ad0de2aa64ca281c7b7cab3b66e17c4f595d1fab80b90214f90211a091d29c21c9ff7416e2e7314f5912e2e6209a99026e12ccacbfd1b498ed981076a0e15768ca54a99f80276a1e023c7a36a9eb3106f54c97210e694f0d090f17173fa06bf3544c939680c6c422185f2facbcf0afc3ac29ad7c1b69078899f410a0c710a0f9c7b8b679bfb81b1d1199c7cdbda437a3ba66daad5d3f1ed9fab5a9fc97f349a0085f12b4134e60002ece5215bc3167dddedd2bc384c0372084e1a22ae202a655a06ecefb6536d152f4e3788f2ee4f1e9e7a254c6506db3ed44d8709b259a4f5fe0a075de2affd5601392de0f42964bc82887090a33c4709e4dd4a72eebee53bce929a074bcc926b8e4d5be57b27b479e255d9322d038b2e77e7676724fc7b0efcfc74aa03812659ea8178131121193ee1ae4c30ab054a8744e0c63d2081f910e770fbc21a087e47b3e87d53624deb9178d2ded0d6ba6313488f2d1c730906c47bf1d1d3281a04eee770df3cd32cc9321de094939802f5e53ba223bacade769402abf8cf91dfca01f8ade399e93c68c8ef2703a9d41c6cddbd6c3d04d745a8a5a76ab61bd049527a005a4bef0743f40d8dee65799a6b8efa044f304709ca44dde2d3ccc8104abf651a0c6a8531ac33aaf86109ea56ffa9cbf4517ff8d37f76520da89437150abd77c4ba0ace333416d0dc931ee3a78f7c2386201cd312b19c20c6b9c57abfa313077b9bfa0548c28373c9f2a643ef5a50af13b24f340dbd9e8f34d6502bfb1e5add3ebf28d80b90214f90211a080c24e029fc0f8ebb93b6d6bccc328f2c49ff474159e7e3e9827a207035ebb35a0c9feaaa5752601a286b0cde72242d2fa36ffa4c94412d6d5b6d4ea5799461af5a0683949a9b5c22c62b06dd9922730ec1b3e832a514a02c6ffe380655ffe99c77ca045c595e624971dbcd2d97c594256bd01028a7ee5e550c5b0ec7502f5dd95256ba0ca296ec5d7a49c541685c43abe1619b1e80ebad10772d097a3373de1aece72b1a0f2843d3f1c0e5306766bfb47be6e115dbc68c840464ba8761166abff7be91a5ea000e449032d65048440433012666e546982ee09177aa9e900337abbe4457f9580a06a5b5fcf57a1eae3d7df0c4802b60b42de2311f1fa23a1c979396dea8e8a8974a00e209da4553e88d2710459faceff7b244e5bdf585df0d5b4462af76b28761954a01ac8b8bf470510a3488e8303f68aa3002a8d2902817c7e82f5e51d0b9147573fa044cd7e841cbba3859318743462e833e258363b91c99ca0873660a96a6985a1d6a04c5b8dd32d19f61ebf70d2bdd6b81ffb3d4baebf183bf744f4f107cabd707549a060e423d7e6c04aa60df0791b20bf6f1384e7016ad73f91dcace04ac81696181ca0368c26079c1659d06fc3979e74c1fadc91fd86c133c2b0b60fc1680a63afb908a012442c17735a2b4ad90e0dea4ed270ed04d743fd373043607d0721b0a4c20f69a0d04973872715327c4cff70af4fa25cc98aedc6019c78bfe7bb5322e7be442a0780b90214f90211a02003d028d7a9952f3537f1bacd5355f9cd15ffdb3b0320465469ee0bd63d8cdfa08ae64938d7e196d11df9602ac8f51544847a288278ca5139ab56c8c3d8c4168ca0c6b1974b09b1cf73a309e6c25dab139cd51b90771af2683d2381b8d86ea2ee55a0d646da3405c7f32a3ee3f1ed0b39e35a751569c59238faae3d47e5d3de1fcabea0139a453d2776bcdd371adb7a17314d9a8e8b9cc14b592ab01a06d839aa87e89aa072a84d2d5a35b6cd6dddc422da763360da79fb558e00131c074a85eda4abe9a1a0e17e40d1ef509e40f0dffb0a63c5079bc59c89454222b9cb2b98bb1560bb08e8a00ee17c5d8efcbafd4e019e1ca3bb482b6f0f880956587a202c67b4af06359d7fa012d62d4c477b2222497b946546b213b92271b86d280cb9ad13e92ca3d5af4be0a0307c34d06f6f3b097a0407050aefad6ce44a77b204f968b96a5be4318dab3854a010c723df1ef0bbf80f0c0f8d4959a5394eec82d69f8685eada1e8e14bb94cc80a01d4e35a6bbe6d381b7a77f54a7fc4416f242a8d0f7574139e86763b9dd5f6b7ca0e4ce8a2aa1901506dcc0a355180be12ab9ee75f34aca311884d5fba395b14ea1a05d8b0c593e7f79dd15a71355a0145b1b0a318b532a51317e8ab9850aec954a66a0faade219a3ce432c2ec65bec1ca692fc879c4875ec2c00e81489eff802701083a0d2883ea362abca76be4a9110c9bf2b8f46ae9ed204b136e15929e27cc412c7dd80b90214f90211a0c2332f0f15eedca1e1434810d8e6cd9a3f75688c80f7617f241dff87cc0dde3aa0b7e6e083d2a65e27090079da274e01bc1afc91ae247a670fbe8bce0d76b44b8da093460542ccacb9680fe5a79abfcc97db68d0d845b438b27492945dc60cc37486a09e76311a289abf2c706fe8c5242ab3ad3188fdb1c0626a4d504bcad5b747c9ffa0de04dffa807147cb8ba0d4d81d36d7fb95a6e60c6245829db5d0e2cf9bbbddaca026aee6ee7e9c8cd1347e3b662f6ebb225d10d3848059db6305a60965d8609e61a0b269cb09d110523bb117a9934f4fc6d974cc03db5f36a3c35e22938970b203f8a0a555ab1fc84447a85c44c00365fa53cdd626887469ab89a84aa17b823b257665a032400a2e1fc559f2a0f9f9ebc64f09f79c3806f96ca38dbfc1c66a76c26d45b5a01f02079c66611f4396221463acabd93e084bffcac382f5bac2568f1f663eb121a02eed784638a1afebae6a6384a5237928fd0846f7159fcaed30c7430f942f0839a0283461d805fd72ed60627e1e74e518bcf65565aef6ae4093671f1af2ca7f05e0a00524b4ac006d6e11c3b28d780b0707dbab7c47b0691b9b707a2dd7d01b1e7b61a07b0517a176691aec7337930c7a62277472d7514ba142a0a9e41cb4160d16d5bda0c8c8bc1ca8c13493c98d3deebebdc1e1e4865bc59120a0da1134b95c6a825368a0298f42242f7de6281b41e10e0c96a01f9044795ebc1e41345e4988799345dac280b90214f90211a095b9889317a088e2ff979d85893e23cb3ec091a0eced00bf2608b09528d30eaea08e0a2aef31d3817c95ca9561af8c5788e3afcab0783439825a66c1a4210cf3b6a049ef720f106c1c9b15339026eb21330d9bfde8cd1eedb4817b01d34ca36e2526a015066ea9d934b8f486b7f7c5dd5abcd0f87c0585fa71eb70d6e5176d76ec1c6ba0f1c71b8a6ce31478dda7dd74cd9f40be0d81640f2a8e1d19cacc3262c5adfa4ba072637ebfc507d4d39f4c9936d415febbd2fd8bb29c6e47951c135f1e926af9b5a050cf735290e3013c3406a388f65eb55d2fe19016995a9620352fdd2759260355a01cae5c026e5444a2d8a10ebc11973e14a1d687f9ef9547c4878020b85fc32df2a04ddb98a0ae6079fbccb2836c9f30b6fe2b71fd6ecbc53fcc3d662f7f65c2ae70a04c972c242ec2b42b94ce4cff4d67ca3ead89ed4093c2640c37a0ae5c8c402ce8a0422f91986f6c6b0763f88a8efa354cf97c160fee718ae16b94a6267834c539f0a0b5b7fa471f9e267d44f42ca23b05e7577d79a708b586e5f3bfc91cffdfc9595fa02dc1b9d365a2d9b32350e6df9a1a72d7cd7f288040254667807f91e1d4b37f74a005d3dc75f43c404dca66b03fa5bb26cceb435a55b065ab0919450c2f83c30fdfa05321c6545b832cbf31ca6d95b7b9676ef92d32bd65b151f2d9b410f85324dfd8a0fb93825b957d2ec4094bc6a82b1261687eacbad17cc4fae2cc62f41263a0bf0380"); NodeDataMessage msg = new NodeDataMessage(data); NodeDataMessage msg2 = new NodeDataMessage(msg.getDataList()); assertArrayEquals(msg.getEncoded(), msg2.getEncoded()); } @Test public void testNodeDataMessageEmpty() { byte[] data = Hex.decode("c0"); NodeDataMessage msg = new NodeDataMessage(data); NodeDataMessage msg2 = new NodeDataMessage(msg.getDataList()); assertArrayEquals(msg.getEncoded(), msg2.getEncoded()); } }
27,403
569.916667
25,723
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/eth/handler/ProcessNewBlockHashesTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.handler; import org.ethereum.core.BlockIdentifier; import org.ethereum.net.eth.message.NewBlockHashesMessage; import org.ethereum.net.server.Channel; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Testing {@link Eth62#processNewBlockHashes(NewBlockHashesMessage)} */ public class ProcessNewBlockHashesTest { private static final Logger logger = LoggerFactory.getLogger("test"); private class Eth62Tester extends Eth62 { private byte[] blockHash; private int maxBlockAsk; private int skip; private boolean reverse; private boolean wasCalled = false; Eth62Tester() { this.syncDone = true; this.channel = new Channel(); } void setGetNewBlockHeadersParams(byte[] blockHash, int maxBlocksAsk, int skip, boolean reverse) { this.blockHash = blockHash; this.maxBlockAsk = maxBlocksAsk; this.skip = skip; this.reverse = reverse; this.wasCalled = false; } @Override protected synchronized void sendGetNewBlockHeaders(byte[] blockHash, int maxBlocksAsk, int skip, boolean reverse) { this.wasCalled = true; logger.error("Request for sending new headers: hash {}, max {}, skip {}, reverse {}", Hex.toHexString(blockHash), maxBlocksAsk, skip, reverse); assert Arrays.equals(blockHash, this.blockHash) && maxBlocksAsk == this.maxBlockAsk && skip == this.skip && reverse == this.reverse; } } private Eth62Tester ethHandler; public ProcessNewBlockHashesTest() { ethHandler = new Eth62Tester(); } @Test public void testSingleHashHandling() { List<BlockIdentifier> blockIdentifiers = new ArrayList<>(); byte[] blockHash = new byte[] {2, 3, 4}; long blockNumber = 123; blockIdentifiers.add(new BlockIdentifier(blockHash, blockNumber)); NewBlockHashesMessage msg = new NewBlockHashesMessage(blockIdentifiers); ethHandler.setGetNewBlockHeadersParams(blockHash, 1, 0, false); ethHandler.processNewBlockHashes(msg); assert ethHandler.wasCalled; } @Test public void testSeveralHashesHandling() { List<BlockIdentifier> blockIdentifiers = new ArrayList<>(); byte[] blockHash1 = new byte[] {2, 3, 4}; long blockNumber1 = 123; byte[] blockHash2 = new byte[] {5, 3, 4}; long blockNumber2 = 124; byte[] blockHash3 = new byte[] {2, 6, 4}; long blockNumber3 = 125; blockIdentifiers.add(new BlockIdentifier(blockHash1, blockNumber1)); blockIdentifiers.add(new BlockIdentifier(blockHash2, blockNumber2)); blockIdentifiers.add(new BlockIdentifier(blockHash3, blockNumber3)); NewBlockHashesMessage msg = new NewBlockHashesMessage(blockIdentifiers); ethHandler.setGetNewBlockHeadersParams(blockHash1, 3, 0, false); ethHandler.processNewBlockHashes(msg); assert ethHandler.wasCalled; } @Test public void testSeveralHashesMixedOrderHandling() { List<BlockIdentifier> blockIdentifiers = new ArrayList<>(); byte[] blockHash1 = new byte[] {5, 3, 4}; long blockNumber1 = 124; byte[] blockHash2 = new byte[] {2, 3, 4}; long blockNumber2 = 123; byte[] blockHash3 = new byte[] {2, 6, 4}; long blockNumber3 = 125; blockIdentifiers.add(new BlockIdentifier(blockHash1, blockNumber1)); blockIdentifiers.add(new BlockIdentifier(blockHash2, blockNumber2)); blockIdentifiers.add(new BlockIdentifier(blockHash3, blockNumber3)); NewBlockHashesMessage msg = new NewBlockHashesMessage(blockIdentifiers); ethHandler.setGetNewBlockHeadersParams(blockHash2, 3, 0, false); ethHandler.processNewBlockHashes(msg); assert ethHandler.wasCalled; } }
4,891
37.519685
123
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/eth/handler/HeaderMessageValidationTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.handler; import org.ethereum.core.BlockHeader; import org.ethereum.net.eth.message.BlockHeadersMessage; import org.ethereum.net.eth.message.GetBlockHeadersMessage; import org.junit.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Testing {@link org.ethereum.net.eth.handler.Eth62#isValid(BlockHeadersMessage, GetBlockHeadersMessageWrapper)} */ public class HeaderMessageValidationTest { private byte[] EMPTY_ARRAY = new byte[0]; private class Eth62Tester extends Eth62 { boolean blockHeaderMessageValid(BlockHeadersMessage msg, GetBlockHeadersMessageWrapper request) { return super.isValid(msg, request); } } private Eth62Tester ethHandler; public HeaderMessageValidationTest() { ethHandler = new Eth62Tester(); } @Test public void testSingleBlockResponse() { long blockNumber = 0L; BlockHeader blockHeader = new BlockHeader(new byte[] {11, 12}, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY, blockNumber, EMPTY_ARRAY, 1L, 2L, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY); List<BlockHeader> blockHeaders = new ArrayList<>(); blockHeaders.add(blockHeader); BlockHeadersMessage msg = new BlockHeadersMessage(blockHeaders); byte[] hash = blockHeader.getHash(); // Block number doesn't matter when hash is provided in request GetBlockHeadersMessage requestHash = new GetBlockHeadersMessage(123L, hash, 1, 0, false); GetBlockHeadersMessageWrapper wrapperHash = new GetBlockHeadersMessageWrapper(requestHash); assert ethHandler.blockHeaderMessageValid(msg, wrapperHash); // Getting same with block number request GetBlockHeadersMessage requestNumber = new GetBlockHeadersMessage(blockNumber, null, 1, 0, false); GetBlockHeadersMessageWrapper wrapperNumber = new GetBlockHeadersMessageWrapper(requestNumber); assert ethHandler.blockHeaderMessageValid(msg, wrapperNumber); // Getting same with reverse request GetBlockHeadersMessage requestReverse = new GetBlockHeadersMessage(blockNumber, null, 1, 0, true); GetBlockHeadersMessageWrapper wrapperReverse = new GetBlockHeadersMessageWrapper(requestReverse); assert ethHandler.blockHeaderMessageValid(msg, wrapperReverse); // Getting same with skip request GetBlockHeadersMessage requestSkip = new GetBlockHeadersMessage(blockNumber, null, 1, 10, false); GetBlockHeadersMessageWrapper wrapperSkip = new GetBlockHeadersMessageWrapper(requestSkip); assert ethHandler.blockHeaderMessageValid(msg, wrapperSkip); } @Test public void testFewBlocksNoSkip() { List<BlockHeader> blockHeaders = new ArrayList<>(); long blockNumber1 = 0L; BlockHeader blockHeader1 = new BlockHeader(new byte[] {11, 12}, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY, blockNumber1, EMPTY_ARRAY, 1L, 2L, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY); byte[] hash1 = blockHeader1.getHash(); blockHeaders.add(blockHeader1); long blockNumber2 = 1L; BlockHeader blockHeader2 = new BlockHeader(hash1, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY, blockNumber2, EMPTY_ARRAY, 1L, 2L, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY); byte[] hash2 = blockHeader2.getHash(); blockHeaders.add(blockHeader2); BlockHeadersMessage msg = new BlockHeadersMessage(blockHeaders); // Block number doesn't matter when hash is provided in request GetBlockHeadersMessage requestHash = new GetBlockHeadersMessage(123L, hash1, 2, 0, false); GetBlockHeadersMessageWrapper wrapperHash = new GetBlockHeadersMessageWrapper(requestHash); assert ethHandler.blockHeaderMessageValid(msg, wrapperHash); // Getting same with block number request GetBlockHeadersMessage requestNumber = new GetBlockHeadersMessage(blockNumber1, null, 2, 0, false); GetBlockHeadersMessageWrapper wrapperNumber = new GetBlockHeadersMessageWrapper(requestNumber); assert ethHandler.blockHeaderMessageValid(msg, wrapperNumber); // Reverse list Collections.reverse(blockHeaders); GetBlockHeadersMessage requestReverse = new GetBlockHeadersMessage(blockNumber2, null, 2, 0, true); GetBlockHeadersMessageWrapper wrapperReverse = new GetBlockHeadersMessageWrapper(requestReverse); assert ethHandler.blockHeaderMessageValid(msg, wrapperReverse); } @Test public void testFewBlocksWithSkip() { List<BlockHeader> blockHeaders = new ArrayList<>(); long blockNumber1 = 0L; BlockHeader blockHeader1 = new BlockHeader(new byte[] {11, 12}, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY, blockNumber1, EMPTY_ARRAY, 1L, 2L, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY); blockHeaders.add(blockHeader1); long blockNumber2 = 16L; BlockHeader blockHeader2 = new BlockHeader(new byte[] {12, 13}, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY, blockNumber2, EMPTY_ARRAY, 1L, 2L, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY); blockHeaders.add(blockHeader2); long blockNumber3 = 32L; BlockHeader blockHeader3 = new BlockHeader(new byte[] {14, 15}, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY, blockNumber3, EMPTY_ARRAY, 1L, 2L, EMPTY_ARRAY, EMPTY_ARRAY, EMPTY_ARRAY); blockHeaders.add(blockHeader3); BlockHeadersMessage msg = new BlockHeadersMessage(blockHeaders); GetBlockHeadersMessage requestNumber = new GetBlockHeadersMessage(blockNumber1, null, 3, 15, false); GetBlockHeadersMessageWrapper wrapperNumber = new GetBlockHeadersMessageWrapper(requestNumber); assert ethHandler.blockHeaderMessageValid(msg, wrapperNumber); // Requesting more than we have GetBlockHeadersMessage requestMore = new GetBlockHeadersMessage(blockNumber1, null, 4, 15, false); GetBlockHeadersMessageWrapper wrapperMore = new GetBlockHeadersMessageWrapper(requestMore); assert ethHandler.blockHeaderMessageValid(msg, wrapperMore); // Reverse list Collections.reverse(blockHeaders); GetBlockHeadersMessage requestReverse = new GetBlockHeadersMessage(blockNumber3, null, 3, 15, true); GetBlockHeadersMessageWrapper wrapperReverse = new GetBlockHeadersMessageWrapper(requestReverse); assert ethHandler.blockHeaderMessageValid(msg, wrapperReverse); } }
7,386
47.281046
113
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/eth/handler/LockBlockchainTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.eth.handler; import org.ethereum.config.CommonConfig; import org.ethereum.config.NoAutoscan; import org.ethereum.config.SystemProperties; import org.ethereum.core.Block; import org.ethereum.core.BlockHeader; import org.ethereum.core.Blockchain; import org.ethereum.core.BlockchainImpl; import org.ethereum.db.BlockStore; import org.ethereum.db.BlockStoreDummy; import org.ethereum.listener.CompositeEthereumListener; import org.ethereum.net.eth.message.EthMessage; import org.ethereum.net.eth.message.GetBlockBodiesMessage; import org.ethereum.net.eth.message.GetBlockHeadersMessage; import org.ethereum.sync.SyncManager; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; import org.spongycastle.util.encoders.Hex; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; /** * Testing whether Eth handler {@link Eth62} is blocking {@link BlockchainImpl} */ public class LockBlockchainTest { private final AtomicBoolean result = new AtomicBoolean(); private Blockchain blockchain; private final static long DELAY = 1000; //Default delay in ms private final static String BLOCK_RLP = "f901f8f901f3a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a09178d0f23c965d81f0834a4c72c6253ce6830f4022b1359aaebfc1ecba442d4ea056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080832fefd8808080a0000000000000000000000000000000000000000000000000000000000000000088000000000000002ac0c0"; public LockBlockchainTest() { SysPropConfig1.props.overrideParams( "peer.discovery.enabled", "false", "peer.listen.port", "37777", "peer.privateKey", "3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c", "genesis", "genesis-light.json", "database.dir", "testDB-1"); final BlockStore blockStoreDummy = new BlockStoreDummy() { @Override public synchronized Block getChainBlockByNumber(long blockNumber) { return super.getChainBlockByNumber(blockNumber); } @Override public synchronized List<BlockHeader> getListHeadersEndWith(byte[] hash, long qty) { return super.getListHeadersEndWith(hash, qty); } @Override public synchronized Block getBestBlock() { return new Block(Hex.decode(BLOCK_RLP)); } }; this.blockchain = new BlockchainImpl(SysPropConfig1.props) { @Override public synchronized boolean isBlockExist(byte[] hash) { try { this.blockStore = blockStoreDummy; Thread.sleep(100000); } catch (InterruptedException e) { e.printStackTrace(); } return true; } }; SysPropConfig1.testHandler = new Eth62(SysPropConfig1.props, blockchain, blockStoreDummy, new CompositeEthereumListener()) { { this.blockstore = blockStoreDummy; this.syncManager = Mockito.mock(SyncManager.class); } @Override public synchronized void sendStatus() { super.sendStatus(); } @Override protected void sendMessage(EthMessage message) { result.set(true); System.out.println("Mocking message sending..."); } }; } @Before public void setUp() throws Exception { result.set(false); } @Configuration @NoAutoscan public static class SysPropConfig1 { static Eth62 testHandler = null; @Bean @Scope("prototype") public Eth62 eth62() { return testHandler; } static SystemProperties props = new SystemProperties(); @Bean public SystemProperties systemProperties() { return props; } } @Test public synchronized void testHeadersWithoutSkip() throws FileNotFoundException, InterruptedException { ExecutorService executor1 = Executors.newSingleThreadExecutor(); executor1.submit(() -> { blockchain.isBlockExist(null); } ); this.wait(DELAY); ExecutorService executor2 = Executors.newSingleThreadExecutor(); executor2.submit(() -> { GetBlockHeadersMessage msg = new GetBlockHeadersMessage(1L, new byte[0], 10, 0, false); SysPropConfig1.testHandler.processGetBlockHeaders(msg); } ); this.wait(DELAY); assert result.get(); } @Test public synchronized void testHeadersWithSkip() throws FileNotFoundException, InterruptedException { ExecutorService executor1 = Executors.newSingleThreadExecutor(); executor1.submit(() -> { blockchain.isBlockExist(null); } ); this.wait(DELAY); ExecutorService executor2 = Executors.newSingleThreadExecutor(); executor2.submit(() -> { GetBlockHeadersMessage msg = new GetBlockHeadersMessage(1L, new byte[0], 10, 5, false); SysPropConfig1.testHandler.processGetBlockHeaders(msg); } ); this.wait(DELAY); assert result.get(); } @Test public synchronized void testBodies() throws FileNotFoundException, InterruptedException { ExecutorService executor1 = Executors.newSingleThreadExecutor(); executor1.submit(() -> { blockchain.isBlockExist(null); } ); this.wait(DELAY); ExecutorService executor2 = Executors.newSingleThreadExecutor(); executor2.submit(() -> { List<byte[]> hashes = new ArrayList<>(); hashes.add(new byte[] {1, 2, 3}); hashes.add(new byte[] {4, 5, 6}); GetBlockBodiesMessage msg = new GetBlockBodiesMessage(hashes); SysPropConfig1.testHandler.processGetBlockBodies(msg); } ); this.wait(DELAY); assert result.get(); } @Test public synchronized void testStatus() throws FileNotFoundException, InterruptedException { ExecutorService executor1 = Executors.newSingleThreadExecutor(); executor1.submit(() -> { blockchain.isBlockExist(null); } ); this.wait(DELAY); ExecutorService executor2 = Executors.newSingleThreadExecutor(); executor2.submit(() -> { try { SysPropConfig1.testHandler.sendStatus(); } catch (Exception e) { e.printStackTrace(); } } ); this.wait(DELAY); assert result.get(); } }
8,647
38.309091
1,061
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/p2p/EIP8P2pTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.p2p; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.spongycastle.util.encoders.Hex.decode; /** * @author Mikhail Kalinin * @since 18.02.2016 */ public class EIP8P2pTest { // devp2p hello packet advertising version 55 and containing a few additional list elements @Test public void test1() { HelloMessage msg = new HelloMessage(decode( "f87137916b6e6574682f76302e39312f706c616e39cdc5836574683dc6846d6f726b1682270fb840" + "fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569" + "bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877c883666f6f836261720304")); assertEquals(55, msg.getP2PVersion()); } }
1,567
35.465116
100
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/wire/AdaptiveMessageIdsTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.wire; import org.ethereum.net.client.Capability; import org.ethereum.net.eth.EthVersion; import org.ethereum.net.eth.message.EthMessageCodes; import org.ethereum.net.p2p.P2pMessageCodes; import org.ethereum.net.rlpx.MessageCodesResolver; import org.ethereum.net.shh.ShhHandler; import org.ethereum.net.shh.ShhMessageCodes; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.ethereum.net.eth.EthVersion.*; /** * @author Roman Mandeleil * @since 15.10.2014 */ public class AdaptiveMessageIdsTest { private MessageCodesResolver messageCodesResolver; @Before public void setUp() { messageCodesResolver = new MessageCodesResolver(); } @Test public void test1() { assertEquals(7, P2pMessageCodes.values().length); assertEquals(0, messageCodesResolver.withP2pOffset(P2pMessageCodes.HELLO.asByte())); assertEquals(1, messageCodesResolver.withP2pOffset(P2pMessageCodes.DISCONNECT.asByte())); assertEquals(2, messageCodesResolver.withP2pOffset(P2pMessageCodes.PING.asByte())); assertEquals(3, messageCodesResolver.withP2pOffset(P2pMessageCodes.PONG.asByte())); assertEquals(4, messageCodesResolver.withP2pOffset(P2pMessageCodes.GET_PEERS.asByte())); assertEquals(5, messageCodesResolver.withP2pOffset(P2pMessageCodes.PEERS.asByte())); assertEquals(15, messageCodesResolver.withP2pOffset(P2pMessageCodes.USER.asByte())); } @Test public void test2() { assertEquals(8, EthMessageCodes.values(V62).length); assertEquals(0, EthMessageCodes.STATUS.asByte()); assertEquals(1, EthMessageCodes.NEW_BLOCK_HASHES.asByte()); assertEquals(2, EthMessageCodes.TRANSACTIONS.asByte()); assertEquals(3, EthMessageCodes.GET_BLOCK_HEADERS.asByte()); assertEquals(4, EthMessageCodes.BLOCK_HEADERS.asByte()); assertEquals(5, EthMessageCodes.GET_BLOCK_BODIES.asByte()); assertEquals(6, EthMessageCodes.BLOCK_BODIES.asByte()); assertEquals(7, EthMessageCodes.NEW_BLOCK.asByte()); messageCodesResolver.setEthOffset(0x10); assertEquals(0x10 + 0, messageCodesResolver.withEthOffset(EthMessageCodes.STATUS.asByte())); assertEquals(0x10 + 1, messageCodesResolver.withEthOffset(EthMessageCodes.NEW_BLOCK_HASHES.asByte())); assertEquals(0x10 + 2, messageCodesResolver.withEthOffset(EthMessageCodes.TRANSACTIONS.asByte())); assertEquals(0x10 + 3, messageCodesResolver.withEthOffset(EthMessageCodes.GET_BLOCK_HEADERS.asByte())); assertEquals(0x10 + 4, messageCodesResolver.withEthOffset(EthMessageCodes.BLOCK_HEADERS.asByte())); assertEquals(0x10 + 5, messageCodesResolver.withEthOffset(EthMessageCodes.GET_BLOCK_BODIES.asByte())); assertEquals(0x10 + 6, messageCodesResolver.withEthOffset(EthMessageCodes.BLOCK_BODIES.asByte())); assertEquals(0x10 + 7, messageCodesResolver.withEthOffset(EthMessageCodes.NEW_BLOCK.asByte())); } @Test public void test3() { assertEquals(3, ShhMessageCodes.values().length); assertEquals(0, ShhMessageCodes.STATUS.asByte()); assertEquals(1, ShhMessageCodes.MESSAGE.asByte()); assertEquals(2, ShhMessageCodes.FILTER.asByte()); messageCodesResolver.setShhOffset(0x20); assertEquals(0x20 + 0, messageCodesResolver.withShhOffset(ShhMessageCodes.STATUS.asByte())); assertEquals(0x20 + 1, messageCodesResolver.withShhOffset(ShhMessageCodes.MESSAGE.asByte())); assertEquals(0x20 + 2, messageCodesResolver.withShhOffset(ShhMessageCodes.FILTER.asByte())); } @Test public void test4() { List<Capability> capabilities = Arrays.asList( new Capability(Capability.ETH, EthVersion.V62.getCode()), new Capability(Capability.SHH, ShhHandler.VERSION)); messageCodesResolver.init(capabilities); assertEquals(0x10 + 0, messageCodesResolver.withEthOffset(EthMessageCodes.STATUS.asByte())); assertEquals(0x10 + 1, messageCodesResolver.withEthOffset(EthMessageCodes.NEW_BLOCK_HASHES.asByte())); assertEquals(0x10 + 2, messageCodesResolver.withEthOffset(EthMessageCodes.TRANSACTIONS.asByte())); assertEquals(0x10 + 3, messageCodesResolver.withEthOffset(EthMessageCodes.GET_BLOCK_HEADERS.asByte())); assertEquals(0x10 + 4, messageCodesResolver.withEthOffset(EthMessageCodes.BLOCK_HEADERS.asByte())); assertEquals(0x10 + 5, messageCodesResolver.withEthOffset(EthMessageCodes.GET_BLOCK_BODIES.asByte())); assertEquals(0x10 + 6, messageCodesResolver.withEthOffset(EthMessageCodes.BLOCK_BODIES.asByte())); assertEquals(0x10 + 7, messageCodesResolver.withEthOffset(EthMessageCodes.NEW_BLOCK.asByte())); assertEquals(0x18 + 0, messageCodesResolver.withShhOffset(ShhMessageCodes.STATUS.asByte())); assertEquals(0x18 + 1, messageCodesResolver.withShhOffset(ShhMessageCodes.MESSAGE.asByte())); assertEquals(0x18 + 2, messageCodesResolver.withShhOffset(ShhMessageCodes.FILTER.asByte())); } @Test // Capabilities should be read in alphabetical order public void test5() { List<Capability> capabilities = Arrays.asList( new Capability(Capability.SHH, ShhHandler.VERSION), new Capability(Capability.ETH, EthVersion.V62.getCode())); messageCodesResolver.init(capabilities); assertEquals(0x10 + 0, messageCodesResolver.withEthOffset(EthMessageCodes.STATUS.asByte())); assertEquals(0x10 + 1, messageCodesResolver.withEthOffset(EthMessageCodes.NEW_BLOCK_HASHES.asByte())); assertEquals(0x10 + 2, messageCodesResolver.withEthOffset(EthMessageCodes.TRANSACTIONS.asByte())); assertEquals(0x10 + 3, messageCodesResolver.withEthOffset(EthMessageCodes.GET_BLOCK_HEADERS.asByte())); assertEquals(0x10 + 4, messageCodesResolver.withEthOffset(EthMessageCodes.BLOCK_HEADERS.asByte())); assertEquals(0x10 + 5, messageCodesResolver.withEthOffset(EthMessageCodes.GET_BLOCK_BODIES.asByte())); assertEquals(0x10 + 6, messageCodesResolver.withEthOffset(EthMessageCodes.BLOCK_BODIES.asByte())); assertEquals(0x10 + 7, messageCodesResolver.withEthOffset(EthMessageCodes.NEW_BLOCK.asByte())); assertEquals(0x18 + 0, messageCodesResolver.withShhOffset(ShhMessageCodes.STATUS.asByte())); assertEquals(0x18 + 1, messageCodesResolver.withShhOffset(ShhMessageCodes.MESSAGE.asByte())); assertEquals(0x18 + 2, messageCodesResolver.withShhOffset(ShhMessageCodes.FILTER.asByte())); } }
7,490
47.960784
111
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/swarm/MessageTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import org.ethereum.net.client.Capability; import org.ethereum.net.swarm.bzz.BzzStatusMessage; import org.ethereum.net.swarm.bzz.PeerAddress; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; /** * Created by Admin on 25.06.2015. */ public class MessageTest { @Test public void statusMessageTest() { BzzStatusMessage m1 = new BzzStatusMessage(777, "IdString", new PeerAddress(new byte[] {127,0,0, (byte) 255}, 1010, new byte[] {1,2,3,4}), 888, Arrays.asList(new Capability[] { new Capability("bzz", (byte) 0), new Capability("shh", (byte) 202), })); byte[] encoded = m1.getEncoded(); BzzStatusMessage m2 = new BzzStatusMessage(encoded); System.out.println(m1); System.out.println(m2); Assert.assertEquals(m1.getVersion(), m2.getVersion()); Assert.assertEquals(m1.getId(), m2.getId()); Assert.assertTrue(Arrays.equals(m1.getAddr().getIp(), m2.getAddr().getIp())); Assert.assertTrue(Arrays.equals(m1.getAddr().getId(), m2.getAddr().getId())); Assert.assertEquals(m1.getAddr().getPort(), m2.getAddr().getPort()); Assert.assertEquals(m1.getNetworkId(), m2.getNetworkId()); Assert.assertEquals(m1.getCapabilities(), m2.getCapabilities()); } }
2,196
37.54386
99
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/swarm/RLPTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import org.ethereum.util.RLP; import org.ethereum.util.RLPElement; import org.ethereum.util.RLPList; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import java.util.Arrays; /** * Created by Admin on 06.07.2015. */ public class RLPTest { @Test public void simpleTest() { for (int i = 0; i < 255; i++) { byte data = (byte) i; byte[] bytes1 = RLP.encodeElement(new byte[]{data}); byte[] bytes2 = RLP.encodeByte(data); System.out.println(i + ": " + Arrays.toString(bytes1) + Arrays.toString(bytes2)); } } @Test public void zeroTest() { { byte[] e = RLP.encodeList( RLP.encodeString("aaa"), RLP.encodeInt((byte) 0) ); System.out.println(Hex.toHexString(e)); RLPList l1 = (RLPList) RLP.decode2(e).get(0); System.out.println(new String (l1.get(0).getRLPData())); System.out.println(l1.get(1).getRLPData()); byte[] rlpData = l1.get(1).getRLPData(); byte ourByte = rlpData == null ? 0 : rlpData[0]; } { byte[] e = RLP.encodeList( // RLP.encodeString("aaa"), RLP.encodeElement(new byte[] {1}), RLP.encodeElement(new byte[] {0}) ); System.out.println(Hex.toHexString(e)); } } @Test public void frameHaderTest() { byte[] bytes = Hex.decode("c28080"); RLPList list = RLP.decode2(bytes); System.out.println(list.size()); System.out.println(list.get(0)); byte[] bytes1 = RLP.encodeList(RLP.encodeInt(0)); System.out.println(Arrays.toString(bytes1)); } }
2,623
29.870588
93
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/swarm/ManifestTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Test; import java.nio.charset.StandardCharsets; /** * Created by Admin on 11.06.2015. */ public class ManifestTest { static String testManifest = "{\"entries\":[\n" + " {\"path\":\"a/b\"},\n" + " {\"path\":\"a\"},\n" + " {\"path\":\"a/bb\"},\n" + " {\"path\":\"a/bd\"},\n" + " {\"path\":\"a/bb/c\"}\n" + "]}"; static DPA dpa = new SimpleDPA(); @Test public void simpleTest() { Manifest mf = new Manifest(dpa); mf.add(new Manifest.ManifestEntry("a", "hash1", "image/jpeg", Manifest.Status.OK)); mf.add(new Manifest.ManifestEntry("ab", "hash2", "image/jpeg", Manifest.Status.OK)); System.out.println(mf.dump()); String hash = mf.save(); System.out.println("Hash: " + hash); System.out.println(dpa); Manifest mf1 = Manifest.loadManifest(dpa, hash); System.out.println(mf1.dump()); Manifest.ManifestEntry ab = mf1.get("ab"); System.out.println(ab); Manifest.ManifestEntry a = mf1.get("a"); System.out.println(a); System.out.println(mf1.dump()); } @Test public void readWriteReadTest() throws Exception { String testManiHash = dpa.store(Util.stringToReader(testManifest)).getHexString(); Manifest m = Manifest.loadManifest(dpa, testManiHash); System.out.println(m.dump()); String nHash = m.save(); Manifest m1 = Manifest.loadManifest(dpa, nHash); } }
2,426
31.797297
92
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/swarm/KademliaTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import org.ethereum.net.rlpx.Node; import org.ethereum.net.rlpx.discover.table.NodeTable; import org.junit.Ignore; import org.junit.Test; import java.util.*; /** * Created by Admin on 01.07.2015. */ public class KademliaTest { @Ignore @Test public void nodesConnectivityTest() { Map<Node, Integer> nameMap = new IdentityHashMap<>(); Node[] nodes = new Node[300]; NodeTable table = getTestNodeTable(); for (int i = 0; i < nodes.length; i++) { nodes[i] = getNode(1000 + i); table.addNode(nodes[i]); nameMap.put(nodes[i], i); } Map<Node, Set<Node>> reachable = new IdentityHashMap<>(); for (Node node : nodes) { Map<Node, Object> reachnodes = new IdentityHashMap<>(); reachable.put(node, reachnodes.keySet()); List<Node> closestNodes = table.getClosestNodes(node.getId()); int max = 16; for (Node closestNode : closestNodes) { reachnodes.put(closestNode, null); if (--max == 0) break; } } for (Node node : nodes) { System.out.println("Closing node " + nameMap.get(node)); Map<Node, Object> closure = new IdentityHashMap<>(); addAll(reachable, reachable.get(node), closure.keySet()); reachable.put(node, closure.keySet()); } for (Map.Entry<Node, Set<Node>> entry : reachable.entrySet()) { System.out.println("Node " + nameMap.get(entry.getKey()) + " has " + entry.getValue().size() + " neighbours"); // for (Node nb : entry.getValue()) { // System.out.println(" " + nameMap.get(nb)); // } } } static Random gen = new Random(0); public static byte[] getNodeId() { byte[] id = new byte[64]; gen.nextBytes(id); return id; } public static Node getNode(int port) { return new Node(getNodeId(), "127.0.0.1", port); } public static NodeTable getTestNodeTable() { NodeTable testTable = new NodeTable(getNode(3333)); return testTable; } private void addAll(Map<Node, Set<Node>> reachableMap, Set<Node> reachable, Set<Node> ret) { for (Node node : reachable) { if (!ret.contains(node)) { ret.add(node); addAll(reachableMap, reachableMap.get(node), ret); } } } }
3,312
32.806122
96
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/swarm/StringTrieTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import org.junit.*; import org.junit.Test; /** * Created by Admin on 11.06.2015. */ public class StringTrieTest { class A extends StringTrie.TrieNode<A> { String id; public A() { } public A(A parent, String relPath) { super(parent, relPath); } public void setId(String id) { this.id = id; } @Override protected A createNode(A parent, String path) { return new A(parent, path); } @Override public String toString() { return "A[" + (id != null ? id : "") + "]"; } } class T extends StringTrie<A> { public T() { super(new A()); } @Override public A add(String path) { A ret = super.add(path); ret.setId(path); return ret; } }; @Test public void testAdd() { T trie = new T(); trie.add("aaa"); trie.add("bbb"); trie.add("aad"); trie.add("aade"); trie.add("aadd"); System.out.println(Util.dumpTree(trie.rootNode)); Assert.assertEquals("aaa", trie.get("aaa").getAbsolutePath()); Assert.assertEquals("bbb", trie.get("bbb").getAbsolutePath()); Assert.assertEquals("aad", trie.get("aad").getAbsolutePath()); Assert.assertEquals("aa", trie.get("aaqqq").getAbsolutePath()); Assert.assertEquals("", trie.get("bbe").getAbsolutePath()); } @Test public void testAddRootLeaf() { T trie = new T(); trie.add("ax"); trie.add("ay"); trie.add("a"); System.out.println(Util.dumpTree(trie.rootNode)); } @Test public void testAddDuplicate() { T trie = new T(); A a = trie.add("a"); A ay = trie.add("ay"); A a1 = trie.add("a"); Assert.assertTrue(a == a1); A ay1 = trie.add("ay"); Assert.assertTrue(ay == ay1); } @Test public void testAddLeafRoot() { T trie = new T(); trie.add("a"); trie.add("ax"); System.out.println(Util.dumpTree(trie.rootNode)); } @Test public void testAddDelete() { T trie = new T(); trie.add("aaaa"); trie.add("aaaaxxxx"); trie.add("aaaaxxxxeeee"); System.out.println(Util.dumpTree(trie.rootNode)); trie.delete("aaaa"); System.out.println(Util.dumpTree(trie.rootNode)); trie.delete("aaaaxxxx"); System.out.println(Util.dumpTree(trie.rootNode)); } }
3,406
24.616541
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/swarm/SimpleDPA.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import io.netty.buffer.ByteBuf; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.UUID; /** * Created by Admin on 11.06.2015. */ public class SimpleDPA extends DPA { Random rnd = new Random(0); Map<Key, SectionReader> store = new HashMap<>(); public SimpleDPA() { super(null); } @Override public SectionReader retrieve(Key key) { return store.get(key); } @Override public Key store(SectionReader reader) { byte[] bb = new byte[16]; rnd.nextBytes(bb); Key key = new Key(bb); store.put(key, reader); return key; } @Override public String toString() { StringBuilder sb = new StringBuilder("SimpleDPA:\n"); for (Map.Entry<Key, SectionReader> entry : store.entrySet()) { sb.append(" ").append(entry.getKey()).append(": ") .append(Util.readerToString(entry.getValue())).append('\n'); } return sb.toString(); } }
1,894
28.153846
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/swarm/BzzProtocolTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import org.ethereum.net.rlpx.Node; import org.ethereum.net.swarm.bzz.BzzMessage; import org.ethereum.net.swarm.bzz.BzzProtocol; import org.ethereum.net.swarm.bzz.PeerAddress; import org.ethereum.util.ByteUtil; import org.ethereum.util.Utils; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.io.OutputStream; import java.io.PrintWriter; import java.util.*; import java.util.concurrent.*; import java.util.function.Consumer; import static org.ethereum.crypto.HashUtil.sha3; /** * Created by Admin on 24.06.2015. */ public class BzzProtocolTest { interface Predicate<T> { boolean test(T t);} public static class FilterPrinter extends PrintWriter { String filter; Predicate<String> pFilter; public FilterPrinter(OutputStream out) { super(out, true); } @Override public void println(String x) { if (pFilter == null || pFilter.test(x)) { // if (filter == null || x.contains(filter)) { super.println(x); } } public void setFilter(final String filter) { pFilter = s -> s.contains(filter); } public void setFilter(Predicate<String> pFilter) { this.pFilter = pFilter; } } static FilterPrinter stdout = new FilterPrinter(System.out); public static class TestPipe { protected Consumer<BzzMessage> out1; protected Consumer<BzzMessage> out2; protected String name1, name2; public TestPipe(Consumer<BzzMessage> out1, Consumer<BzzMessage> out2) { this.out1 = out1; this.out2 = out2; } protected TestPipe() { } Consumer<BzzMessage> createIn1() { return bzzMessage -> { BzzMessage smsg = serialize(bzzMessage); if (TestPeer.MessageOut) { stdout.println("+ " + name1 + " => " + name2 + ": " + smsg); } out2.accept(smsg); }; } Consumer<BzzMessage> createIn2() { return bzzMessage -> { BzzMessage smsg = serialize(bzzMessage); if (TestPeer.MessageOut) { stdout.println("+ " + name2 + " => " + name1 + ": " + smsg); } out1.accept(smsg); }; } public void setNames(String name1, String name2) { this.name1 = name1; this.name2 = name2; } private BzzMessage serialize(BzzMessage msg) { try { return msg.getClass().getConstructor(byte[].class).newInstance(msg.getEncoded()); } catch (Exception e) { throw new RuntimeException(e); } } public Consumer<BzzMessage> getOut1() { return out1; } public Consumer<BzzMessage> getOut2() { return out2; } } public static class TestAsyncPipe extends TestPipe { static ScheduledExecutorService exec = Executors.newScheduledThreadPool(32); static Queue<Future<?>> tasks = new LinkedBlockingQueue<>(); class AsyncConsumer implements Consumer<BzzMessage> { Consumer<BzzMessage> delegate; boolean rev; public AsyncConsumer(Consumer<BzzMessage> delegate, boolean rev) { this.delegate = delegate; this.rev = rev; } @Override public void accept(final BzzMessage bzzMessage) { ScheduledFuture<?> future = exec.schedule(() -> { try { if (!rev) { if (TestPeer.MessageOut) { stdout.println("- " + name1 + " => " + name2 + ": " + bzzMessage); } } else { if (TestPeer.MessageOut) { stdout.println("- " + name2 + " => " + name1 + ": " + bzzMessage); } } delegate.accept(bzzMessage); } catch (Exception e) { e.printStackTrace(); } }, channelLatencyMs, TimeUnit.MILLISECONDS); tasks.add(future); } } long channelLatencyMs = 2; public static void waitForCompletion() { try { while(!tasks.isEmpty()) { tasks.poll().get(); } } catch (Exception e) { throw new RuntimeException(e); } } public TestAsyncPipe(Consumer<BzzMessage> out1, Consumer<BzzMessage> out2) { this.out1 = new AsyncConsumer(out1, false); this.out2 = new AsyncConsumer(out2, true); } } public static class SimpleHive extends Hive { Map<BzzProtocol, Object> peers = new IdentityHashMap<>(); // PeerAddress thisAddress; TestPeer thisPeer; // NodeTable nodeTable; public SimpleHive(PeerAddress thisAddress) { super(thisAddress); // this.thisAddress = thisAddress; // nodeTable = new NodeTable(thisAddress.toNode()); } public SimpleHive setThisPeer(TestPeer thisPeer) { this.thisPeer = thisPeer; return this; } @Override public void addPeer(BzzProtocol peer) { peers.put(peer, null); super.addPeer(peer); // nodeTable.addNode(peer.getNode().toNode()); // peersAdded(); } // @Override // public void removePeer(BzzProtocol peer) { // peers.remove(peer); // nodeTable.dropNode(peer.getNode().toNode()); // } // // @Override // public void addPeerRecords(BzzPeersMessage req) { // for (PeerAddress peerAddress : req.getPeers()) { // nodeTable.addNode(peerAddress.toNode()); // } // peersAdded(); // } @Override public Collection<PeerAddress> getNodes(Key key, int max) { List<Node> closestNodes = nodeTable.getClosestNodes(key.getBytes()); ArrayList<PeerAddress> ret = new ArrayList<>(); for (Node node : closestNodes) { ret.add(new PeerAddress(node)); if (--max == 0) break; } return ret; } @Override public Collection<BzzProtocol> getPeers(Key key, int maxCount) { if (thisPeer == null) return peers.keySet(); // TreeMap<Key, TestPeer> sort = new TreeMap<>((o1, o2) -> { // for (int i = 0; i < o1.getBytes().length; i++) { // if (o1.getBytes()[i] > o2.getBytes()[i]) return 1; // if (o1.getBytes()[i] < o2.getBytes()[i]) return -1; // } // return 0; // }); // for (TestPeer testPeer : TestPeer.staticMap.values()) { // if (thisPeer != testPeer) { // sort.put(distance(key, new Key(testPeer.peerAddress.getId())), testPeer); // } // } List<Node> closestNodes = nodeTable.getClosestNodes(key.getBytes()); ArrayList<BzzProtocol> ret = new ArrayList<>(); for (Node node : closestNodes) { ret.add(thisPeer.getPeer(new PeerAddress(node))); if (--maxCount == 0) break; } return ret; } } public static class TestPeer { static Map<PeerAddress, TestPeer> staticMap = Collections.synchronizedMap(new HashMap<PeerAddress, TestPeer>()); public static boolean MessageOut = false; public static boolean AsyncPipe = false; String name; PeerAddress peerAddress; LocalStore localStore; Hive hive; NetStore netStore; Map<Key, BzzProtocol> connections = new HashMap<>(); public TestPeer(int num) { this(new PeerAddress(new byte[]{0, 0, (byte) ((num >> 8) & 0xFF), (byte) (num & 0xFF)}, 1000 + num, sha3(new byte[]{(byte) ((num >> 8) & 0xFF), (byte) (num & 0xFF)})), "" + num); } public TestPeer(PeerAddress peerAddress, String name) { this.name = name; this.peerAddress = peerAddress; localStore = new LocalStore(new MemStore(), new MemStore()); hive = new SimpleHive(peerAddress).setThisPeer(this); netStore = new NetStore(localStore, hive); netStore.start(peerAddress); staticMap.put(peerAddress, this); } public BzzProtocol getPeer(PeerAddress addr) { Key peerKey = new Key(addr.getId()); BzzProtocol protocol = connections.get(peerKey); if (protocol == null) { connect(staticMap.get(addr)); protocol = connections.get(peerKey); } return protocol; } private BzzProtocol createPeerProtocol(PeerAddress addr) { Key peerKey = new Key(addr.getId()); BzzProtocol protocol = connections.get(peerKey); if (protocol == null) { protocol = new BzzProtocol(netStore); connections.put(peerKey, protocol); } return protocol; } public void connect(TestPeer peer) { BzzProtocol myBzz = this.createPeerProtocol(peer.peerAddress); BzzProtocol peerBzz = peer.createPeerProtocol(peerAddress); TestPipe pipe = AsyncPipe ? new TestAsyncPipe(myBzz, peerBzz) : new TestPipe(myBzz, peerBzz); pipe.setNames(this.name, peer.name); System.out.println("Connecting: " + this.name + " <=> " + peer.name); myBzz.setMessageSender(pipe.createIn1()); peerBzz.setMessageSender(pipe.createIn2()); myBzz.start(); peerBzz.start(); } public void connect(PeerAddress addr) { TestPeer peer = staticMap.get(addr); if (peer != null) { connect(peer); } } } @Test public void simple3PeersTest() throws Exception { TestPeer.MessageOut = true; TestPeer.AsyncPipe = true; TestPeer p1 = new TestPeer(1); TestPeer p2 = new TestPeer(2); TestPeer p3 = new TestPeer(3); // TestPeer p4 = new TestPeer(4); System.out.println("Put chunk to 1"); Key key = new Key(new byte[]{0x22, 0x33}); Chunk chunk = new Chunk(key, new byte[] {0,0,0,0,0,0,0,0, 77, 88}); p1.netStore.put(chunk); System.out.println("Connect 1 <=> 2"); p1.connect(p2); System.out.println("Connect 2 <=> 3"); p2.connect(p3); // p2.connect(p4); // Thread.sleep(3000); System.err.println("Requesting chunk from 3..."); Chunk chunk1 = p3.netStore.get(key); Assert.assertEquals(key, chunk1.getKey()); Assert.assertArrayEquals(chunk.getData(), chunk1.getData()); } private String dumpPeers(TestPeer[] allPeers, Key key) { String s = "Name\tChunks\tPeers\tMsgIn\tMsgOut\n"; for (TestPeer peer : allPeers) { s += (peer.name + "\t" + (int)((Statter.SimpleStatter)((MemStore) peer.localStore.memStore).statCurChunks).getLast() + "\t" + ((Statter.SimpleStatter)(peer.netStore.statHandshakes)).getCount() + "\t" + ((Statter.SimpleStatter)(peer.netStore.statInMsg)).getCount() + "\t" + ((Statter.SimpleStatter)(peer.netStore.statOutMsg)).getCount()) + "\t" + (key != null ? ", keyDist: " + hex(getDistance(peer.peerAddress.getId(), key.getBytes())) : "") +"\n"; s += " Chunks:\n"; for (Key k : ((MemStore) peer.localStore.memStore).store.keySet()) { s += (" " + k.toString().substring(0,8) + ", dist: " + hex(getDistance(peer.peerAddress.getId(), k.getBytes()))) + "\n"; } s += " Nodes:\n"; Map<Node, BzzProtocol> entries = peer.hive.getAllEntries(); SortedMap<Long, Node> sort = new TreeMap<>(); for (Node node : entries.keySet()) { int dist = getDistance(node.getId(), key.getBytes()); sort.put(0xFFFFFFFFl & dist, node); } for (Node node : sort.values()) { s += " " + (entries.get(node) == null ? " " : "*") + " " + node.getHost() + ", dist: " + hex(getDistance(peer.peerAddress.getId(), node.getId())) + (key != null ? ", keyDist: " + hex(getDistance(node.getId(), key.getBytes())) : "") + "\n"; } } return s; } private String hex(int i ) { return "0x" + Utils.align(Integer.toHexString(i), '0', 8, true); } private int getDistance(byte[] k1, byte[] k2) { int i1 = ByteUtil.byteArrayToInt(Arrays.copyOfRange(k1, 0, 4)); int i2 = ByteUtil.byteArrayToInt(Arrays.copyOfRange(k2, 0, 4)); return i1 ^ i2; } @Ignore @Test public void manyPeersTest() throws InterruptedException { TestPeer.AsyncPipe = true; // TestPeer.MessageOut = true; final int maxStoreCount = 3; TestPeer p0 = new TestPeer(0); p0.netStore.maxStorePeers = maxStoreCount; System.out.println("Creating chain of peers"); final TestPeer[] allPeers = new TestPeer[100]; allPeers[0] = p0; for (int i = 1; i < allPeers.length; i++) { allPeers[i] = new TestPeer(i); allPeers[i].netStore.maxStorePeers = maxStoreCount; // System.out.println("Connecting " + i + " <=> " + (i-1)); allPeers[i].connect(allPeers[i-1]); // System.out.println("Connecting " + i + " <=> " + (0)); // allPeers[i].connect(p0); } // p0.netStore.put(chunk); System.out.println("Waiting for net idle "); TestAsyncPipe.waitForCompletion(); TestPeer.MessageOut = true; stdout.setFilter(s -> s.startsWith("+") && s.contains("BzzStoreReqMessage")); // System.out.println("==== Storage statistics:\n" + dumpPeers(allPeers, null)); // System.out.println("Sleeping..."); // System.out.println("Connecting a new peer..."); // allPeers[allPeers.length-1].connect(new TestPeer(allPeers.length)); // Thread.sleep(10000000); System.out.println("Put chunk to 0"); // Key key = new Key(new byte[]{0x22, 0x33}); // Chunk chunk = new Chunk(key, new byte[] {0,0,0,0,0,0,0,0, 77, 88}); Chunk[] chunks = new Chunk[10]; int shift = 1; for (int i = 0; i < chunks.length; i++) { Key key = new Key(sha3(new byte[]{0x22, (byte) (i+shift)})); // stdout.setFilter(Hex.toHexString(key.getBytes())); chunks[i] = new Chunk(key, new byte[] {0,0,0,0,0,0,0,0, 77, (byte) i}); System.out.println("==== Storage statistics before:\n" + dumpPeers(allPeers, key)); System.out.println("Putting chunk" + i); p0.netStore.put(chunks[i]); TestAsyncPipe.waitForCompletion(); System.out.println("==== Storage statistics after:\n" + dumpPeers(allPeers, key)); } System.out.println("Waiting for net idle "); TestAsyncPipe.waitForCompletion(); TestPeer.MessageOut = true; System.out.println("==== Storage statistics:"); System.out.println("Name\tChunks\tPeers\tMsgIn\tMsgOut"); for (TestPeer peer : allPeers) { System.out.println(peer.name + "\t" + (int)((Statter.SimpleStatter)((MemStore) peer.localStore.memStore).statCurChunks).getLast() + "\t" + ((Statter.SimpleStatter)(peer.netStore.statHandshakes)).getCount() + "\t" + ((Statter.SimpleStatter)(peer.netStore.statInMsg)).getCount() + "\t" + ((Statter.SimpleStatter)(peer.netStore.statOutMsg)).getCount()); for (Key key : ((MemStore) peer.localStore.memStore).store.keySet()) { System.out.println(" " + key); } } // TestPeer.MessageOut = true; System.out.println("Requesting chunk from the last..."); for (int i = 0; i < chunks.length; i++) { Key key = new Key(sha3(new byte[]{0x22, (byte) (i+shift)})); System.out.println("======== Looking for " + key); Chunk chunk1 = allPeers[allPeers.length - 1].netStore.get(key); System.out.println("########### Found: " + chunk1); Assert.assertEquals(key, chunk1.getKey()); Assert.assertArrayEquals(chunks[i].getData(), chunk1.getData()); } System.out.println("All found!"); System.out.println("==== Storage statistics:"); System.out.println("Name\tChunks\tPeers\tMsgIn\tMsgOut"); for (TestPeer peer : allPeers) { System.out.println(peer.name + "\t" + (int)((Statter.SimpleStatter)((MemStore) peer.localStore.memStore).statCurChunks).getLast() + "\t" + ((Statter.SimpleStatter)(peer.netStore.statHandshakes)).getCount() + "\t" + ((Statter.SimpleStatter)(peer.netStore.statInMsg)).getCount() + "\t" + ((Statter.SimpleStatter)(peer.netStore.statOutMsg)).getCount()); // for (Key key : ((MemStore) peer.localStore.memStore).store.keySet()) { // System.out.println(" " + key); // } } } @Ignore // OutOfMemory @Test public void manyPeersLargeDataTest() { TestPeer.AsyncPipe = true; // TestPeer.MessageOut = true; TestPeer p0 = new TestPeer(0); System.out.println("Creating chain of peers"); TestPeer[] allPeers = new TestPeer[100]; allPeers[0] = p0; for (int i = 1; i < allPeers.length; i++) { allPeers[i] = new TestPeer(i); System.out.println("Connecting " + i + " <=> " + (i-1)); allPeers[i].connect(allPeers[i-1]); } TreeChunker chunker = new TreeChunker(); int chunks = 100; byte[] data = new byte[(int) (chunks * chunker.getChunkSize())]; for (int i = 0; i < chunks; i++) { for (int idx = (int) (i * chunker.getChunkSize()); idx < (i+1) * chunker.getChunkSize(); idx++) { data[idx] = (byte) (i + 1); } } System.out.println("Split and put data to node 0..."); Key key = chunker.split(new Util.ArrayReader(data), new Util.ChunkConsumer(p0.netStore)); System.out.println("Assemble data back from the last node ..."); SectionReader reader = chunker.join(allPeers[allPeers.length - 1].netStore, key); Assert.assertEquals(data.length, reader.getSize()); byte[] data1 = new byte[(int) reader.getSize()]; reader.read(data1, 0); for (int i = 0; i < data.length; i++) { if (data[i] != data1[i]) { System.out.println("Not equal at index " + i); } Assert.assertEquals(data[i], data1[i]); } System.out.println("==== Storage statistics:"); System.out.println("Name\tChunks\tPeers\tMsgIn\tMsgOut"); for (TestPeer peer : allPeers) { System.out.println(peer.name + "\t" + (int)((Statter.SimpleStatter)((MemStore) peer.localStore.memStore).statCurChunks).getLast() + "\t" + ((Statter.SimpleStatter)(peer.netStore.statHandshakes)).getCount() + "\t" + ((Statter.SimpleStatter)(peer.netStore.statInMsg)).getCount() + "\t" + ((Statter.SimpleStatter)(peer.netStore.statOutMsg)).getCount()); } } @Test public void simpleTest() { PeerAddress peerAddress1 = new PeerAddress(new byte[] {0,0,0,1}, 1001, new byte[] {1}); PeerAddress peerAddress2 = new PeerAddress(new byte[] {0,0,0,2}, 1002, new byte[] {2}); LocalStore localStore1 = new LocalStore(new MemStore(), new MemStore()); LocalStore localStore2 = new LocalStore(new MemStore(), new MemStore()); Hive hive1 = new SimpleHive(peerAddress1); Hive hive2 = new SimpleHive(peerAddress2); NetStore netStore1 = new NetStore(localStore1, hive1); NetStore netStore2 = new NetStore(localStore2, hive2); netStore1.start(peerAddress1); netStore2.start(peerAddress2); BzzProtocol bzz1 = new BzzProtocol(netStore1); BzzProtocol bzz2 = new BzzProtocol(netStore2); TestPipe pipe = new TestPipe(bzz1, bzz2); pipe.setNames("1", "2"); bzz1.setMessageSender(pipe.createIn1()); bzz2.setMessageSender(pipe.createIn2()); bzz1.start(); bzz2.start(); Key key = new Key(new byte[]{0x22, 0x33}); Chunk chunk = new Chunk(key, new byte[] {0,0,0,0,0,0,0,0, 77, 88}); netStore1.put(chunk); // netStore1.put(chunk); localStore1.clean(); Chunk chunk1 = netStore1.get(key); Assert.assertEquals(key, chunk1.getKey()); Assert.assertArrayEquals(chunk.getData(), chunk1.getData()); } }
22,426
37.011864
122
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/swarm/ChunkerTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Random; import static java.lang.Math.min; /** * Created by Admin on 19.06.2015. */ public class ChunkerTest { public static class SimpleChunkStore implements ChunkStore { Map<Key, byte[]> map = new HashMap<>(); @Override public void put(Chunk chunk) { map.put(chunk.getKey(), chunk.getData()); } @Override public Chunk get(Key key) { byte[] bytes = map.get(key); return bytes == null ? null : new Chunk(key, bytes); } } @Test public void simpleTest() { byte[] arr = new byte[200]; new Random(0).nextBytes(arr); Util.ArrayReader r = new Util.ArrayReader(arr); TreeChunker tc = new TreeChunker(4, TreeChunker.DEFAULT_HASHER); ArrayList<Chunk> l = new ArrayList<>(); Key root = tc.split(r, l); SimpleChunkStore chunkStore = new SimpleChunkStore(); for (Chunk chunk : l) { chunkStore.put(chunk); } SectionReader reader = tc.join(chunkStore, root); long size = reader.getSize(); int off = 30; byte[] arrOut = new byte[(int) size]; int readLen = reader.read(arrOut, off); System.out.println("Read len: " + readLen); for (int i = 0; i < arr.length && off + i < arrOut.length; i++) { if (arr[i] != arrOut[off+ i]) throw new RuntimeException("Not equal at " + i); } System.out.println("Done."); } }
2,419
31.702703
90
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/swarm/GoPeerTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.swarm; import org.ethereum.Start; import org.junit.Ignore; import org.junit.Test; import static org.ethereum.crypto.HashUtil.sha3; /** * Created by Admin on 06.07.2015. */ public class GoPeerTest { @Ignore @Test // TODO to be done at some point: run Go peer and connect to it public void putTest() throws Exception { System.out.println("Starting Java peer..."); Start.main(new String[]{}); System.out.println("Warming up..."); Thread.sleep(5000); System.out.println("Sending a chunk..."); Key key = new Key(sha3(new byte[]{0x22, 0x33})); // stdout.setFilter(Hex.toHexString(key.getBytes())); Chunk chunk = new Chunk(key, new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 77, 88}); NetStore.getInstance().put(chunk); } }
1,623
32.833333
81
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/shh/FilterTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.shh; import org.ethereum.crypto.ECKey; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class FilterTest { String to = WhisperImpl.toIdentity(new ECKey()); String from = WhisperImpl.toIdentity(new ECKey()); String[] topics = {"topic1", "topic2", "topic3", "topic4"}; class FilterStub extends MessageWatcher { public FilterStub() { } public FilterStub(String to, String from, Topic[] filterTopics) { super(to, from, filterTopics); } @Override protected void newMessage(WhisperMessage msg) { } } @Test public void test1() { MessageWatcher matcher = new FilterStub(); assertTrue(matcher.match(to, from, Topic.createTopics(topics))); } @Test public void test2() { MessageWatcher matcher = new FilterStub().setTo(to); assertTrue(matcher.match(to, from, Topic.createTopics(topics))); } @Test public void test3() { MessageWatcher matcher = new FilterStub().setTo(to); assertFalse(matcher.match(null, from, Topic.createTopics(topics))); } @Test public void test4() { MessageWatcher matcher = new FilterStub().setFrom(from); assertTrue(matcher.match(null, from, Topic.createTopics(topics))); } @Test public void test5() { MessageWatcher matcher = new FilterStub().setFrom(from); assertTrue(!matcher.match(to, null, Topic.createTopics(topics))); } @Test public void test6() { MessageWatcher matcher = new FilterStub(null, from, Topic.createTopics(topics)); assertTrue(matcher.match(to, from, Topic.createTopics(topics))); } @Test public void test7() { MessageWatcher matcher = new FilterStub(null, null, Topic.createTopics(topics)); assertTrue(!matcher.match(to, from, Topic.createTopics(new String[]{}))); } }
2,788
30.693182
89
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/shh/ShhTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.shh; import org.junit.Assert; import org.ethereum.crypto.ECKey; import org.ethereum.util.RLP; import org.ethereum.util.RLPList; import org.junit.Test; import java.math.BigInteger; import org.spongycastle.util.encoders.Hex; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; /** * @author by Konstantin Shabalin */ public class ShhTest { /* private byte[] payload = "Hello whisper!".getBytes(); private ECKey privKey = ECKey.fromPrivate(BigInteger.TEN); private byte[] pubKey = privKey.getPubKey(); private int ttl = 10000; private Topic[] topics = new Topic[]{ new Topic("topic 1"), new Topic("topic 2"), new Topic("topic 3")}; @Test */ /* Tests whether a message can be wrapped without any identity or encryption. *//* public void test1() { WhisperMessage sent = new WhisperMessage(payload); Options options = new Options(null, null, topics, ttl); ShhEnvelopeMessage e = sent.wrap(Options.DEFAULT_POW, options); RLPList rlpList = RLP.decode2(e.getEncoded()); RLPList.recursivePrint(rlpList); System.out.println(); assertEquals(Hex.toHexString(e.getData()), Hex.toHexString(sent.getBytes())); assertEquals(Hex.toHexString(sent.getPayload()), Hex.toHexString(payload)); assertTrue(sent.getSignature() == null); WhisperMessage received = e.open(null); ECKey recovered = received.recover(); assertTrue(recovered == null); } @Test */ /* Tests whether a message can be signed, and wrapped in plain-text. *//* public void test2() { WhisperMessage sent = new WhisperMessage(payload); Options options = new Options(privKey, null, topics, ttl); ShhEnvelopeMessage e = sent.wrap(Options.DEFAULT_POW, options); assertEquals(Hex.toHexString(e.getData()), Hex.toHexString(sent.getBytes())); assertEquals(Hex.toHexString(sent.getPayload()), Hex.toHexString(payload)); assertTrue(sent.getSignature() != null); WhisperMessage received = e.open(null); ECKey recovered = received.recover(); assertEquals(Hex.toHexString(pubKey), Hex.toHexString(recovered.getPubKey())); } @Test */ /* Tests whether a message can be encrypted and decrypted using an anonymous sender (i.e. no signature).*//* public void test3() { WhisperMessage sent = new WhisperMessage(payload); Options options = new Options(null, pubKey, topics, ttl); ShhEnvelopeMessage e = sent.wrap(Options.DEFAULT_POW, options); assertEquals(Hex.toHexString(e.getData()), Hex.toHexString(sent.getBytes())); assertNotEquals(Hex.toHexString(sent.getPayload()), Hex.toHexString(payload)); assertTrue(sent.getSignature() == null); WhisperMessage received = e.open(null); assertEquals(Hex.toHexString(sent.getBytes()), Hex.toHexString(received.getBytes())); ECKey recovered = received.recover(); assertTrue(recovered == null); } @Test */ /* Tests whether a message can be properly signed and encrypted. *//* public void test4() { WhisperMessage sent = new WhisperMessage(payload); Options options = new Options(privKey, pubKey, topics, ttl); ShhEnvelopeMessage e = sent.wrap(Options.DEFAULT_POW, options); assertEquals(Hex.toHexString(e.getData()), Hex.toHexString(sent.getBytes())); assertNotEquals(Hex.toHexString(sent.getPayload()), Hex.toHexString(payload)); assertTrue(sent.getSignature() != null); WhisperMessage received = e.open(privKey); ECKey recovered = received.recover(); sent.decrypt(privKey); assertEquals(Hex.toHexString(sent.getBytes()), Hex.toHexString(received.getBytes())); assertEquals(Hex.toHexString(sent.getPayload()), Hex.toHexString(payload)); assertEquals(Hex.toHexString(pubKey), Hex.toHexString(recovered.getPubKey())); } @Test public void test5() { ECKey fromKey = ECKey.fromPrivate(Hex.decode("ba43d10d069f0c41a8914849c1abeeac2a681b21ae9b60a6a2362c06e6eb1bc8")); ECKey toKey = ECKey.fromPrivate(Hex.decode("00000000069f0c41a8914849c1abeeac2a681b21ae9b60a6a2362c06e6eb1bc8")); // System.out.println("Sending from: " + Hex.toHexString(fromKey.getPubKey()) + "\n to: " + Hex.toHexString(toKey.getPubKey())); byte[] bytes = post(fromKey, Hex.toHexString(toKey.getPubKey()), new String[]{"myTopic"}, "Hello all!", 1, 1); ShhEnvelopeMessage envelope = new ShhEnvelopeMessage(bytes); WhisperMessage msg = envelope.open(toKey); // System.out.println("Received: " + envelope + "\n " + msg); assertEquals("Hello all!", new String(msg.getPayload())); } public byte[] post(ECKey fromKey, String to, String[] topics, String payload, int ttl, int pow) { Topic[] topicList = Topic.createTopics(topics); WhisperMessage m = new WhisperMessage(payload.getBytes()); Options options = new Options( fromKey, to == null ? null : Hex.decode(to), topicList, ttl ); ShhEnvelopeMessage e = m.wrap(pow, options); return e.getEncoded(); } */ }
6,161
37.273292
135
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/shh/TopicTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.shh; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import static org.junit.Assert.assertEquals; public class TopicTest { @Test public void test1(){ Topic topic = new Topic("cow"); assertEquals("91887637", Hex.toHexString(topic.getBytes())); } @Test public void test2(){ Topic topic = new Topic("cowcowcow"); assertEquals("3a6de614", Hex.toHexString(topic.getBytes())); } }
1,270
30.775
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/shh/BloomFilterTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.shh; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.assertTrue; /** * Created by Anton Nashatyrev on 24.09.2015. */ public class BloomFilterTest { private static final Logger logger = LoggerFactory.getLogger("test"); @Test public void test1() { BloomFilter filter = BloomFilter.createNone(); for (int i = 0; i < 100; i++) { filter.addTopic(new Topic("Topic" + i)); } for (int i = 0; i < 100; i++) { assertTrue("Topic #" + i, filter.hasTopic(new Topic("Topic" + i))); } int falsePositiveCnt = 0; for (int i = 0; i < 10000; i++) { falsePositiveCnt += filter.hasTopic(new Topic("Topic_" + i)) ? 1 : 0; } logger.info("falsePositiveCnt: " + falsePositiveCnt); assertTrue(falsePositiveCnt < 1000); // false positive probability ~8.7% } }
1,752
32.711538
81
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/shh/ShhLongRun.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.shh; import org.apache.commons.lang3.tuple.Pair; import org.ethereum.config.NoAutoscan; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.manager.WorldManager; import org.ethereum.net.p2p.HelloMessage; import org.ethereum.net.rlpx.Node; import org.ethereum.net.server.Channel; import org.junit.Ignore; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; /** * This is not a JUnit test but rather a long running standalone test for messages exchange with another peer. * To start it another peer with JSON PRC API should be started. * E.g. the following is the cmd for starting up C++ eth: * * > eth --no-bootstrap --no-discovery --listen 10003 --shh --json-rpc * * If the eth is running on a remote host:port the appropriate constants in the test need to be updated * * Created by Anton Nashatyrev on 05.10.2015. */ @Ignore public class ShhLongRun extends Thread { private static URL remoteJsonRpc; @Test public void test() throws Exception { // remoteJsonRpc = new URL("http://whisper-1.ether.camp:8545"); // Node node = new Node("enode://52994910050f13cbd7848f02709f2f5ebccc363f13dafc4ec201e405e2f143ebc9c440935b3217073f6ec47f613220e0bc6b7b34274b7d2de125b82a2acd34ee" + // "@whisper-1.ether.camp:30303"); remoteJsonRpc = new URL("http://localhost:8545"); Node node = new Node("enode://6ed738b650ac2b771838506172447dc683b7e9dae7b91d699a48a0f94651b1a0d2e2ef01c6fffa22f762aaa553286047f0b0bb39f2e3a24b2a18fe1b9637dcbe" + "@localhost:10003"); Ethereum ethereum = EthereumFactory.createEthereum(Config.class); ethereum.connect( node.getHost(), node.getPort(), Hex.toHexString(node.getId())); Thread.sleep(1000000000); } public static void main(String[] args) throws Exception { new ShhLongRun().test(); } @Configuration @NoAutoscan public static class Config { @Bean public TestComponent testBean() { return new TestComponent(); } } @Component @NoAutoscan public static class TestComponent extends Thread { @Autowired WorldManager worldManager; @Autowired Ethereum ethereum; @Autowired Whisper whisper; Whisper remoteWhisper; public TestComponent() { } @PostConstruct void init() { System.out.println("========= init"); worldManager.addListener(new EthereumListenerAdapter() { @Override public void onHandShakePeer(Channel channel, HelloMessage helloMessage) { System.out.println("========= onHandShakePeer"); if (!isAlive()) { start(); } } }); } static class MessageMatcher extends MessageWatcher { List<Pair<Date, WhisperMessage>> awaitedMsgs = new ArrayList<>(); public MessageMatcher(String to, String from, Topic[] topics) { super(to, from, topics); } @Override protected synchronized void newMessage(WhisperMessage msg) { System.out.println("=== Msg received: " + msg); for (Pair<Date, WhisperMessage> awaitedMsg : awaitedMsgs) { if (Arrays.equals(msg.getPayload(), awaitedMsg.getRight().getPayload())) { if (!match(msg, awaitedMsg.getRight())) { throw new RuntimeException("Messages not matched: \n" + awaitedMsg + "\n" + msg); } else { awaitedMsgs.remove(awaitedMsg); break; } } } checkForMissingMessages(); } private boolean equal(Object o1, Object o2) { if (o1 == null) return o2 == null; return o1.equals(o2); } protected boolean match(WhisperMessage m1, WhisperMessage m2) { if (!Arrays.equals(m1.getPayload(), m2.getPayload())) return false; if (!equal(m1.getFrom(), m2.getFrom())) return false; if (!equal(m1.getTo(), m2.getTo())) return false; if (m1.getTopics() != null) { if (m1.getTopics().length != m2.getTopics().length) return false; for (int i = 0; i < m1.getTopics().length; i++) { if (!m1.getTopics()[i].equals(m2.getTopics()[i])) return false; } } else if (m2.getTopics() != null) return false; return true; } public synchronized void waitForMessage(WhisperMessage msg) { checkForMissingMessages(); awaitedMsgs.add(Pair.of(new Date(), msg)); } private void checkForMissingMessages() { for (Pair<Date, WhisperMessage> msg : awaitedMsgs) { if (System.currentTimeMillis() > msg.getLeft().getTime() + 10 * 1000) { throw new RuntimeException("Message was not delivered: " + msg); } } } } @Override public void run() { try { remoteWhisper = new JsonRpcWhisper(remoteJsonRpc); Whisper whisper = this.whisper; // Whisper whisper = new JsonRpcWhisper(remoteJsonRpc1); System.out.println("========= Waiting for SHH init"); Thread.sleep(1 * 1000); System.out.println("========= Running"); String localKey1 = whisper.newIdentity(); String localKey2 = whisper.newIdentity(); String remoteKey1 = remoteWhisper.newIdentity(); String remoteKey2 = remoteWhisper.newIdentity(); String localTopic = "LocalTopic"; String remoteTopic = "RemoteTopic"; MessageMatcher localMatcherBroad = new MessageMatcher(null, null, Topic.createTopics(remoteTopic)); MessageMatcher remoteMatcherBroad = new MessageMatcher(null, null, Topic.createTopics(localTopic)); MessageMatcher localMatcherTo = new MessageMatcher(localKey1, null, null); MessageMatcher localMatcherToFrom = new MessageMatcher(localKey2, remoteKey2, null); MessageMatcher remoteMatcherTo = new MessageMatcher(remoteKey1, null, Topic.createTopics("aaa")); MessageMatcher remoteMatcherToFrom = new MessageMatcher(remoteKey2, localKey2, Topic.createTopics("aaa")); whisper.watch(localMatcherBroad); whisper.watch(localMatcherTo); whisper.watch(localMatcherToFrom); remoteWhisper.watch(remoteMatcherBroad); remoteWhisper.watch(remoteMatcherTo); remoteWhisper.watch(remoteMatcherToFrom); int cnt = 0; while (true) { { WhisperMessage msg = new WhisperMessage() .setPayload("local-" + cnt) .setTopics(Topic.createTopics(localTopic)); remoteMatcherBroad.waitForMessage(msg); whisper.send(msg.getPayload(), msg.getTopics()); } { WhisperMessage msg = new WhisperMessage() .setPayload("remote-" + cnt) .setTopics(Topic.createTopics(remoteTopic)); localMatcherBroad.waitForMessage(msg); remoteWhisper.send(msg.getPayload(), msg.getTopics()); } { WhisperMessage msg = new WhisperMessage() .setPayload("local-to-" + cnt) .setTo(remoteKey1) .setTopics(Topic.createTopics("aaa")); remoteMatcherTo.waitForMessage(msg); whisper.send(msg.getTo(), msg.getPayload(), msg.getTopics()); } { WhisperMessage msg = new WhisperMessage() .setPayload("remote-to-" + cnt) .setTo(localKey1); localMatcherTo.waitForMessage(msg); remoteWhisper.send(msg.getTo(), msg.getPayload(), Topic.createTopics()); } { WhisperMessage msg = new WhisperMessage() .setPayload("local-to-from-" + cnt) .setTo(remoteKey2) .setFrom(localKey2) .setTopics(Topic.createTopics("aaa")); remoteMatcherToFrom.waitForMessage(msg); whisper.send(msg.getFrom(), msg.getTo(), msg.getPayload(), msg.getTopics()); } { WhisperMessage msg = new WhisperMessage() .setPayload("remote-to-from-" + cnt) .setTo(localKey2) .setFrom(remoteKey2); localMatcherToFrom.waitForMessage(msg); remoteWhisper.send(msg.getFrom(), msg.getTo(), msg.getPayload(), msg.getTopics()); } Thread.sleep(1000); cnt++; } } catch (Exception e) { e.printStackTrace(); } } } }
11,235
40.157509
171
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/shh/EnvelopeTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.shh; import org.ethereum.crypto.ECIESCoder; import org.ethereum.crypto.ECKey; import org.ethereum.util.RLP; import org.ethereum.util.RLPDump; import org.ethereum.util.RLPTest; import org.junit.Assert; import org.junit.Test; import org.spongycastle.crypto.InvalidCipherTextException; import org.spongycastle.util.encoders.Hex; import java.io.IOException; import java.util.Arrays; import java.util.Collections; /** * Created by Anton Nashatyrev on 25.09.2015. */ public class EnvelopeTest { @Test public void testBroadcast1() { WhisperMessage msg1 = new WhisperMessage() .setTopics(Topic.createTopics("Topic1", "Topic2")) .setPayload("Hello"); WhisperMessage msg2 = new WhisperMessage() .setTopics(Topic.createTopics("Topic1", "Topic3")) .setPayload("Hello again"); ShhEnvelopeMessage envelope = new ShhEnvelopeMessage(msg1, msg2); byte[] bytes = envelope.getEncoded(); ShhEnvelopeMessage inbound = new ShhEnvelopeMessage(bytes); Assert.assertEquals(2, inbound.getMessages().size()); WhisperMessage inMsg1 = inbound.getMessages().get(0); boolean b = inMsg1.decrypt(Collections.EMPTY_LIST, Arrays.asList(Topic.createTopics("Topic2", "Topic3"))); Assert.assertTrue(b); Assert.assertEquals("Hello", new String(inMsg1.getPayload())); WhisperMessage inMsg2 = inbound.getMessages().get(1); b = inMsg2.decrypt(Collections.EMPTY_LIST, Arrays.asList(Topic.createTopics("Topic1", "Topic3"))); Assert.assertTrue(b); Assert.assertEquals("Hello again", new String(inMsg2.getPayload())); } @Test public void testPow1() { ECKey from = new ECKey(); ECKey to = new ECKey(); System.out.println("From: " + Hex.toHexString(from.getPrivKeyBytes())); System.out.println("To: " + Hex.toHexString(to.getPrivKeyBytes())); WhisperMessage msg1 = new WhisperMessage() .setTopics(Topic.createTopics("Topic1", "Topic2")) .setPayload("Hello") .setFrom(from) .setTo(WhisperImpl.toIdentity(to)) .setWorkToProve(1000); WhisperMessage msg2 = new WhisperMessage() .setTopics(Topic.createTopics("Topic1", "Topic3")) .setPayload("Hello again") .setWorkToProve(500); ShhEnvelopeMessage envelope = new ShhEnvelopeMessage(msg1, msg2); byte[] bytes = envelope.getEncoded(); // System.out.println(RLPTest.dump(RLP.decode2(bytes), 0)); ShhEnvelopeMessage inbound = new ShhEnvelopeMessage(bytes); Assert.assertEquals(2, inbound.getMessages().size()); WhisperMessage inMsg1 = inbound.getMessages().get(0); boolean b = inMsg1.decrypt(Collections.singleton(to), Arrays.asList(Topic.createTopics("Topic2", "Topic3"))); Assert.assertTrue(b); Assert.assertEquals("Hello", new String(inMsg1.getPayload())); Assert.assertEquals(msg1.getTo(), inMsg1.getTo()); Assert.assertEquals(msg1.getFrom(), inMsg1.getFrom()); // System.out.println(msg1.nonce + ": " + inMsg1.nonce + ", " + inMsg1.getPow()); Assert.assertTrue(inMsg1.getPow() > 10); WhisperMessage inMsg2 = inbound.getMessages().get(1); b = inMsg2.decrypt(Collections.EMPTY_LIST, Arrays.asList(Topic.createTopics("Topic2", "Topic3"))); Assert.assertTrue(b); Assert.assertEquals("Hello again", new String(inMsg2.getPayload())); // System.out.println(msg2.nonce + ": " + inMsg2.getPow()); Assert.assertTrue(inMsg2.getPow() > 8); } @Test public void testCpp1() throws Exception { byte[] cipherText1 = Hex.decode("0469e324b8ab4a8e2bf0440548498226c9864d1210248ebf76c3396dd1748f0b04d347728b683993e4061998390c2cc8d6d09611da6df9769ebec888295f9be99e86ddad866f994a494361a5658d2b48d1140d73f71a382a4dc7ee2b0b5487091b0c25a3f0e6"); ECKey priv = ECKey.fromPrivate(Hex.decode("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a")); ECKey pub = ECKey.fromPublicOnly(Hex.decode("04bd27a63c91fe3233c5777e6d3d7b39204d398c8f92655947eb5a373d46e1688f022a1632d264725cbc7dc43ee1cfebde42fa0a86d08b55d2acfbb5e9b3b48dc5")); byte[] plain1 = ECIESCoder.decryptSimple(priv.getPrivKey(), cipherText1); byte[] cipherText2 = ECIESCoder.encryptSimple(pub.getPubKeyPoint(), plain1); // System.out.println("Cipher1: " + Hex.toHexString(cipherText1)); // System.out.println("Cipher2: " + Hex.toHexString(cipherText2)); byte[] plain2 = ECIESCoder.decryptSimple(priv.getPrivKey(), cipherText2); Assert.assertArrayEquals(plain1, plain2); } }
5,618
43.952
248
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/rlpx/SnappyConnectionTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.rlpx; import org.ethereum.config.NoAutoscan; import org.ethereum.config.SystemProperties; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.net.eth.message.StatusMessage; import org.ethereum.net.server.Channel; import org.junit.Ignore; import org.junit.Test; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.FileNotFoundException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * @author Mikhail Kalinin * @since 02.11.2017 */ @Ignore public class SnappyConnectionTest { @Configuration @NoAutoscan public static class SysPropConfig1 { static SystemProperties props; @Bean public SystemProperties systemProperties() { return props; } } @Configuration @NoAutoscan public static class SysPropConfig2 { static SystemProperties props; @Bean public SystemProperties systemProperties() { return props; } } @Test public void test4To4() throws FileNotFoundException, InterruptedException { runScenario(4, 4); } @Test public void test4To5() throws FileNotFoundException, InterruptedException { runScenario(4, 5); } @Test public void test5To4() throws FileNotFoundException, InterruptedException { runScenario(5, 4); } @Test public void test5To5() throws FileNotFoundException, InterruptedException { runScenario(5, 5); } private void runScenario(int vOutbound, int vInbound) throws FileNotFoundException, InterruptedException { SysPropConfig1.props = new SystemProperties(); SysPropConfig1.props.overrideParams( "peer.listen.port", "30334", "peer.privateKey", "ba43d10d069f0c41a8914849c1abeeac2a681b21ae9b60a6a2362c06e6eb1bc8", "database.dir", "test_db-1", "peer.p2p.version", String.valueOf(vInbound)); SysPropConfig2.props = new SystemProperties(); SysPropConfig2.props.overrideParams( "peer.listen.port", "30335", "peer.privateKey", "d3a4a240b107ab443d46187306d0b947ce3d6b6ed95aead8c4941afcebde43d2", "database.dir", "test_db-2", "peer.p2p.version", String.valueOf(vOutbound)); Ethereum ethereum1 = EthereumFactory.createEthereum(SysPropConfig1.class); Ethereum ethereum2 = EthereumFactory.createEthereum(SysPropConfig2.class); final CountDownLatch semaphore = new CountDownLatch(2); ethereum1.addListener(new EthereumListenerAdapter() { @Override public void onEthStatusUpdated(Channel channel, StatusMessage statusMessage) { System.out.println("1: -> " + statusMessage); semaphore.countDown(); } }); ethereum2.addListener(new EthereumListenerAdapter() { @Override public void onEthStatusUpdated(Channel channel, StatusMessage statusMessage) { System.out.println("2: -> " + statusMessage); semaphore.countDown(); } }); ethereum2.connect(new Node("enode://a560c55a0a5b5d137c638eb6973812f431974e4398c6644fa0c19181954fab530bb2a1e2c4eec7cc855f6bab9193ea41d6cf0bf2b8b41ed6b8b9e09c072a1e5a" + "@localhost:30334")); semaphore.await(60, TimeUnit.SECONDS); ethereum1.close(); ethereum2.close(); if(semaphore.getCount() > 0) { throw new RuntimeException("One or both StatusMessage was not received: " + semaphore.getCount()); } System.out.println("Passed."); } }
4,650
34.234848
175
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/rlpx/EncryptionHandshakeTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.rlpx; import org.ethereum.crypto.ECKey; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; /** * Created by android on 4/8/15. */ public class EncryptionHandshakeTest { private ECKey myKey; private ECKey remoteKey; private EncryptionHandshake initiator; @Before public void setUp() { remoteKey = new ECKey(); myKey = new ECKey(); initiator = new EncryptionHandshake(remoteKey.getPubKeyPoint()); } @Test public void testCreateAuthInitiate() throws Exception { AuthInitiateMessage message = initiator.createAuthInitiate(new byte[32], myKey); int expectedLength = 65+32+64+32+1; byte[] buffer = message.encode(); assertEquals(expectedLength, buffer.length); } @Test public void testAgreement() throws Exception { EncryptionHandshake responder = new EncryptionHandshake(); AuthInitiateMessage initiate = initiator.createAuthInitiate(null, myKey); byte[] initiatePacket = initiator.encryptAuthMessage(initiate); byte[] responsePacket = responder.handleAuthInitiate(initiatePacket, remoteKey); initiator.handleAuthResponse(myKey, initiatePacket, responsePacket); assertArrayEquals(initiator.getSecrets().aes, responder.getSecrets().aes); assertArrayEquals(initiator.getSecrets().mac, responder.getSecrets().mac); assertArrayEquals(initiator.getSecrets().token, responder.getSecrets().token); } }
2,373
37.290323
88
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/rlpx/FramingTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.rlpx; import org.ethereum.config.NoAutoscan; import org.ethereum.config.SystemProperties; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.net.eth.message.StatusMessage; import org.ethereum.net.message.Message; import org.ethereum.net.server.Channel; import org.junit.Ignore; import org.junit.Test; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import java.io.FileNotFoundException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Created by Anton Nashatyrev on 13.10.2015. */ @Ignore public class FramingTest { @Configuration @NoAutoscan public static class SysPropConfig1 { static SystemProperties props; @Bean public SystemProperties systemProperties() { return props; } @Bean @Scope("prototype") public MessageCodec messageCodec() { MessageCodec codec = new MessageCodec(); codec.setMaxFramePayloadSize(16); System.out.println("SysPropConfig1.messageCodec"); return codec; } } @Configuration @NoAutoscan public static class SysPropConfig2 { static SystemProperties props; @Bean @Scope("prototype") public MessageCodec messageCodec() { MessageCodec codec = new MessageCodec(); codec.setMaxFramePayloadSize(16); System.out.println("SysPropConfig2.messageCodec"); return codec; } @Bean public SystemProperties systemProperties() { return props; } } @Test public void testTest() throws FileNotFoundException, InterruptedException { SysPropConfig1.props = new SystemProperties(); SysPropConfig1.props.overrideParams( "peer.listen.port", "30334", "peer.privateKey", "ba43d10d069f0c41a8914849c1abeeac2a681b21ae9b60a6a2362c06e6eb1bc8", "database.dir", "testDB-1"); SysPropConfig2.props = new SystemProperties(); SysPropConfig2.props.overrideParams( "peer.listen.port", "30335", "peer.privateKey", "d3a4a240b107ab443d46187306d0b947ce3d6b6ed95aead8c4941afcebde43d2", "database.dir", "testDB-2"); Ethereum ethereum1 = EthereumFactory.createEthereum(SysPropConfig1.props, SysPropConfig1.class); Ethereum ethereum2 = EthereumFactory.createEthereum(SysPropConfig2.props, SysPropConfig2.class); final CountDownLatch semaphore = new CountDownLatch(2); ethereum1.addListener(new EthereumListenerAdapter() { @Override public void onRecvMessage(Channel channel, Message message) { if (message instanceof StatusMessage) { System.out.println("1: -> " + message); semaphore.countDown(); } } }); ethereum2.addListener(new EthereumListenerAdapter() { @Override public void onRecvMessage(Channel channel, Message message) { if (message instanceof StatusMessage) { System.out.println("2: -> " + message); semaphore.countDown(); } } }); ethereum2.connect(new Node("enode://a560c55a0a5b5d137c638eb6973812f431974e4398c6644fa0c19181954fab530bb2a1e2c4eec7cc855f6bab9193ea41d6cf0bf2b8b41ed6b8b9e09c072a1e5a" + "@localhost:30334")); semaphore.await(60, TimeUnit.SECONDS); ethereum1.close(); ethereum2.close(); if(semaphore.getCount() > 0) { throw new RuntimeException("One or both StatusMessage was not received: " + semaphore.getCount()); } System.out.println("Passed."); } }
4,825
34.485294
175
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/rlpx/EIP8DiscoveryTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.rlpx; import org.ethereum.crypto.ECKey; import org.junit.Test; import static org.ethereum.crypto.ECKey.fromPrivate; import static org.junit.Assert.*; import static org.spongycastle.util.encoders.Hex.decode; /** * @author Mikhail Kalinin * @since 18.02.2016 */ public class EIP8DiscoveryTest { private ECKey key = fromPrivate(decode("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")); @Test public void test1() { // ping packet with version 4, additional list elements PingMessage msg = (PingMessage) PingMessage.decode(decode( "e9614ccfd9fc3e74360018522d30e1419a143407ffcce748de3e22116b7e8dc92ff74788c0b6663a" + "aa3d67d641936511c8f8d6ad8698b820a7cf9e1be7155e9a241f556658c55428ec0563514365799a" + "4be2be5a685a80971ddcfa80cb422cdd0101ec04cb847f000001820cfa8215a8d790000000000000" + "000000000000000000018208ae820d058443b9a3550102")); assertEquals(4, msg.version); // ping packet with version 555, additional list elements and additional random data msg = (PingMessage) PingMessage.decode(decode( "577be4349c4dd26768081f58de4c6f375a7a22f3f7adda654d1428637412c3d7fe917cadc56d4e5e" + "7ffae1dbe3efffb9849feb71b262de37977e7c7a44e677295680e9e38ab26bee2fcbae207fba3ff3" + "d74069a50b902a82c9903ed37cc993c50001f83e82022bd79020010db83c4d001500000000abcdef" + "12820cfa8215a8d79020010db885a308d313198a2e037073488208ae82823a8443b9a355c5010203" + "040531b9019afde696e582a78fa8d95ea13ce3297d4afb8ba6433e4154caa5ac6431af1b80ba7602" + "3fa4090c408f6b4bc3701562c031041d4702971d102c9ab7fa5eed4cd6bab8f7af956f7d565ee191" + "7084a95398b6a21eac920fe3dd1345ec0a7ef39367ee69ddf092cbfe5b93e5e568ebc491983c09c7" + "6d922dc3")); assertEquals(555, msg.version); } @Test public void test2() { // pong packet with additional list elements and additional random data PongMessage.decode(decode( "09b2428d83348d27cdf7064ad9024f526cebc19e4958f0fdad87c15eb598dd61d08423e0bf66b206" + "9869e1724125f820d851c136684082774f870e614d95a2855d000f05d1648b2d5945470bc187c2d2" + "216fbe870f43ed0909009882e176a46b0102f846d79020010db885a308d313198a2e037073488208" + "ae82823aa0fbc914b16819237dcd8801d7e53f69e9719adecb3cc0e790c57e91ca4461c9548443b9" + "a355c6010203c2040506a0c969a58f6f9095004c0177a6b47f451530cab38966a25cca5cb58f0555" + "42124e")); // findnode packet with additional list elements and additional random data FindNodeMessage.decode(decode( "c7c44041b9f7c7e41934417ebac9a8e1a4c6298f74553f2fcfdcae6ed6fe53163eb3d2b52e39fe91" + "831b8a927bf4fc222c3902202027e5e9eb812195f95d20061ef5cd31d502e47ecb61183f74a504fe" + "04c51e73df81f25c4d506b26db4517490103f84eb840ca634cae0d49acb401d8a4c6b6fe8c55b70d" + "115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be0081290476" + "7bf5ccd1fc7f8443b9a35582999983999999280dc62cc8255c73471e0a61da0c89acdc0e035e260a" + "dd7fc0c04ad9ebf3919644c91cb247affc82b69bd2ca235c71eab8e49737c937a2c396")); // neighbours packet with additional list elements and additional random data NeighborsMessage.decode(decode( "c679fc8fe0b8b12f06577f2e802d34f6fa257e6137a995f6f4cbfc9ee50ed3710faf6e66f932c4c8" + "d81d64343f429651328758b47d3dbc02c4042f0fff6946a50f4a49037a72bb550f3a7872363a83e1" + "b9ee6469856c24eb4ef80b7535bcf99c0004f9015bf90150f84d846321163782115c82115db84031" + "55e1427f85f10a5c9a7755877748041af1bcd8d474ec065eb33df57a97babf54bfd2103575fa8291" + "15d224c523596b401065a97f74010610fce76382c0bf32f84984010203040101b840312c55512422" + "cf9b8a4097e9a6ad79402e87a15ae909a4bfefa22398f03d20951933beea1e4dfa6f968212385e82" + "9f04c2d314fc2d4e255e0d3bc08792b069dbf8599020010db83c4d001500000000abcdef12820d05" + "820d05b84038643200b172dcfef857492156971f0e6aa2c538d8b74010f8e140811d53b98c765dd2" + "d96126051913f44582e8c199ad7c6d6819e9a56483f637feaac9448aacf8599020010db885a308d3" + "13198a2e037073488203e78203e8b8408dcab8618c3253b558d459da53bd8fa68935a719aff8b811" + "197101a4b2b47dd2d47295286fc00cc081bb542d760717d1bdd6bec2c37cd72eca367d6dd3b9df73" + "8443b9a355010203b525a138aa34383fec3d2719a0")); } }
5,462
52.038835
112
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/rlpx/RlpxConnectionTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.rlpx; import com.google.common.collect.Lists; import org.ethereum.crypto.ECKey; import org.ethereum.net.client.Capability; import org.junit.Before; import org.junit.Test; import java.io.*; import java.security.SecureRandom; import static org.junit.Assert.*; /** * Created by devrandom on 2015-04-11. */ public class RlpxConnectionTest { private FrameCodec iCodec; private FrameCodec rCodec; private EncryptionHandshake initiator; private EncryptionHandshake responder; private HandshakeMessage iMessage; private PipedInputStream to; private PipedOutputStream toOut; private PipedInputStream from; private PipedOutputStream fromOut; @Before public void setUp() throws Exception { ECKey remoteKey = new ECKey(); ECKey myKey = new ECKey(); initiator = new EncryptionHandshake(remoteKey.getPubKeyPoint()); responder = new EncryptionHandshake(); AuthInitiateMessage initiate = initiator.createAuthInitiate(null, myKey); byte[] initiatePacket = initiator.encryptAuthMessage(initiate); byte[] responsePacket = responder.handleAuthInitiate(initiatePacket, remoteKey); initiator.handleAuthResponse(myKey, initiatePacket, responsePacket); to = new PipedInputStream(1024*1024); toOut = new PipedOutputStream(to); from = new PipedInputStream(1024*1024); fromOut = new PipedOutputStream(from); iCodec = new FrameCodec(initiator.getSecrets()); rCodec = new FrameCodec(responder.getSecrets()); byte[] nodeId = {1, 2, 3, 4}; iMessage = new HandshakeMessage( 123, "abcd", Lists.newArrayList( new Capability("zz", (byte) 1), new Capability("yy", (byte) 3) ), 3333, nodeId ); } @Test public void testFrame() throws Exception { byte[] payload = new byte[123]; new SecureRandom().nextBytes(payload); FrameCodec.Frame frame = new FrameCodec.Frame(12345, 123, new ByteArrayInputStream(payload)); iCodec.writeFrame(frame, toOut); FrameCodec.Frame frame1 = rCodec.readFrames(new DataInputStream(to)).get(0); byte[] payload1 = new byte[frame1.size]; assertEquals(frame.size, frame1.size); frame1.payload.read(payload1); assertArrayEquals(payload, payload1); assertEquals(frame.type, frame1.type); } @Test public void testMessageEncoding() throws IOException { byte[] wire = iMessage.encode(); HandshakeMessage message1 = HandshakeMessage.parse(wire); assertEquals(123, message1.version); assertEquals("abcd", message1.name); assertEquals(3333, message1.listenPort); assertArrayEquals(message1.nodeId, message1.nodeId); assertEquals(iMessage.caps, message1.caps); } @Test public void testHandshake() throws IOException { RlpxConnection iConn = new RlpxConnection(initiator.getSecrets(), from, toOut); RlpxConnection rConn = new RlpxConnection(responder.getSecrets(), to, fromOut); iConn.sendProtocolHandshake(iMessage); rConn.handleNextMessage(); HandshakeMessage receivedMessage = rConn.getHandshakeMessage(); assertNotNull(receivedMessage); assertArrayEquals(iMessage.nodeId, receivedMessage.nodeId); } }
4,263
37.763636
101
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/rlpx/SnappyCodecTest.java
/* * Copyright (c) [2017] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. * * */ package org.ethereum.net.rlpx; import org.ethereum.net.rlpx.discover.NodeStatistics; import org.ethereum.net.server.Channel; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.spongycastle.util.encoders.Hex; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.FileCopyUtils; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static org.ethereum.net.message.ReasonCode.BAD_PROTOCOL; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * EIP-706 provides snappy samples. FrameCodec should be * able to decode these samples. */ public class SnappyCodecTest { @Test public void testDecodeGoGeneratedSnappy() throws Exception { Resource golangGeneratedSnappy = new ClassPathResource("/rlp/block.go.snappy"); List<Object> result = snappyDecode(golangGeneratedSnappy); assertEquals(1, result.size()); } @Test public void testDecodePythonGeneratedSnappy() throws Exception { Resource pythonGeneratedSnappy = new ClassPathResource("/rlp/block.py.snappy"); List<Object> result = snappyDecode(pythonGeneratedSnappy); assertEquals(1, result.size()); } @Test public void testFramedDecodeDisconnect() throws Exception { byte[] frameBytes = new byte[] {(byte) 0xff, 0x06, 0x00, 0x00, 0x73, 0x4e, 0x61, 0x50, 0x70, 0x59}; Channel shouldBeDropped = mock(Channel.class); when(shouldBeDropped.getNodeStatistics()) .thenReturn(new NodeStatistics(new Node(new byte[0], "", 0))); doAnswer(invocation -> { shouldBeDropped.getNodeStatistics().nodeDisconnectedLocal(invocation.getArgument(0)); return null; }).when(shouldBeDropped).disconnect(any()); snappyDecode(frameBytes, shouldBeDropped); assertTrue(shouldBeDropped.getNodeStatistics().wasDisconnected()); String stats = shouldBeDropped.getNodeStatistics().toString(); assertTrue(stats.contains(BAD_PROTOCOL.toString())); } private void snappyDecode(byte[] payload, Channel channel) throws Exception { SnappyCodec codec = new SnappyCodec(channel); FrameCodec.Frame msg = new FrameCodec.Frame(1, payload); List<Object> result = newArrayList(); codec.decode(null, msg, result); } private List<Object> snappyDecode(Resource hexEncodedSnappyResource) throws Exception { Channel channel = new Channel(); SnappyCodec codec = new SnappyCodec(channel); byte[] golangSnappyBytes = FileCopyUtils.copyToByteArray(hexEncodedSnappyResource.getInputStream()); FrameCodec.Frame msg = new FrameCodec.Frame(1, Hex.decode(golangSnappyBytes)); List<Object> result = newArrayList(); codec.decode(null, msg, result); return result; } }
3,953
38.54
108
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/rlpx/SanityLongRunTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.rlpx; import com.typesafe.config.ConfigFactory; import org.ethereum.config.NoAutoscan; import org.ethereum.config.SystemProperties; import org.ethereum.core.Block; import org.ethereum.core.TransactionReceipt; import org.ethereum.crypto.ECKey; import org.ethereum.facade.Ethereum; import org.ethereum.facade.EthereumFactory; import org.ethereum.listener.EthereumListenerAdapter; import org.ethereum.net.eth.message.StatusMessage; import org.ethereum.net.message.Message; import org.ethereum.net.server.Channel; import org.ethereum.net.shh.MessageWatcher; import org.ethereum.net.shh.WhisperMessage; import org.junit.Ignore; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.FileNotFoundException; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * Created by Anton Nashatyrev on 13.10.2015. */ @Ignore public class SanityLongRunTest { @Configuration @NoAutoscan public static class SysPropConfig1 { static SystemProperties props; @Bean public SystemProperties systemProperties() { return props; } } @Configuration @NoAutoscan public static class SysPropConfig2 { static SystemProperties props; @Bean public SystemProperties systemProperties() { return props; } } String config1 = "peer.discovery.enabled = true \n" + // "peer.discovery.enabled = false \n" + "database.dir = testDB-1 \n" + "database.reset = true \n" + "sync.enabled = true \n" + // "sync.enabled = false \n" + "peer.capabilities = [eth, shh] \n" + "peer.listen.port = 60300 \n" + " # derived nodeId = deadbeea2250b3efb9e6268451e74bdbdc5632a1a03a0f5b626f59150ff772ac287e122531b5e8d55ff10cb541bbc8abf5def6bcbfa31cf5923ca3c3d783d312\n" + "peer.privateKey = d3a4a240b107ab443d46187306d0b947ce3d6b6ed95aead8c4941afcebde43d2\n" + "peer.p2p.version = 4 \n" + "peer.p2p.framing.maxSize = 1024 \n"; ECKey config2Key = new ECKey(); String config2 = "peer.discovery.enabled = false \n" + "database.dir = testDB-2 \n" + "database.reset = true \n" + "sync.enabled = true \n" + "peer.capabilities = [eth, shh] \n" + // "peer.listen.port = 60300 \n" + "peer.privateKey = " + Hex.toHexString(config2Key.getPrivKeyBytes()) + "\n" + "peer { active = [" + " { url = \"enode://deadbeea2250b3efb9e6268451e74bdbdc5632a1a03a0f5b626f59150ff772ac287e122531b5e8d55ff10cb541bbc8abf5def6bcbfa31cf5923ca3c3d783d312" + "@localhost:60300\" }" + "] } \n" + "peer.p2p.version = 5 \n" + "peer.p2p.framing.maxSize = 1024 \n"; @Test public void testTest() throws FileNotFoundException, InterruptedException { SysPropConfig1.props = new SystemProperties(ConfigFactory.parseString(config1)); SysPropConfig2.props = new SystemProperties(ConfigFactory.parseString(config2)); // Ethereum ethereum1 = EthereumFactory.createEthereum(SysPropConfig1.props, SysPropConfig1.class); Ethereum ethereum1 = null; // Thread.sleep(1000000000); Ethereum ethereum2 = EthereumFactory.createEthereum(SysPropConfig2.props, SysPropConfig2.class); final CountDownLatch semaphore = new CountDownLatch(1); ethereum2.addListener(new EthereumListenerAdapter() { @Override public void onRecvMessage(Channel channel, Message message) { if (message instanceof StatusMessage) { System.out.println("=== Status received: " + message); semaphore.countDown(); } } }); semaphore.await(60, TimeUnit.SECONDS); if(semaphore.getCount() > 0) { throw new RuntimeException("StatusMessage was not received in 60 sec: " + semaphore.getCount()); } final CountDownLatch semaphoreBlocks = new CountDownLatch(1); final CountDownLatch semaphoreFirstBlock = new CountDownLatch(1); ethereum2.addListener(new EthereumListenerAdapter() { int blocksCnt = 0; @Override public void onBlock(Block block, List<TransactionReceipt> receipts) { blocksCnt++; if (blocksCnt % 1000 == 0 || blocksCnt == 1) { System.out.println("=== Blocks imported: " + blocksCnt); if (blocksCnt == 1) { semaphoreFirstBlock.countDown(); } } if (blocksCnt >= 10_000) { semaphoreBlocks.countDown(); System.out.println("=== Blocks task done."); } } }); semaphoreFirstBlock.await(180, TimeUnit.SECONDS); if(semaphoreFirstBlock.getCount() > 0) { throw new RuntimeException("No blocks were received in 60 sec: " + semaphore.getCount()); } // SHH messages exchange String identity1 = ethereum1.getWhisper().newIdentity(); String identity2 = ethereum2.getWhisper().newIdentity(); final int[] counter1 = new int[1]; final int[] counter2 = new int[1]; ethereum1.getWhisper().watch(new MessageWatcher(identity1, null, null) { @Override protected void newMessage(WhisperMessage msg) { System.out.println("=== You have a new message to 1: " + msg); counter1[0]++; } }); ethereum2.getWhisper().watch(new MessageWatcher(identity2, null, null) { @Override protected void newMessage(WhisperMessage msg) { System.out.println("=== You have a new message to 2: " + msg); counter2[0]++; } }); System.out.println("=== Sending messages ... "); int cnt = 0; long end = System.currentTimeMillis() + 60 * 60 * 1000; while (semaphoreBlocks.getCount() > 0) { ethereum1.getWhisper().send(identity2, "Hello Eth2!".getBytes(), null); ethereum2.getWhisper().send(identity1, "Hello Eth1!".getBytes(), null); cnt++; Thread.sleep(10 * 1000); if (counter1[0] != cnt || counter2[0] != cnt) { throw new RuntimeException("Message was not delivered in 10 sec: " + cnt); } if (System.currentTimeMillis() > end) { throw new RuntimeException("Wanted blocks amount was not received in a hour"); } } ethereum1.close(); ethereum2.close(); System.out.println("Passed."); } }
7,801
37.623762
166
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/rlpx/KademliaTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.rlpx; import org.ethereum.net.rlpx.discover.table.KademliaOptions; import org.ethereum.net.rlpx.discover.table.NodeBucket; import org.ethereum.net.rlpx.discover.table.NodeEntry; import org.ethereum.net.rlpx.discover.table.NodeTable; import org.junit.Ignore; import org.junit.Test; import java.util.List; import java.util.Random; import static org.junit.Assert.*; public class KademliaTest { @Ignore @Test public void test1() { //init table with one home node NodeTable t = getTestNodeTable(0); Node homeNode = t.getNode(); //table should contain the home node only assertEquals(t.getAllNodes().size(), 1); Node bucketNode = t.getAllNodes().get(0).getNode(); assertEquals(homeNode, bucketNode); } @Test public void test2() { NodeTable t = getTestNodeTable(0); Node n = getNode(); t.addNode(n); assertTrue(containsNode(t, n)); t.dropNode(n); assertFalse(containsNode(t, n)); } @Test public void test3() { NodeTable t = getTestNodeTable(1000); showBuckets(t); List<Node> closest1 = t.getClosestNodes(t.getNode().getId()); List<Node> closest2 = t.getClosestNodes(getNodeId()); assertNotEquals(closest1, closest2); } @Test public void test4() { NodeTable t = getTestNodeTable(0); Node homeNode = t.getNode(); //t.getBucketsCount() returns non empty buckets assertEquals(t.getBucketsCount(), 1); //creates very close nodes for (int i = 1; i < KademliaOptions.BUCKET_SIZE; i++) { Node n= getNode(homeNode.getId(), i); t.addNode(n); } assertEquals(t.getBucketsCount(), 1); assertEquals(t.getBuckets()[0].getNodesCount(), KademliaOptions.BUCKET_SIZE); } public static byte[] getNodeId() { Random gen = new Random(); byte[] id = new byte[64]; gen.nextBytes(id); return id; } public static Node getNode(byte[] id, int i) { id[0] += (byte) i; Node n = getNode(); n.setId(id); return n; } public static Node getNode() { return new Node(getNodeId(), "127.0.0.1", 30303); } public static NodeTable getTestNodeTable(int nodesQuantity) { NodeTable testTable = new NodeTable(getNode()); for (int i = 0; i < nodesQuantity; i++) { testTable.addNode(getNode()); } return testTable; } public static void showBuckets(NodeTable t) { for (NodeBucket b : t.getBuckets()) { if (b.getNodesCount() > 0) { System.out.println(String.format("Bucket %d nodes %d depth %d", b.getDepth(), b.getNodesCount(), b.getDepth())); } } } public static boolean containsNode(NodeTable t, Node n) { for (NodeEntry e : t.getAllNodes()) { if (e.getNode().toString().equals(n.toString())) { return true; } } return false; } }
3,896
27.445255
128
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/rlpx/EIP8HandshakeTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.rlpx; import org.ethereum.crypto.ECKey; import org.junit.Before; import org.junit.Test; import org.spongycastle.crypto.InvalidCipherTextException; import static org.ethereum.crypto.ECKey.fromPrivate; import static org.junit.Assert.*; import static org.spongycastle.util.encoders.Hex.decode; /** * @author Mikhail Kalinin * @since 17.02.2016 */ public class EIP8HandshakeTest { private ECKey keyA = fromPrivate(decode("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee")); private ECKey keyB = fromPrivate(decode("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")); private ECKey ephemeralKeyA = fromPrivate(decode("869d6ecf5211f1cc60418a13b9d870b22959d0c16f02bec714c960dd2298a32d")); private ECKey ephemeralKeyB = fromPrivate(decode("e238eb8e04fee6511ab04c6dd3c89ce097b11f25d584863ac2b6d5b35b1847e4")); private byte[] nonceA = decode("7e968bba13b6c50e2c4cd7f241cc0d64d1ac25c7f5952df231ac6a2bda8ee5d6"); private byte[] nonceB = decode("559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd"); private ECKey.ECDSASignature signatureA = ECKey.ECDSASignature.fromComponents( decode("299ca6acfd35e3d72d8ba3d1e2b60b5561d5af5218eb5bc182045769eb422691"), decode("0a301acae3b369fffc4a4899d6b02531e89fd4fe36a2cf0d93607ba470b50f78"), (byte) 27 ); private EncryptionHandshake handshakerA; private EncryptionHandshake handshakerB; @Before public void setUp() { handshakerA = new EncryptionHandshake(keyB.getPubKeyPoint()); handshakerB = new EncryptionHandshake(null, ephemeralKeyB, null, nonceB, false); } // AuthInitiate EIP-8 format with version 4 and no additional list elements (sent from A to B) @Test public void test1() throws InvalidCipherTextException { byte[] authMessageData = decode( "01b304ab7578555167be8154d5cc456f567d5ba302662433674222360f08d5f1534499d3678b513b" + "0fca474f3a514b18e75683032eb63fccb16c156dc6eb2c0b1593f0d84ac74f6e475f1b8d56116b84" + "9634a8c458705bf83a626ea0384d4d7341aae591fae42ce6bd5c850bfe0b999a694a49bbbaf3ef6c" + "da61110601d3b4c02ab6c30437257a6e0117792631a4b47c1d52fc0f8f89caadeb7d02770bf999cc" + "147d2df3b62e1ffb2c9d8c125a3984865356266bca11ce7d3a688663a51d82defaa8aad69da39ab6" + "d5470e81ec5f2a7a47fb865ff7cca21516f9299a07b1bc63ba56c7a1a892112841ca44b6e0034dee" + "70c9adabc15d76a54f443593fafdc3b27af8059703f88928e199cb122362a4b35f62386da7caad09" + "c001edaeb5f8a06d2b26fb6cb93c52a9fca51853b68193916982358fe1e5369e249875bb8d0d0ec3" + "6f917bc5e1eafd5896d46bd61ff23f1a863a8a8dcd54c7b109b771c8e61ec9c8908c733c0263440e" + "2aa067241aaa433f0bb053c7b31a838504b148f570c0ad62837129e547678c5190341e4f1693956c" + "3bf7678318e2d5b5340c9e488eefea198576344afbdf66db5f51204a6961a63ce072c8926c"); // encode (on A side) AuthInitiateMessageV4 msg1 = handshakerA.createAuthInitiateV4(keyA); msg1.signature = signatureA; msg1.nonce = nonceA; msg1.version = 4; byte[] encrypted = handshakerA.encryptAuthInitiateV4(msg1); // decode (on B side) AuthInitiateMessageV4 msg2 = handshakerB.decryptAuthInitiateV4(encrypted, keyB); assertEquals(4, msg2.version); assertArrayEquals(nonceA, msg2.nonce); assertEquals(signatureA.r, msg2.signature.r); assertEquals(signatureA.s, msg2.signature.s); assertEquals(signatureA.v, msg2.signature.v); AuthInitiateMessageV4 msg3 = handshakerB.decryptAuthInitiateV4(authMessageData, keyB); assertEquals(4, msg3.version); assertArrayEquals(nonceA, msg3.nonce); assertEquals(signatureA.r, msg3.signature.r); assertEquals(signatureA.s, msg3.signature.s); assertEquals(signatureA.v, msg3.signature.v); } // AuthInitiate EIP-8 format with version 56 and 3 additional list elements (sent from A to B) @Test public void test2() throws InvalidCipherTextException { byte[] authMessageData = decode( "01b8044c6c312173685d1edd268aa95e1d495474c6959bcdd10067ba4c9013df9e40ff45f5bfd6f7" + "2471f93a91b493f8e00abc4b80f682973de715d77ba3a005a242eb859f9a211d93a347fa64b597bf" + "280a6b88e26299cf263b01b8dfdb712278464fd1c25840b995e84d367d743f66c0e54a586725b7bb" + "f12acca27170ae3283c1073adda4b6d79f27656993aefccf16e0d0409fe07db2dc398a1b7e8ee93b" + "cd181485fd332f381d6a050fba4c7641a5112ac1b0b61168d20f01b479e19adf7fdbfa0905f63352" + "bfc7e23cf3357657455119d879c78d3cf8c8c06375f3f7d4861aa02a122467e069acaf513025ff19" + "6641f6d2810ce493f51bee9c966b15c5043505350392b57645385a18c78f14669cc4d960446c1757" + "1b7c5d725021babbcd786957f3d17089c084907bda22c2b2675b4378b114c601d858802a55345a15" + "116bc61da4193996187ed70d16730e9ae6b3bb8787ebcaea1871d850997ddc08b4f4ea668fbf3740" + "7ac044b55be0908ecb94d4ed172ece66fd31bfdadf2b97a8bc690163ee11f5b575a4b44e36e2bfb2" + "f0fce91676fd64c7773bac6a003f481fddd0bae0a1f31aa27504e2a533af4cef3b623f4791b2cca6" + "d490"); AuthInitiateMessageV4 msg2 = handshakerB.decryptAuthInitiateV4(authMessageData, keyB); assertEquals(56, msg2.version); assertArrayEquals(nonceA, msg2.nonce); } // AuthResponse EIP-8 format with version 4 and no additional list elements (sent from B to A) @Test public void test3() throws InvalidCipherTextException { byte[] authInitiateData = decode( "01b304ab7578555167be8154d5cc456f567d5ba302662433674222360f08d5f1534499d3678b513b" + "0fca474f3a514b18e75683032eb63fccb16c156dc6eb2c0b1593f0d84ac74f6e475f1b8d56116b84" + "9634a8c458705bf83a626ea0384d4d7341aae591fae42ce6bd5c850bfe0b999a694a49bbbaf3ef6c" + "da61110601d3b4c02ab6c30437257a6e0117792631a4b47c1d52fc0f8f89caadeb7d02770bf999cc" + "147d2df3b62e1ffb2c9d8c125a3984865356266bca11ce7d3a688663a51d82defaa8aad69da39ab6" + "d5470e81ec5f2a7a47fb865ff7cca21516f9299a07b1bc63ba56c7a1a892112841ca44b6e0034dee" + "70c9adabc15d76a54f443593fafdc3b27af8059703f88928e199cb122362a4b35f62386da7caad09" + "c001edaeb5f8a06d2b26fb6cb93c52a9fca51853b68193916982358fe1e5369e249875bb8d0d0ec3" + "6f917bc5e1eafd5896d46bd61ff23f1a863a8a8dcd54c7b109b771c8e61ec9c8908c733c0263440e" + "2aa067241aaa433f0bb053c7b31a838504b148f570c0ad62837129e547678c5190341e4f1693956c" + "3bf7678318e2d5b5340c9e488eefea198576344afbdf66db5f51204a6961a63ce072c8926c"); byte[] authResponseData = decode( "01ea0451958701280a56482929d3b0757da8f7fbe5286784beead59d95089c217c9b917788989470" + "b0e330cc6e4fb383c0340ed85fab836ec9fb8a49672712aeabbdfd1e837c1ff4cace34311cd7f4de" + "05d59279e3524ab26ef753a0095637ac88f2b499b9914b5f64e143eae548a1066e14cd2f4bd7f814" + "c4652f11b254f8a2d0191e2f5546fae6055694aed14d906df79ad3b407d94692694e259191cde171" + "ad542fc588fa2b7333313d82a9f887332f1dfc36cea03f831cb9a23fea05b33deb999e85489e645f" + "6aab1872475d488d7bd6c7c120caf28dbfc5d6833888155ed69d34dbdc39c1f299be1057810f34fb" + "e754d021bfca14dc989753d61c413d261934e1a9c67ee060a25eefb54e81a4d14baff922180c395d" + "3f998d70f46f6b58306f969627ae364497e73fc27f6d17ae45a413d322cb8814276be6ddd13b885b" + "201b943213656cde498fa0e9ddc8e0b8f8a53824fbd82254f3e2c17e8eaea009c38b4aa0a3f306e8" + "797db43c25d68e86f262e564086f59a2fc60511c42abfb3057c247a8a8fe4fb3ccbadde17514b7ac" + "8000cdb6a912778426260c47f38919a91f25f4b5ffb455d6aaaf150f7e5529c100ce62d6d92826a7" + "1778d809bdf60232ae21ce8a437eca8223f45ac37f6487452ce626f549b3b5fdee26afd2072e4bc7" + "5833c2464c805246155289f4"); // agree (on B side) AuthInitiateMessageV4 initiate = handshakerB.decryptAuthInitiateV4(authInitiateData, keyB); AuthResponseMessageV4 response = handshakerB.makeAuthInitiateV4(initiate, keyB); assertArrayEquals(keyA.getPubKey(), handshakerB.getRemotePublicKey().getEncoded(false)); handshakerB.agreeSecret(authInitiateData, authResponseData); assertArrayEquals(decode("80e8632c05fed6fc2a13b0f8d31a3cf645366239170ea067065aba8e28bac487"), handshakerB.getSecrets().aes); assertArrayEquals(decode("2ea74ec5dae199227dff1af715362700e989d889d7a493cb0639691efb8e5f98"), handshakerB.getSecrets().mac); byte[] fooHash = new byte[32]; handshakerB.getSecrets().ingressMac.update("foo".getBytes(), 0, "foo".getBytes().length); handshakerB.getSecrets().ingressMac.doFinal(fooHash, 0); assertArrayEquals(decode("0c7ec6340062cc46f5e9f1e3cf86f8c8c403c5a0964f5df0ebd34a75ddc86db5"), fooHash); // decode (on A side) response.ephemeralPublicKey = ephemeralKeyB.getPubKeyPoint(); byte[] encrypted = handshakerB.encryptAuthResponseV4(response); AuthResponseMessageV4 msg2 = handshakerA.decryptAuthResponseV4(encrypted, keyA); assertEquals(4, msg2.version); assertArrayEquals(nonceB, msg2.nonce); assertArrayEquals(ephemeralKeyB.getPubKey(), msg2.ephemeralPublicKey.getEncoded(false)); AuthResponseMessageV4 msg3 = handshakerA.decryptAuthResponseV4(authResponseData, keyA); assertEquals(4, msg3.version); assertArrayEquals(nonceB, msg3.nonce); assertArrayEquals(ephemeralKeyB.getPubKey(), msg3.ephemeralPublicKey.getEncoded(false)); } // AuthResponse EIP-8 format with version 57 and 3 additional list elements (sent from B to A) @Test public void test4() throws InvalidCipherTextException { byte[] authMessageData = decode( "01f004076e58aae772bb101ab1a8e64e01ee96e64857ce82b1113817c6cdd52c09d26f7b90981cd7" + "ae835aeac72e1573b8a0225dd56d157a010846d888dac7464baf53f2ad4e3d584531fa203658fab0" + "3a06c9fd5e35737e417bc28c1cbf5e5dfc666de7090f69c3b29754725f84f75382891c561040ea1d" + "dc0d8f381ed1b9d0d4ad2a0ec021421d847820d6fa0ba66eaf58175f1b235e851c7e2124069fbc20" + "2888ddb3ac4d56bcbd1b9b7eab59e78f2e2d400905050f4a92dec1c4bdf797b3fc9b2f8e84a482f3" + "d800386186712dae00d5c386ec9387a5e9c9a1aca5a573ca91082c7d68421f388e79127a5177d4f8" + "590237364fd348c9611fa39f78dcdceee3f390f07991b7b47e1daa3ebcb6ccc9607811cb17ce51f1" + "c8c2c5098dbdd28fca547b3f58c01a424ac05f869f49c6a34672ea2cbbc558428aa1fe48bbfd6115" + "8b1b735a65d99f21e70dbc020bfdface9f724a0d1fb5895db971cc81aa7608baa0920abb0a565c9c" + "436e2fd13323428296c86385f2384e408a31e104670df0791d93e743a3a5194ee6b076fb6323ca59" + "3011b7348c16cf58f66b9633906ba54a2ee803187344b394f75dd2e663a57b956cb830dd7a908d4f" + "39a2336a61ef9fda549180d4ccde21514d117b6c6fd07a9102b5efe710a32af4eeacae2cb3b1dec0" + "35b9593b48b9d3ca4c13d245d5f04169b0b1"); // decode (on A side) AuthResponseMessageV4 msg2 = handshakerA.decryptAuthResponseV4(authMessageData, keyA); assertEquals(57, msg2.version); assertArrayEquals(nonceB, msg2.nonce); } }
12,334
56.372093
132
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/rlpx/RLPXTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.rlpx; import org.ethereum.crypto.ECKey; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.Collections; import java.util.List; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.merge; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class RLPXTest { private static final org.slf4j.Logger logger = LoggerFactory.getLogger("test"); @Test // ping test public void test1() { Node node = Node.instanceOf("85.65.19.231:30303"); ECKey key = ECKey.fromPrivate(BigInteger.TEN); Message ping = PingMessage.create(node, node, key); logger.info("{}", ping); byte[] wire = ping.getPacket(); PingMessage ping2 = (PingMessage) Message.decode(wire); logger.info("{}", ping2); assertEquals(ping.toString(), ping2.toString()); String key2 = ping2.getKey().toString(); assertEquals(key.toString(), key2.toString()); } @Test // pong test public void test2() { byte[] token = sha3("+++".getBytes(Charset.forName("UTF-8"))); ECKey key = ECKey.fromPrivate(BigInteger.TEN); Message pong = PongMessage.create(token, key); logger.info("{}", pong); byte[] wire = pong.getPacket(); PongMessage pong2 = (PongMessage) Message.decode(wire); logger.info("{}", pong); assertEquals(pong.toString(), pong2.toString()); String key2 = pong2.getKey().toString(); assertEquals(key.toString(), key2.toString()); } @Test // neighbors message public void test3() { String ip = "85.65.19.231"; int port = 30303; byte[] part1 = sha3("007".getBytes(Charset.forName("UTF-8"))); byte[] id = ECKey.fromPrivate(part1).getNodeId(); Node node = new Node(id, ip, port); List<Node> nodes = Collections.singletonList(node); ECKey key = ECKey.fromPrivate(BigInteger.TEN); Message neighbors = NeighborsMessage.create(nodes, key); logger.info("{}", neighbors); byte[] wire = neighbors.getPacket(); NeighborsMessage neighbors2 = (NeighborsMessage) Message.decode(wire); logger.info("{}", neighbors2); assertEquals(neighbors.toString(), neighbors2.toString()); String key2 = neighbors2.getKey().toString(); assertEquals(key.toString(), key2.toString()); } @Test // find node message public void test4() { byte[] id = sha3("+++".getBytes(Charset.forName("UTF-8"))); ECKey key = ECKey.fromPrivate(BigInteger.TEN); Message findNode = FindNodeMessage.create(id, key); logger.info("{}", findNode); byte[] wire = findNode.getPacket(); FindNodeMessage findNode2 = (FindNodeMessage) Message.decode(wire); logger.info("{}", findNode2); assertEquals(findNode.toString(), findNode2.toString()); String key2 = findNode2.getKey().toString(); assertEquals(key.toString(), key2.toString()); } @Test(expected = Exception.class)// failure on MDC public void test5() { byte[] id = sha3("+++".getBytes(Charset.forName("UTF-8"))); ECKey key = ECKey.fromPrivate(BigInteger.TEN); Message findNode = FindNodeMessage.create(id, key); logger.info("{}", findNode); byte[] wire = findNode.getPacket(); wire[64]++; FindNodeMessage findNode2 = (FindNodeMessage) Message.decode(wire); logger.info("{}", findNode2); assertEquals(findNode.toString(), findNode2.toString()); } @Test public void test6() { byte[] id_1 = ECKey.fromPrivate(sha3("+++".getBytes(Charset.forName("UTF-8")))).getNodeId(); String host_1 = "85.65.19.231"; int port_1 = 30303; Node node_1 = new Node(id_1, host_1 , port_1); Node node_2 = new Node(node_1.getRLP()); byte[] id_2 = node_2.getId(); String host_2 = node_2.getHost(); int port_2 = node_2.getPort(); assertEquals(Hex.toHexString(id_1), Hex.toHexString(id_2)); assertEquals(host_1, host_2); assertTrue(port_1 == port_2); } @Test // Neighbors parse data public void test7() { byte[] wire = Hex.decode("d5106e888eeca1e0b4a93bf17c325f912b43ca4176a000966619aa6a96ac9d5a60e66c73ed5629c13d4d0c806a3127379541e8d90d7fcb52c33c5e36557ad92dfed9619fcd3b92e42683aed89bd3c6eef6b59bd0237c36d83ebb0075a59903f50104f90200f901f8f8528c38352e36352e31392e32333182f310b840aeb2dd107edd996adf1bbf835fb3f9a11aabb7ed3dfef84c7a3c8767482bff522906a11e8cddee969153bf5944e64e37943db509bb4cc714c217f20483802ec0f8528c38352e36352e31392e32333182e5b4b840b70cdf8f23024a65afbf12110ca06fa5c37bd9fe4f6234a0120cdaaf16e8bb96d090d0164c316aaa18158d346e9b0a29ad9bfa0404ab4ee9906adfbacb01c21bf8528c38352e36352e31392e32333182df38b840ed8e01b5f5468f32de23a7524af1b35605ffd7cdb79af4eacd522c94f8ed849bb81dfed4992c179caeef0952ecad2d868503164a434c300356b369a33c159289f8528c38352e36352e31392e32333182df38b840136996f11c2c80f231987fc4f0cbd061cb021c63afaf5dd879e7c851a57be8d023af14bc201be81588ecab7971693b3f689a4854df74ad2e2334e88ae76aa122f8528c38352e36352e31392e32333182f303b840742eac32e1e2343b89c03a20fc051854ea6a3ff28ca918d1994fe1e32d6d77ab63352131db3ed0e7d6cc057d859c114b102f49052daee3d1c5f5fdaab972e655f8528c38352e36352e31392e32333182f310b8407d9e1f9ceb66fc21787b830554d604f933be203be9366710fb33355975e874a72b87837cf28b1b9ae171826b64e3c5d178326cbf71f89b3dec614816a1a40ce38454f6b578"); NeighborsMessage msg1 = (NeighborsMessage) NeighborsMessage.decode(wire); ECKey key = ECKey.fromPrivate(BigInteger.TEN); NeighborsMessage msg2 = (NeighborsMessage) NeighborsMessage.create(msg1.getNodes(), key); NeighborsMessage msg3 = (NeighborsMessage) NeighborsMessage.decode(msg2.getPacket()); for (int i = 0; i < msg1.getNodes().size(); ++i) { Node node_1 = msg1.getNodes().get(i); Node node_3 = msg3.getNodes().get(i); assertEquals(node_1.toString(), node_3.toString()); } System.out.println(msg1); } @Test // FindNodeMessage parse data public void test8() { byte[] wire = Hex.decode("3770d98825a42cb69edf70ffdf8d6d2b28a8c5499a7e3350e4a42c94652339cac3f8e9c3b5a181c8dd13e491ad9229f6a8bd018d786e1fb9e5264f43bbd6ce93af9bc85b468dee651bcd518561f83cb166da7aef7e506057dc2fbb2ea582bcc00003f847b84083fba54f6bb80ce31f6d5d1ec0a9a2e4685bc185115b01da6dcb70cd13116a6bd08b86ffe60b7d7ea56c6498848e3741113f8e70b9f0d12dbfe895680d03fd658454f6e772"); FindNodeMessage msg1 = (FindNodeMessage) FindNodeMessage.decode(wire); ECKey key = ECKey.fromPrivate(BigInteger.TEN); FindNodeMessage msg2 = FindNodeMessage.create(msg1.getTarget(), key); FindNodeMessage msg3 = (FindNodeMessage) FindNodeMessage.decode(msg2.getPacket()); Assert.assertEquals(Hex.toHexString(msg1.getTarget()), Hex.toHexString(msg3.getTarget())); } @Ignore //TODO #POC9 @Test // Ping parse data public void test9() { // wire: 4c62e1b75f4003ef77032006a142bbf31772936a1e5098566b28a04a5c71c73f1f2c9f539a85458c50a554de12da9d7e69fb2507f7c0788885508d385bbe7a9538fa675712aa1eaad29902bb46eee4531d00a10fd81179e4151929f60fec4dc50001ce87302e302e302e30808454f8483c // PingMessage: {mdc=4c62e1b75f4003ef77032006a142bbf31772936a1e5098566b28a04a5c71c73f, signature=1f2c9f539a85458c50a554de12da9d7e69fb2507f7c0788885508d385bbe7a9538fa675712aa1eaad29902bb46eee4531d00a10fd81179e4151929f60fec4dc500, type=01, data=ce87302e302e302e30808454f8483c} // FIXME: wire contains empty from data byte[] wire = Hex.decode("4c62e1b75f4003ef77032006a142bbf31772936a1e5098566b28a04a5c71c73f1f2c9f539a85458c50a554de12da9d7e69fb2507f7c0788885508d385bbe7a9538fa675712aa1eaad29902bb46eee4531d00a10fd81179e4151929f60fec4dc50001ce87302e302e302e30808454f8483c"); PingMessage msg1 = (PingMessage)Message.decode(wire); ECKey key = ECKey.fromPrivate(BigInteger.TEN); Node node = Node.instanceOf(msg1.getToHost() + ":" + msg1.getToPort()); PingMessage msg2 = PingMessage.create(node, node, key); PingMessage msg3 = (PingMessage)Message.decode(msg2.getPacket()); assertEquals(msg1.getToHost(), msg3.getToHost()); } @Test // Pong parse data public void test10(){ // wire: 84db9bf6a1f7a3444f4d4946155da16c63a51abdd6822ac683d8243f260b99b265601b769acebfe3c76ddeb6e83e924f2bac2beca0c802ff0745d349bd58bc6662d62d38c2a3bb3e167a333d7d099496ebd35e096c5c1ee1587e9bd11f20e3d80002e6a079d49bdba3a7acfc9a2881d768d1aa246c2486ab166f0305a863bd47c5d21e0e8454f8483c // PongMessage: {mdc=84db9bf6a1f7a3444f4d4946155da16c63a51abdd6822ac683d8243f260b99b2, signature=65601b769acebfe3c76ddeb6e83e924f2bac2beca0c802ff0745d349bd58bc6662d62d38c2a3bb3e167a333d7d099496ebd35e096c5c1ee1587e9bd11f20e3d800, type=02, data=e6a079d49bdba3a7acfc9a2881d768d1aa246c2486ab166f0305a863bd47c5d21e0e8454f8483c} byte[] wire = Hex.decode("84db9bf6a1f7a3444f4d4946155da16c63a51abdd6822ac683d8243f260b99b265601b769acebfe3c76ddeb6e83e924f2bac2beca0c802ff0745d349bd58bc6662d62d38c2a3bb3e167a333d7d099496ebd35e096c5c1ee1587e9bd11f20e3d80002e6a079d49bdba3a7acfc9a2881d768d1aa246c2486ab166f0305a863bd47c5d21e0e8454f8483c"); PongMessage msg1 = (PongMessage)Message.decode(wire); ECKey key = ECKey.fromPrivate(BigInteger.TEN); PongMessage msg2 = PongMessage.create(msg1.getToken(), key, 1448375807); PongMessage msg3 = (PongMessage) Message.decode(msg2.getPacket()); assertEquals(Hex.toHexString(msg1.getToken()), Hex.toHexString(msg3.getToken())); } /** * Correct encoding of IP addresses according to official RLPx protocol documentation * https://github.com/ethereum/devp2p/blob/master/rlpx.md */ @Test public void testCorrectIpPing() { // {mdc=d7a3a7ce591180e2f6d6f8655ece88fe3d98fff2b9896578712f77aabb8394eb, // signature=6a436c85ad30842cb64451f9a5705b96089b37ad7705cf28ee15e51be55a9b756fe178371d28961aa432ce625fb313fd8e6c8607a776107115bafdd591e89dab00, // type=01, data=e804d7900000000000000000000000000000000082765f82765fc9843a8808ba8233d88084587328cd} byte[] wire = Hex.decode("d7a3a7ce591180e2f6d6f8655ece88fe3d98fff2b9896578712f77aabb8394eb6a436c85ad30842cb64451f9a5705b96089b37ad7705cf28ee15e51be55a9b756fe178371d28961aa432ce625fb313fd8e6c8607a776107115bafdd591e89dab0001e804d7900000000000000000000000000000000082765f82765fc9843a8808ba8233d88084587328cd"); PingMessage msg1 = (PingMessage) Message.decode(wire); assertEquals(30303, msg1.getFromPort()); assertEquals("0.0.0.0", msg1.getFromHost()); assertEquals(13272, msg1.getToPort()); assertEquals("58.136.8.186", msg1.getToHost()); } @Test(expected = IllegalArgumentException.class) public void testInvalidNodeId() { byte[] id_1 = sha3("+++".getBytes(Charset.forName("UTF-8"))); String host_1 = "85.65.19.231"; int port_1 = 30303; Node node_1 = new Node(id_1, host_1 , port_1); new Node(node_1.getRLP()); } }
12,250
42.137324
1,257
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/net/rlpx/discover/QueueTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.net.rlpx.discover; import org.junit.Test; import java.util.Comparator; import java.util.concurrent.TimeUnit; /** * Created by Anton Nashatyrev on 03.08.2015. */ public class QueueTest { boolean exception = false; @Test public void simple() throws Exception { final PeerConnectionTester.MutablePriorityQueue<String, String> queue = new PeerConnectionTester.MutablePriorityQueue<>(String::compareTo); final int threadCnt = 8; final int elemCnt = 1000; Runnable adder = () -> { try { System.out.println("Adding..."); for (int i = 0; i < elemCnt && !exception; i++) { queue.add("aaa" + i); if (i % 100 == 0) Thread.sleep(10); } System.out.println("Done."); } catch (Exception e) { exception = true; e.printStackTrace(); } }; ThreadGroup tg = new ThreadGroup("test"); Thread t1[] = new Thread[threadCnt]; for (int i = 0; i < t1.length; i++) { t1[i] = new Thread(tg, adder); t1[i].start(); } Runnable taker = () -> { try { System.out.println("Taking..."); for (int i = 0; i < elemCnt && !exception; i++) { queue.poll(1, TimeUnit.SECONDS); } System.out.println("OK: " + queue.size()); } catch (Exception e) { exception = true; e.printStackTrace(); } }; Thread t2[] = new Thread[threadCnt]; for (int i = 0; i < t2.length; i++) { t2[i] = new Thread(tg, taker); t2[i].start(); } for (Thread thread : t1) { thread.join(); } for (Thread thread : t2) { thread.join(); } if (exception) throw new RuntimeException("Test failed"); } }
2,827
29.408602
83
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/BlockReplayTest.java
package org.ethereum.datasource; import org.ethereum.core.Block; import org.ethereum.core.Genesis; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.db.IndexedBlockStore; import org.ethereum.db.TransactionStore; import org.ethereum.listener.BlockReplay; import org.ethereum.listener.EthereumListener; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import static java.math.BigInteger.ZERO; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; /** * @author alexbraz * @since 29/03/2019 */ public class BlockReplayTest { private static final Logger logger = LoggerFactory.getLogger("test"); BlockReplay replay; EthereumListener listener; private List<Block> blocks = new ArrayList<>(); private BigInteger totDifficulty = ZERO; Block genesis = Genesis.getInstance(); @Before public void setup() throws URISyntaxException, IOException { URL scenario1 = ClassLoader .getSystemResource("blockstore/load.dmp"); File file = new File(scenario1.toURI()); List<String> strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); IndexedBlockStore indexedBlockStore = indexedBlockStore = new IndexedBlockStore(); indexedBlockStore.init(new HashMapDB<byte[]>(), new HashMapDB<byte[]>()); TransactionStore txStore = new TransactionStore(new HashMapDB<>()); listener = mock(EthereumListener.class); replay = new BlockReplay(indexedBlockStore, txStore, listener, 0L); for (String blockRLP : strData) { Block block = new Block( Hex.decode(blockRLP)); if (block.getNumber() % 1000 == 0) logger.info("adding block.hash: [{}] block.number: [{}]", block.getShortHash(), block.getNumber()); blocks.add(block); totDifficulty = totDifficulty.add(block.getDifficultyBI()); indexedBlockStore.saveBlock(block, totDifficulty, true); } } @Test public void testReplayBlock() { IndexedBlockStore i = mock(IndexedBlockStore.class); when(i.getChainBlockByNumber(anyLong())).thenReturn(genesis); TransactionStore txStore = new TransactionStore(new HashMapDB<>()); replay = new BlockReplay(i, txStore, listener, 0L); replay.replay(); verify(listener, times(1)).onBlock(any()); } @Test public void testListenerNoConnection() { replay.onNoConnections(); verify(listener, times(1)).onNoConnections(); replay.onSyncDone(null); verify(listener, times(1)).onSyncDone(any()); replay.onNodeDiscovered(any()); verify(listener, times(1)).onNodeDiscovered(any()); replay.onEthStatusUpdated(any(), any()); verify(listener, times(1)).onEthStatusUpdated(any(), any()); replay.onHandShakePeer(any(), any()); verify(listener, times(1)).onHandShakePeer(any(), any()); replay.onPeerAddedToSyncPool(any()); verify(listener, times(1)).onPeerAddedToSyncPool(any()); replay.onPeerDisconnect(anyString(), anyLong()); verify(listener, times(1)).onPeerDisconnect(anyString(), anyLong()); replay.onPendingStateChanged(any()); verify(listener, times(1)).onPendingStateChanged(any()); replay.onPendingTransactionUpdate(any(), any(), any()); verify(listener, times(1)).onPendingTransactionUpdate(any(), any(), any()); replay.onRecvMessage(any(), any()); verify(listener, times(1)).onRecvMessage(any(), any()); replay.onTransactionExecuted(any()); verify(listener, times(1)).onTransactionExecuted(any()); replay.onSendMessage(any(), any()); verify(listener, times(1)).onSendMessage(any(), any()); replay.onVMTraceCreated(anyString(), anyString()); verify(listener, times(1)).onVMTraceCreated(anyString(), anyString()); } }
4,370
31.619403
90
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/BlockSerializerTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.db.IndexedBlockStore; import org.ethereum.db.IndexedBlockStore.BlockInfo; import org.ethereum.util.ByteUtil; import org.ethereum.util.FastByteComparisons; import org.junit.Ignore; import org.junit.Test; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import static org.ethereum.crypto.HashUtil.sha3; /** * Test for {@link IndexedBlockStore.BLOCK_INFO_SERIALIZER} */ public class BlockSerializerTest { private static final Random rnd = new Random(); private List<BlockInfo> generateBlockInfos(int count) { List<BlockInfo> blockInfos = new ArrayList<>(); for (int i = 0; i < count; i++) { BlockInfo blockInfo = new BlockInfo(); blockInfo.setHash(sha3(ByteUtil.intToBytes(i))); blockInfo.setTotalDifficulty(BigInteger.probablePrime(512, rnd)); blockInfo.setMainChain(rnd.nextBoolean()); blockInfos.add(blockInfo); } return blockInfos; } @Test public void testTest() { List<BlockInfo> blockInfoList = generateBlockInfos(100); byte[] data = IndexedBlockStore.BLOCK_INFO_SERIALIZER.serialize(blockInfoList); System.out.printf("Blocks total byte size: %s%n", data.length); List<BlockInfo> blockInfoList2 = IndexedBlockStore.BLOCK_INFO_SERIALIZER.deserialize(data); assert blockInfoList.size() == blockInfoList2.size(); for (int i = 0; i < blockInfoList2.size(); i++) { assert FastByteComparisons.equal(blockInfoList2.get(i).getHash(), blockInfoList.get(i).getHash()); assert blockInfoList2.get(i).getTotalDifficulty().compareTo(blockInfoList.get(i).getTotalDifficulty()) == 0; assert blockInfoList2.get(i).isMainChain() == blockInfoList.get(i).isMainChain(); } } @Test @Ignore public void testTime() { int BLOCKS = 100; int PASSES = 10_000; List<BlockInfo> blockInfoList = generateBlockInfos(BLOCKS); long s = System.currentTimeMillis(); for (int i = 0; i < PASSES; i++) { byte[] data = IndexedBlockStore.BLOCK_INFO_SERIALIZER.serialize(blockInfoList); List<BlockInfo> blockInfoList2 = IndexedBlockStore.BLOCK_INFO_SERIALIZER.deserialize(data); } long e = System.currentTimeMillis(); System.out.printf("Serialize/deserialize blocks per 1 ms: %s%n", PASSES * BLOCKS / (e - s)); } @Test(expected = RuntimeException.class) public void testNullTotalDifficulty() { BlockInfo blockInfo = new BlockInfo(); blockInfo.setMainChain(true); blockInfo.setTotalDifficulty(null); blockInfo.setHash(new byte[0]); byte[] data = IndexedBlockStore.BLOCK_INFO_SERIALIZER.serialize(Collections.singletonList(blockInfo)); List<BlockInfo> blockInfos = IndexedBlockStore.BLOCK_INFO_SERIALIZER.deserialize(data); } @Test(expected = RuntimeException.class) public void testNegativeTotalDifficulty() { BlockInfo blockInfo = new BlockInfo(); blockInfo.setMainChain(true); blockInfo.setTotalDifficulty(BigInteger.valueOf(-1)); blockInfo.setHash(new byte[0]); byte[] data = IndexedBlockStore.BLOCK_INFO_SERIALIZER.serialize(Collections.singletonList(blockInfo)); List<BlockInfo> blockInfos = IndexedBlockStore.BLOCK_INFO_SERIALIZER.deserialize(data); } @Test public void testZeroTotalDifficultyEmptyHash() { BlockInfo blockInfo = new BlockInfo(); blockInfo.setMainChain(true); blockInfo.setTotalDifficulty(BigInteger.ZERO); blockInfo.setHash(new byte[0]); byte[] data = IndexedBlockStore.BLOCK_INFO_SERIALIZER.serialize(Collections.singletonList(blockInfo)); List<BlockInfo> blockInfos = IndexedBlockStore.BLOCK_INFO_SERIALIZER.deserialize(data); assert blockInfos.size() == 1; BlockInfo actualBlockInfo = blockInfos.get(0); assert actualBlockInfo.isMainChain(); assert actualBlockInfo.getTotalDifficulty().compareTo(BigInteger.ZERO) == 0; assert actualBlockInfo.getHash().length == 0; } }
5,033
40.262295
120
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/AsyncWriteCacheTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.crypto.HashUtil; import org.ethereum.db.SlowHashMapDb; import org.ethereum.db.StateSource; import org.ethereum.util.ByteUtil; import org.ethereum.util.Utils; import org.junit.Ignore; import org.junit.Test; import java.util.Arrays; import java.util.Map; import static java.lang.Math.max; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.intToBytes; import static org.ethereum.util.ByteUtil.intsToBytes; import static org.spongycastle.util.encoders.Hex.decode; /** * Created by Anton Nashatyrev on 19.01.2017. */ public class AsyncWriteCacheTest { volatile boolean flushing; @Test public void simpleTest1() { final SlowHashMapDb<String> db = new SlowHashMapDb<String>().withDelay(100); AsyncWriteCache<byte[], String> cache = new AsyncWriteCache<byte[], String>(db) { @Override protected WriteCache<byte[], String> createCache(Source<byte[], String> source) { return new WriteCache.BytesKey<String>(source, WriteCache.CacheType.SIMPLE) { @Override public boolean flush() { flushing = true; System.out.println("Flushing started"); boolean ret = super.flush(); System.out.println("Flushing complete"); flushing = false; return ret; } }; } }; cache.put(decode("1111"), "1111"); cache.flush(); assert cache.get(decode("1111")) == "1111"; while (!flushing); System.out.println("get"); assert cache.get(decode("1111")) == "1111"; System.out.println("put"); cache.put(decode("2222"), "2222"); System.out.println("get"); assert flushing; while (flushing) { assert cache.get(decode("2222")) == "2222"; assert cache.get(decode("1111")) == "1111"; } assert cache.get(decode("2222")) == "2222"; assert cache.get(decode("1111")) == "1111"; cache.put(decode("1111"), "1112"); cache.flush(); assert cache.get(decode("1111")) == "1112"; assert cache.get(decode("2222")) == "2222"; while (!flushing); System.out.println("Second flush"); cache.flush(); System.out.println("Second flush complete"); assert cache.get(decode("1111")) == "1112"; assert cache.get(decode("2222")) == "2222"; System.out.println("put"); cache.put(decode("3333"), "3333"); assert cache.get(decode("1111")) == "1112"; assert cache.get(decode("2222")) == "2222"; assert cache.get(decode("3333")) == "3333"; System.out.println("Second flush"); cache.flush(); System.out.println("Second flush complete"); assert cache.get(decode("1111")) == "1112"; assert cache.get(decode("2222")) == "2222"; assert cache.get(decode("3333")) == "3333"; assert db.get(decode("1111")) == "1112"; assert db.get(decode("2222")) == "2222"; assert db.get(decode("3333")) == "3333"; } @Ignore @Test public void highLoadTest1() throws InterruptedException { final SlowHashMapDb<byte[]> db = new SlowHashMapDb<byte[]>() { @Override public void updateBatch(Map<byte[], byte[]> rows) { Utils.sleep(10000); super.updateBatch(rows); } }; StateSource stateSource = new StateSource(db, false); stateSource.getReadCache().withMaxCapacity(1); stateSource.put(sha3(intToBytes(1)), intToBytes(1)); stateSource.put(sha3(intToBytes(2)), intToBytes(2)); System.out.println("Flush..."); stateSource.flush(); System.out.println("Flush!"); Thread.sleep(100); System.out.println("Get..."); byte[] bytes1 = stateSource.get(sha3(intToBytes(1))); System.out.println("Get!: " + bytes1); byte[] bytes2 = stateSource.get(sha3(intToBytes(2))); System.out.println("Get!: " + bytes2); // int cnt = 0; // while(true) { // for (int i = 0; i < 1000; i++) { // stateSource.put(sha3(intToBytes(cnt)), intToBytes(cnt)); // cnt++; // } // // stateSource.getWriteCache().flush(); // //// for (int i = 0; i < 200; i++) { //// stateSource.put(sha3(intToBytes(cnt)), intToBytes(cnt)); //// cnt++; //// } // // Thread.sleep(800); // // for (int i = max(0, cnt - 1000); i < cnt; i++) { // // byte[] bytes = stateSource.get(sha3(intToBytes(i))); // assert Arrays.equals(bytes, intToBytes(i)); // } // System.err.println("Iteration done"); // } // // } }
5,821
32.653179
93
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/RocksDbDataSourceTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.datasource.rocksdb.RocksDbDataSource; import org.junit.Ignore; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import java.util.HashMap; import java.util.Map; import static org.ethereum.TestUtils.randomBytes; import static org.junit.Assert.*; @Ignore public class RocksDbDataSourceTest { @Test public void testBatchUpdating() { RocksDbDataSource dataSource = new RocksDbDataSource("test"); dataSource.reset(); final int batchSize = 100; Map<byte[], byte[]> batch = createBatch(batchSize); dataSource.updateBatch(batch); assertEquals(batchSize, dataSource.keys().size()); for (Map.Entry<byte[], byte[]> e : batch.entrySet()) { assertArrayEquals(e.getValue(), dataSource.get(e.getKey())); assertArrayEquals(e.getValue(), dataSource.prefixLookup(e.getKey(), NodeKeyCompositor.PREFIX_BYTES)); } dataSource.close(); } @Test public void testPutting() { RocksDbDataSource dataSource = new RocksDbDataSource("test"); dataSource.reset(); byte[] key = randomBytes(32); dataSource.put(key, randomBytes(32)); assertNotNull(dataSource.get(key)); assertEquals(1, dataSource.keys().size()); dataSource.close(); } @Test public void testPrefixLookup() { RocksDbDataSource dataSource = new RocksDbDataSource("test"); dataSource.reset(); byte[] k1 = Hex.decode("a9539c810cc2e8fa20785bdd78ec36cc1dab4b41f0d531e80a5e5fd25c3037ee"); byte[] k2 = Hex.decode("b25e1b5be78dbadf6c4e817c6d170bbb47e9916f8f6cc4607c5f3819ce98497b"); byte[] v1, v2, v3; v3 = v1 = "v1".getBytes(); v2 = "v2".getBytes(); dataSource.put(k1, v1); assertArrayEquals(v1, dataSource.get(k1)); assertArrayEquals(v1, dataSource.prefixLookup(k1, NodeKeyCompositor.PREFIX_BYTES)); dataSource.put(k2, v2); assertArrayEquals(v2, dataSource.get(k2)); assertArrayEquals(v1, dataSource.prefixLookup(k1, NodeKeyCompositor.PREFIX_BYTES)); assertArrayEquals(v2, dataSource.prefixLookup(k2, NodeKeyCompositor.PREFIX_BYTES)); byte[] k3 = Hex.decode("a9539c810cc2e8fa20785bdd78ec36ccb25e1b5be78dbadf6c4e817c6d170bbb"); byte[] k4 = Hex.decode("a9539c810cc2e8fa20785bdd78ec36cdb25e1b5be78dbadf6c4e817c6d170bbb"); dataSource.put(k3, v3); dataSource.put(k4, v3); assertArrayEquals(v3, dataSource.get(k3)); assertArrayEquals(v3, dataSource.get(k4)); assertArrayEquals(v1, dataSource.prefixLookup(k1, NodeKeyCompositor.PREFIX_BYTES)); assertArrayEquals(v2, dataSource.prefixLookup(k2, NodeKeyCompositor.PREFIX_BYTES)); assertArrayEquals(v3, dataSource.prefixLookup(k3, NodeKeyCompositor.PREFIX_BYTES)); assertArrayEquals(v3, dataSource.prefixLookup(Hex.decode("a9539c810cc2e8fa20785bdd78ec36cc00000000000000000000000000000000"), NodeKeyCompositor.PREFIX_BYTES)); assertArrayEquals(v3, dataSource.prefixLookup(Hex.decode("a9539c810cc2e8fa20785bdd78ec36ccb25e1b5be78dbadf6c4e817c6d170bb0"), NodeKeyCompositor.PREFIX_BYTES)); assertNull(dataSource.prefixLookup(Hex.decode("a9539c810cc2e8fa20785bdd78ec36c000000000000000000000000000000000"), NodeKeyCompositor.PREFIX_BYTES)); dataSource.delete(k2); assertNull(dataSource.prefixLookup(k2, NodeKeyCompositor.PREFIX_BYTES)); assertArrayEquals(v3, dataSource.get(k3)); dataSource.delete(k3); assertNull(dataSource.prefixLookup(k2, NodeKeyCompositor.PREFIX_BYTES)); assertArrayEquals(v1, dataSource.get(k1)); dataSource.delete(k1); assertNull(dataSource.prefixLookup(k1, NodeKeyCompositor.PREFIX_BYTES)); assertNull(dataSource.prefixLookup(k2, NodeKeyCompositor.PREFIX_BYTES)); assertNull(dataSource.prefixLookup(k3, NodeKeyCompositor.PREFIX_BYTES)); assertNull(dataSource.get(k1)); assertNull(dataSource.get(k2)); assertNull(dataSource.get(k3)); assertArrayEquals(v3, dataSource.get(k4)); dataSource.put(Hex.decode("df92d643f6f19067a6a1cac3c37332d1631be8a462f0c2c41efb60078515ed50"), v1); assertArrayEquals(dataSource.prefixLookup(Hex.decode("df92d643f6f19067a6a1cac3c37332d1d1b3ede7e2015c259e493a1bff2ed58c"), NodeKeyCompositor.PREFIX_BYTES), v1); dataSource.close(); } private static Map<byte[], byte[]> createBatch(int batchSize) { HashMap<byte[], byte[]> result = new HashMap<>(); for (int i = 0; i < batchSize; i++) { result.put(randomBytes(32), randomBytes(32)); } return result; } }
5,552
38.105634
167
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/CountingBytesSourceTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.vm.DataWord; import org.junit.Before; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.longToBytes; import static org.junit.Assert.*; /** * Test for {@link CountingBytesSource} */ public class CountingBytesSourceTest { private Source<byte[], byte[]> src; private byte[] intToKey(int i) { return sha3(longToBytes(i)); } private byte[] intToValue(int i) { return (DataWord.of(i)).getData(); } private String str(Object obj) { if (obj == null) return null; return Hex.toHexString((byte[]) obj); } @Before public void setUp() { Source<byte[], byte[]> parentSrc = new HashMapDB<>(); this.src = new CountingBytesSource(parentSrc); } @Test(expected = NullPointerException.class) public void testKeyNull() { src.put(null, null); } @Test public void testValueNull() { src.put(intToKey(0), null); assertNull(src.get(intToKey(0))); } @Test public void testDelete() { src.put(intToKey(0), intToValue(0)); src.delete(intToKey(0)); assertNull(src.get(intToKey(0))); src.put(intToKey(0), intToValue(0)); src.put(intToKey(0), intToValue(0)); src.delete(intToKey(0)); assertEquals(str(intToValue(0)), str(src.get(intToKey(0)))); src.delete(intToKey(0)); assertNull(src.get(intToKey(0))); src.put(intToKey(1), intToValue(1)); src.put(intToKey(1), intToValue(1)); src.put(intToKey(1), null); assertEquals(str(intToValue(1)), str(src.get(intToKey(1)))); src.put(intToKey(1), null); assertNull(src.get(intToKey(1))); src.put(intToKey(1), intToValue(1)); src.put(intToKey(1), intToValue(2)); src.delete(intToKey(1)); assertEquals(str(intToValue(2)), str(src.get(intToKey(1)))); src.delete(intToKey(1)); assertNull(src.get(intToKey(1))); } @Test public void testALotRefs() { for (int i = 0; i < 100_000; ++i) { src.put(intToKey(0), intToValue(0)); } for (int i = 0; i < 99_999; ++i) { src.delete(intToKey(0)); assertEquals(str(intToValue(0)), str(src.get(intToKey(0)))); } src.delete(intToKey(0)); assertNull(src.get(intToKey(0))); } @Test public void testFlushDoNothing() { for (int i = 0; i < 100; ++i) { for (int j = 0; j <= i; ++j) { src.put(intToKey(i), intToValue(i)); } } assertEquals(str(intToValue(0)), str(src.get(intToKey(0)))); assertEquals(str(intToValue(99)), str(src.get(intToKey(99)))); assertFalse(src.flush()); assertEquals(str(intToValue(0)), str(src.get(intToKey(0)))); assertEquals(str(intToValue(99)), str(src.get(intToKey(99)))); } @Test public void testEmptyValue() { byte[] value = new byte[0]; src.put(intToKey(0), value); src.put(intToKey(0), value); src.delete(intToKey(0)); assertEquals(str(value), str(src.get(intToKey(0)))); src.delete(intToKey(0)); assertNull(src.get(intToKey(0))); } }
4,203
30.140741
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/TrieNodeSourceTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.core.Repository; import org.ethereum.crypto.HashUtil; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.db.RepositoryRoot; import org.ethereum.db.StateSource; import org.ethereum.db.prune.Pruner; import org.ethereum.db.prune.Segment; import org.ethereum.vm.DataWord; import org.junit.Before; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import java.util.concurrent.ExecutionException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * @author Mikhail Kalinin * @since 05.12.2017 */ public class TrieNodeSourceTest { Source<byte[], byte[]> trieNodeSource; StateSource stateSource; Repository repository; HashMapDB<byte[]> db; AsyncWriteCache<byte[], byte[]> stateWriteCache; @Before public void setup() { db = new HashMapDB<>(); stateSource = new StateSource(db, true); stateWriteCache = (AsyncWriteCache<byte[], byte[]>) stateSource.getWriteCache(); trieNodeSource = new PrefixLookupSource<>(db, NodeKeyCompositor.PREFIX_BYTES); repository = new RepositoryRoot(stateSource); } @Test public void testContractStorage() throws ExecutionException, InterruptedException { byte[] addr1 = Hex.decode("5c543e7ae0a1104f78406c340e9c64fd9fce5170"); byte[] addr2 = Hex.decode("8bccc9ba2e5706e24a36dda02ca2a846e39a7bbf"); byte[] k1 = HashUtil.sha3("key1".getBytes()), v1 = "value1".getBytes(); assertNull(trieNodeSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055"))); repository.addStorageRow(addr1, DataWord.of(k1), DataWord.of(v1)); repository.addStorageRow(addr2, DataWord.of(k1), DataWord.of(v1)); flushChanges(); // Logically we must get a node with key 4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055 // and reference counter equal 2, cause both addresses have that node in their storage. // Technically we get two nodes with keys produced by NodeKeyCompositor: // 4b7fc4d98630bae2133ad002f743124f01bb4fbefc0a1a699cd4c20899a2877f // 4b7fc4d98630bae2133ad002f743124fafe15fa1326e1c0fcd4b67a53eee9537 // values they hold are equal, logically it is the same value assertNull(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055"))); assertEquals("eaa1202cc45dfd615ef5099974383a7c13606186f629a558453bdb2985d005ad174e73878676616c756531", Hex.toHexString(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f01bb4fbefc0a1a699cd4c20899a2877f")))); assertEquals("eaa1202cc45dfd615ef5099974383a7c13606186f629a558453bdb2985d005ad174e73878676616c756531", Hex.toHexString(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124fafe15fa1326e1c0fcd4b67a53eee9537")))); // trieNodeSource must return that value supplied with origin key 4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055 // it does a prefix search by only first 16 bytes of the key assertEquals("eaa1202cc45dfd615ef5099974383a7c13606186f629a558453bdb2985d005ad174e73878676616c756531", Hex.toHexString(trieNodeSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055")))); // one of that storage rows is gonna be removed repository.addStorageRow(addr1, DataWord.of(k1), DataWord.ZERO); flushChanges(); // state doesn't contain a copy of node that belongs to addr1 assertNull(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f01bb4fbefc0a1a699cd4c20899a2877f"))); // but still able to pick addr2 value assertEquals("eaa1202cc45dfd615ef5099974383a7c13606186f629a558453bdb2985d005ad174e73878676616c756531", Hex.toHexString(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124fafe15fa1326e1c0fcd4b67a53eee9537")))); // trieNodeSource still able to pick a value by origin key assertEquals("eaa1202cc45dfd615ef5099974383a7c13606186f629a558453bdb2985d005ad174e73878676616c756531", Hex.toHexString(trieNodeSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055")))); // remove a copy of value stick to addr2 repository.addStorageRow(addr2, DataWord.of(k1), DataWord.ZERO); flushChanges(); // no source can resolve any of those keys assertNull(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f01bb4fbefc0a1a699cd4c20899a2877f"))); assertNull(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124fafe15fa1326e1c0fcd4b67a53eee9537"))); assertNull(trieNodeSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055"))); } @Test public void testContractCode() throws ExecutionException, InterruptedException { byte[] addr1 = Hex.decode("5c543e7ae0a1104f78406c340e9c64fd9fce5170"); byte[] addr2 = Hex.decode("8bccc9ba2e5706e24a36dda02ca2a846e39a7bbf"); byte[] code = "contract Foo {}".getBytes(); byte[] codeHash = HashUtil.sha3(code); repository.saveCode(addr1, code); flushChanges(); assertNull(stateSource.get(codeHash)); assertEquals(Hex.toHexString(code), Hex.toHexString(stateSource.get(Hex.decode("0827ccfec1b70192ffadbc46e945a9af01bb4fbefc0a1a699cd4c20899a2877f")))); assertNull(stateSource.get(Hex.decode("0827ccfec1b70192ffadbc46e945a9afafe15fa1326e1c0fcd4b67a53eee9537"))); assertEquals(Hex.toHexString(code), Hex.toHexString(trieNodeSource.get(codeHash))); repository.saveCode(addr2, code); flushChanges(); assertNull(stateSource.get(codeHash)); assertEquals(Hex.toHexString(code), Hex.toHexString(stateSource.get(Hex.decode("0827ccfec1b70192ffadbc46e945a9af01bb4fbefc0a1a699cd4c20899a2877f")))); assertEquals(Hex.toHexString(code), Hex.toHexString(stateSource.get(Hex.decode("0827ccfec1b70192ffadbc46e945a9afafe15fa1326e1c0fcd4b67a53eee9537")))); assertEquals(Hex.toHexString(code), Hex.toHexString(trieNodeSource.get(codeHash))); } private void flushChanges() throws ExecutionException, InterruptedException { repository.commit(); stateSource.getJournalSource().commitUpdates(HashUtil.EMPTY_DATA_HASH); Pruner pruner = new Pruner(stateSource.getJournalSource().getJournal(), stateSource.getNoJournalSource()); pruner.init(HashUtil.EMPTY_DATA_HASH); Segment segment = new Segment(0, HashUtil.EMPTY_DATA_HASH, HashUtil.EMPTY_DATA_HASH); segment.startTracking() .addMain(1, HashUtil.EMPTY_DATA_HASH, HashUtil.EMPTY_DATA_HASH) .commit(); pruner.prune(segment); stateWriteCache.flipStorage(); stateWriteCache.flushAsync().get(); } }
7,823
47
138
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/CountingQuotientFilterTest.java
package org.ethereum.datasource; import org.ethereum.datasource.CountingQuotientFilter; import org.junit.Ignore; import org.junit.Test; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.intToBytes; /** * @author Mikhail Kalinin * @since 15.02.2018 */ public class CountingQuotientFilterTest { @Ignore @Test public void perfTest() { CountingQuotientFilter f = CountingQuotientFilter.create(50_000_000, 100_000); long s = System.currentTimeMillis(); for (int i = 0; i < 5_000_000; i++) { f.insert(sha3(intToBytes(i))); if (i % 10 == 0) f.insert(sha3(intToBytes(0))); if (i > 100_000 && i % 2 == 0) { f.remove(sha3(intToBytes(i - 100_000))); } if (i % 10000 == 0) { System.out.println(i + ": " + (System.currentTimeMillis() - s)); s = System.currentTimeMillis(); } } } @Test public void simpleTest() { CountingQuotientFilter f = CountingQuotientFilter.create(1_000_000, 1_000_000); f.insert(sha3(intToBytes(0))); assert f.maybeContains(sha3(intToBytes(0))); f.insert(sha3(intToBytes(1))); f.remove(sha3(intToBytes(0))); assert f.maybeContains(sha3(intToBytes(1))); assert !f.maybeContains(sha3(intToBytes(0))); for (int i = 0; i < 10; i++) { f.insert(sha3(intToBytes(2))); } assert f.maybeContains(sha3(intToBytes(2))); for (int i = 0; i < 8; i++) { f.remove(sha3(intToBytes(2))); } assert f.maybeContains(sha3(intToBytes(2))); f.remove(sha3(intToBytes(2))); assert f.maybeContains(sha3(intToBytes(2))); f.remove(sha3(intToBytes(2))); assert !f.maybeContains(sha3(intToBytes(2))); f.remove(sha3(intToBytes(2))); // check that it breaks nothing assert !f.maybeContains(sha3(intToBytes(2))); } @Test // elements have same fingerprint, but different hash public void softCollisionTest() { CountingQuotientFilter f = CountingQuotientFilter.create(1_000_000, 1_000_000); f.insert(-1L); f.insert(Long.MAX_VALUE); f.insert(Long.MAX_VALUE - 1); assert f.maybeContains(-1L); assert f.maybeContains(Long.MAX_VALUE); assert f.maybeContains(Long.MAX_VALUE - 1); f.remove(-1L); assert f.maybeContains(Long.MAX_VALUE); assert f.maybeContains(Long.MAX_VALUE - 1); f.remove(Long.MAX_VALUE); assert f.maybeContains(Long.MAX_VALUE - 1); f.remove(Long.MAX_VALUE - 1); assert !f.maybeContains(-1L); assert !f.maybeContains(Long.MAX_VALUE); assert !f.maybeContains(Long.MAX_VALUE - 1); } @Test // elements have same fingerprint, but different hash public void softCollisionTest2() { CountingQuotientFilter f = CountingQuotientFilter.create(1_000_000, 1_000_000); f.insert(0xE0320F4F9B35343FL); f.insert(0xFF2D4CCA9B353435L); f.insert(0xFF2D4CCA9B353435L); f.remove(0xE0320F4F9B35343FL); f.remove(0xFF2D4CCA9B353435L); assert f.maybeContains(0xFF2D4CCA9B353435L); } @Test // elements have same hash public void hardCollisionTest() { CountingQuotientFilter f = CountingQuotientFilter.create(10_000_000, 10_000_000); f.insert(Long.MAX_VALUE); f.insert(Long.MAX_VALUE); f.insert(Long.MAX_VALUE); assert f.maybeContains(Long.MAX_VALUE); f.remove(Long.MAX_VALUE); f.remove(Long.MAX_VALUE); assert f.maybeContains(Long.MAX_VALUE); f.remove(-1L); assert !f.maybeContains(-1L); } @Test public void resizeTest() { CountingQuotientFilter f = CountingQuotientFilter.create(1_000, 1_000); f.insert(Long.MAX_VALUE); f.insert(Long.MAX_VALUE); f.insert(Long.MAX_VALUE); f.insert(Long.MAX_VALUE - 1); for (int i = 100_000; i < 200_000; i++) { f.insert(intToBytes(i)); } assert f.maybeContains(Long.MAX_VALUE); for (int i = 100_000; i < 200_000; i++) { assert f.maybeContains(intToBytes(i)); } assert f.maybeContains(Long.MAX_VALUE); assert f.maybeContains(Long.MAX_VALUE - 1); f.remove(Long.MAX_VALUE); f.remove(Long.MAX_VALUE); f.remove(Long.MAX_VALUE - 1); assert f.maybeContains(Long.MAX_VALUE); f.remove(Long.MAX_VALUE); assert !f.maybeContains(Long.MAX_VALUE); f.remove(Long.MAX_VALUE - 1); assert !f.maybeContains(Long.MAX_VALUE - 1); } }
4,736
28.981013
89
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/LevelDbDataSourceTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.datasource.leveldb.LevelDbDataSource; import org.junit.Ignore; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.ethereum.TestUtils.randomBytes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @Ignore public class LevelDbDataSourceTest { @Test public void testBatchUpdating() { LevelDbDataSource dataSource = new LevelDbDataSource("test"); dataSource.init(DbSettings.DEFAULT); final int batchSize = 100; Map<byte[], byte[]> batch = createBatch(batchSize); dataSource.updateBatch(batch); assertEquals(batchSize, dataSource.keys().size()); dataSource.close(); } @Test public void testPutting() { LevelDbDataSource dataSource = new LevelDbDataSource("test"); dataSource.init(DbSettings.DEFAULT); byte[] key = randomBytes(32); dataSource.put(key, randomBytes(32)); assertNotNull(dataSource.get(key)); assertEquals(1, dataSource.keys().size()); dataSource.close(); } private static Map<byte[], byte[]> createBatch(int batchSize) { HashMap<byte[], byte[]> result = new HashMap<>(); for (int i = 0; i < batchSize; i++) { result.put(randomBytes(32), randomBytes(32)); } return result; } }
2,232
30.450704
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/WriteCacheTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.vm.DataWord; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.longToBytes; import static org.junit.Assert.*; /** * Testing {@link WriteCache} */ public class WriteCacheTest { private byte[] intToKey(int i) { return sha3(longToBytes(i)); } private byte[] intToValue(int i) { return (DataWord.of(i)).getData(); } private String str(Object obj) { if (obj == null) return null; return Hex.toHexString((byte[]) obj); } @Test public void testSimple() { Source<byte[], byte[]> src = new HashMapDB<>(); WriteCache<byte[], byte[]> writeCache = new WriteCache.BytesKey<>(src, WriteCache.CacheType.SIMPLE); for (int i = 0; i < 10_000; ++i) { writeCache.put(intToKey(i), intToValue(i)); } // Everything is cached assertEquals(str(intToValue(0)), str(writeCache.getCached(intToKey(0)).value())); assertEquals(str(intToValue(9_999)), str(writeCache.getCached(intToKey(9_999)).value())); // Everything is flushed writeCache.flush(); assertNull(writeCache.getCached(intToKey(0))); assertNull(writeCache.getCached(intToKey(9_999))); assertEquals(str(intToValue(9_999)), str(writeCache.get(intToKey(9_999)))); assertEquals(str(intToValue(0)), str(writeCache.get(intToKey(0)))); // Get not caches, only write cache assertNull(writeCache.getCached(intToKey(0))); // Deleting key that is currently in cache writeCache.put(intToKey(0), intToValue(12345)); assertEquals(str(intToValue(12345)), str(writeCache.getCached(intToKey(0)).value())); writeCache.delete(intToKey(0)); assertTrue(null == writeCache.getCached(intToKey(0)) || null == writeCache.getCached(intToKey(0)).value()); assertEquals(str(intToValue(0)), str(src.get(intToKey(0)))); writeCache.flush(); assertNull(src.get(intToKey(0))); // Deleting key that is not currently in cache assertTrue(null == writeCache.getCached(intToKey(1)) || null == writeCache.getCached(intToKey(1)).value()); assertEquals(str(intToValue(1)), str(src.get(intToKey(1)))); writeCache.delete(intToKey(1)); assertTrue(null == writeCache.getCached(intToKey(1)) || null == writeCache.getCached(intToKey(1)).value()); assertEquals(str(intToValue(1)), str(src.get(intToKey(1)))); writeCache.flush(); assertNull(src.get(intToKey(1))); } @Test public void testCounting() { Source<byte[], byte[]> parentSrc = new HashMapDB<>(); Source<byte[], byte[]> src = new CountingBytesSource(parentSrc); WriteCache<byte[], byte[]> writeCache = new WriteCache.BytesKey<>(src, WriteCache.CacheType.COUNTING); for (int i = 0; i < 100; ++i) { for (int j = 0; j <= i; ++j) { writeCache.put(intToKey(i), intToValue(i)); } } // Everything is cached assertEquals(str(intToValue(0)), str(writeCache.getCached(intToKey(0)).value())); assertEquals(str(intToValue(99)), str(writeCache.getCached(intToKey(99)).value())); // Everything is flushed writeCache.flush(); assertNull(writeCache.getCached(intToKey(0))); assertNull(writeCache.getCached(intToKey(99))); assertEquals(str(intToValue(99)), str(writeCache.get(intToKey(99)))); assertEquals(str(intToValue(0)), str(writeCache.get(intToKey(0)))); // Deleting key which has 1 ref writeCache.delete(intToKey(0)); // for counting cache we return the cached value even if // it was deleted (once or several times) as we don't know // how many 'instances' are left behind // but when we delete entry which is not in the cache we don't // want to spend unnecessary time for getting the value from // underlying storage, so getCached may return null. // get() should work as expected // assertEquals(str(intToValue(0)), str(writeCache.getCached(intToKey(0)))); assertEquals(str(intToValue(0)), str(src.get(intToKey(0)))); writeCache.flush(); assertNull(writeCache.getCached(intToKey(0))); assertNull(src.get(intToKey(0))); // Deleting key which has 2 refs writeCache.delete(intToKey(1)); writeCache.flush(); assertEquals(str(intToValue(1)), str(writeCache.get(intToKey(1)))); writeCache.delete(intToKey(1)); writeCache.flush(); assertNull(writeCache.get(intToKey(1))); } @Test public void testWithSizeEstimator() { Source<byte[], byte[]> src = new HashMapDB<>(); WriteCache<byte[], byte[]> writeCache = new WriteCache.BytesKey<>(src, WriteCache.CacheType.SIMPLE); writeCache.withSizeEstimators(MemSizeEstimator.ByteArrayEstimator, MemSizeEstimator.ByteArrayEstimator); assertEquals(0, writeCache.estimateCacheSize()); writeCache.put(intToKey(0), intToValue(0)); assertNotEquals(0, writeCache.estimateCacheSize()); long oneObjSize = writeCache.estimateCacheSize(); for (int i = 0; i < 100; ++i) { for (int j = 0; j <= i; ++j) { writeCache.put(intToKey(i), intToValue(i)); } } assertEquals(oneObjSize * 100, writeCache.estimateCacheSize()); writeCache.flush(); assertEquals(0, writeCache.estimateCacheSize()); } }
6,470
40.480769
115
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/BloomFilterTest.java
package org.ethereum.datasource; import org.junit.Test; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.UUID; import static org.junit.Assert.*; /** * The class mostly borrowed from http://github.com/magnuss/java-bloomfilter * * @author Magnus Skjegstad <magnus@skjegstad.com> */ public class BloomFilterTest { static Random r = new Random(); public static byte[] getBytesFromUUID(UUID uuid) { ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return bb.array(); } @Test public void testConstructorCNK() throws Exception { System.out.println("BloomFilter(c,n,k)"); for (int i = 0; i < 10000; i++) { double c = r.nextInt(20) + 1; int n = r.nextInt(10000) + 1; int k = r.nextInt(20) + 1; BloomFilter bf = new BloomFilter(c, n, k); assertEquals(bf.getK(), k); assertEquals(bf.getExpectedBitsPerElement(), c, 0); assertEquals(bf.getExpectedNumberOfElements(), n); assertEquals(bf.size(), c*n, 0); } } /** * Test of equals method, of class BloomFilter. * @throws UnsupportedEncodingException */ @Test public void testEquals() throws UnsupportedEncodingException { System.out.println("equals"); BloomFilter instance1 = new BloomFilter(1000, 100); BloomFilter instance2 = new BloomFilter(1000, 100); for (int i = 0; i < 100; i++) { byte[] val = UUID.randomUUID().toString().getBytes("UTF-8"); instance1.add(val); instance2.add(val); } assert(instance1.equals(instance2)); assert(instance2.equals(instance1)); byte[] anotherEntryByteArray = "Another Entry".getBytes("UTF-8"); instance1.add(anotherEntryByteArray); // make instance1 and instance2 different before clearing instance1.clear(); instance2.clear(); assert(instance1.equals(instance2)); assert(instance2.equals(instance1)); for (int i = 0; i < 100; i++) { byte[] val = UUID.randomUUID().toString().getBytes("UTF-8"); instance1.add(val); instance2.add(val); } assertTrue(instance1.equals(instance2)); assertTrue(instance2.equals(instance1)); } /** * Test of hashCode method, of class BloomFilter. * @throws UnsupportedEncodingException */ @Test public void testHashCode() throws UnsupportedEncodingException { System.out.println("hashCode"); BloomFilter instance1 = new BloomFilter(1000, 100); BloomFilter instance2 = new BloomFilter(1000, 100); assertTrue(instance1.hashCode() == instance2.hashCode()); for (int i = 0; i < 100; i++) { byte[] val = UUID.randomUUID().toString().getBytes("UTF-8"); instance1.add(val); instance2.add(val); } assertTrue(instance1.hashCode() == instance2.hashCode()); instance1.clear(); instance2.clear(); assertTrue(instance1.hashCode() == instance2.hashCode()); instance1 = new BloomFilter(100, 10); instance2 = new BloomFilter(100, 9); assertFalse(instance1.hashCode() == instance2.hashCode()); instance1 = new BloomFilter(100, 10); instance2 = new BloomFilter(99, 9); assertFalse(instance1.hashCode() == instance2.hashCode()); instance1 = new BloomFilter(100, 10); instance2 = new BloomFilter(50, 10); assertFalse(instance1.hashCode() == instance2.hashCode()); } /** * Test of expectedFalsePositiveProbability method, of class BloomFilter. */ @Test public void testExpectedFalsePositiveProbability() { // These probabilities are taken from the bloom filter probability table at // http://pages.cs.wisc.edu/~cao/papers/summary-cache/node8.html System.out.println("expectedFalsePositiveProbability"); BloomFilter instance = new BloomFilter(1000, 100); double expResult = 0.00819; // m/n=10, k=7 double result = instance.expectedFalsePositiveProbability(); assertEquals(instance.getK(), 7); assertEquals(expResult, result, 0.000009); instance = new BloomFilter(100, 10); expResult = 0.00819; // m/n=10, k=7 result = instance.expectedFalsePositiveProbability(); assertEquals(instance.getK(), 7); assertEquals(expResult, result, 0.000009); instance = new BloomFilter(20, 10); expResult = 0.393; // m/n=2, k=1 result = instance.expectedFalsePositiveProbability(); assertEquals(1, instance.getK()); assertEquals(expResult, result, 0.0005); instance = new BloomFilter(110, 10); expResult = 0.00509; // m/n=11, k=8 result = instance.expectedFalsePositiveProbability(); assertEquals(8, instance.getK()); assertEquals(expResult, result, 0.00001); } /** * Test of clear method, of class BloomFilter. */ @Test public void testClear() { System.out.println("clear"); BloomFilter instance = new BloomFilter(1000, 100); for (int i = 0; i < instance.size(); i++) instance.setBit(i, true); instance.clear(); for (int i = 0; i < instance.size(); i++) assertSame(instance.getBit(i), false); } /** * Test of add method, of class BloomFilter. * @throws Exception */ @Test public void testAdd() throws Exception { System.out.println("add"); BloomFilter instance = new BloomFilter(1000, 100); for (int i = 0; i < 100; i++) { byte[] bytes = getBytesFromUUID(UUID.randomUUID()); instance.add(bytes); assert(instance.contains(bytes)); } } /** * Test of contains method, of class BloomFilter. * @throws Exception */ @Test public void testContains() throws Exception { System.out.println("contains"); BloomFilter instance = new BloomFilter(10000, 10); for (int i = 0; i < 10; i++) { byte[] bytes = getBytesFromUUID(UUID.randomUUID()); instance.add(bytes); assert(instance.contains(bytes)); } assertFalse(instance.contains(UUID.randomUUID().toString().getBytes("UTF-8"))); } /** * Test of getBit method, of class BloomFilter. */ @Test public void testGetBit() { System.out.println("getBit"); BloomFilter instance = new BloomFilter(1000, 100); Random r = new Random(); for (int i = 0; i < 100; i++) { boolean b = r.nextBoolean(); instance.setBit(i, b); assertSame(instance.getBit(i), b); } } /** * Test of setBit method, of class BloomFilter. */ @Test public void testSetBit() { System.out.println("setBit"); BloomFilter instance = new BloomFilter(1000, 100); Random r = new Random(); for (int i = 0; i < 100; i++) { instance.setBit(i, true); assertSame(instance.getBit(i), true); } for (int i = 0; i < 100; i++) { instance.setBit(i, false); assertSame(instance.getBit(i), false); } } /** * Test of size method, of class BloomFilter. */ @Test public void testSize() { System.out.println("size"); for (int i = 100; i < 1000; i++) { BloomFilter instance = new BloomFilter(i, 10); assertEquals(instance.size(), i); } } /** Test error rate * * @throws UnsupportedEncodingException */ @Test public void testFalsePositiveRate1() throws UnsupportedEncodingException { // Numbers are from // http://pages.cs.wisc.edu/~cao/papers/summary-cache/node8.html System.out.println("falsePositiveRate1"); for (int j = 10; j < 21; j++) { System.out.print(j-9 + "/11"); List<byte[]> v = new ArrayList<byte[]>(); BloomFilter instance = new BloomFilter(100*j,100); for (int i = 0; i < 100; i++) { byte[] bytes = new byte[100]; r.nextBytes(bytes); v.add(bytes); } for (byte[] bytes : v) { instance.add(bytes); } long f = 0; double tests = 300000; for (int i = 0; i < tests; i++) { byte[] bytes = new byte[100]; r.nextBytes(bytes); if (instance.contains(bytes)) { if (!v.contains(bytes)) { f++; } } } double ratio = f / tests; System.out.println(" - got " + ratio + ", math says " + instance.expectedFalsePositiveProbability()); assertEquals(instance.expectedFalsePositiveProbability(), ratio, 0.01); } } /** Test for correct k **/ @Test public void testGetK() { // Numbers are from http://pages.cs.wisc.edu/~cao/papers/summary-cache/node8.html System.out.println("testGetK"); BloomFilter instance = null; instance = new BloomFilter(2, 1); assertEquals(1, instance.getK()); instance = new BloomFilter(3, 1); assertEquals(2, instance.getK()); instance = new BloomFilter(4, 1); assertEquals(3, instance.getK()); instance = new BloomFilter(5, 1); assertEquals(3, instance.getK()); instance = new BloomFilter(6, 1); assertEquals(4, instance.getK()); instance = new BloomFilter(7, 1); assertEquals(5, instance.getK()); instance = new BloomFilter(8, 1); assertEquals(6, instance.getK()); instance = new BloomFilter(9, 1); assertEquals(6, instance.getK()); instance = new BloomFilter(10, 1); assertEquals(7, instance.getK()); instance = new BloomFilter(11, 1); assertEquals(8, instance.getK()); instance = new BloomFilter(12, 1); assertEquals(8, instance.getK()); } /** * Test of contains method, of class BloomFilter. */ @Test public void testContains_GenericType() throws UnsupportedEncodingException { System.out.println("contains"); int items = 100; BloomFilter instance = new BloomFilter(0.01, items); for (int i = 0; i < items; i++) { byte[] b = UUID.randomUUID().toString().getBytes("UTF-8"); instance.add(b); assertTrue(instance.contains(b)); } } /** * Test of contains method, of class BloomFilter. */ @Test public void testContains_byteArr() { System.out.println("contains"); int items = 100; BloomFilter instance = new BloomFilter(0.01, items); for (int i = 0; i < items; i++) { byte[] bytes = new byte[500]; r.nextBytes(bytes); instance.add(bytes); assertTrue(instance.contains(bytes)); } } /** * Test of count method, of class BloomFilter. */ @Test public void testCount() throws UnsupportedEncodingException { System.out.println("count"); int expResult = 100; BloomFilter instance = new BloomFilter(0.01, expResult); for (int i = 0; i < expResult; i++) { byte[] bytes = new byte[100]; r.nextBytes(bytes); instance.add(bytes); } int result = instance.count(); assertEquals(expResult, result); instance = new BloomFilter(0.01, expResult); for (int i = 0; i < expResult; i++) { instance.add(UUID.randomUUID().toString().getBytes("UTF-8")); } result = instance.count(); assertEquals(expResult, result); } }
12,178
29.989822
113
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/JournalPruneTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.crypto.HashUtil; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.db.prune.Pruner; import org.ethereum.db.prune.Segment; import org.ethereum.util.ByteUtil; import org.junit.Test; import java.util.Collections; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Created by Anton Nashatyrev on 27.07.2016. */ public class JournalPruneTest { class StringJDS extends JournalSource<byte[]> { final HashMapDB<byte[]> mapDB; final Source<byte[], byte[]> db; public StringJDS() { this(new HashMapDB<byte[]>()); } private StringJDS(HashMapDB<byte[]> mapDB) { this(mapDB, mapDB); } private StringJDS(HashMapDB<byte[]> mapDB, Source<byte[], byte[]> db) { super(db); this.db = db; this.mapDB = mapDB; } public synchronized void put(String key) { super.put(key.getBytes(), key.getBytes()); } public synchronized void delete(String key) { super.delete(key.getBytes()); } public String get(String key) { return new String(super.get(key.getBytes())); } } private void checkDb(StringJDS db, String ... keys) { assertEquals(keys.length, db.mapDB.keys().size()); for (String key : keys) { assertTrue(db.get(key.getBytes()) != null); } } private void putKeys(StringJDS db, String ... keys) { for (String key : keys) { db.put(key.getBytes(), key.getBytes()); } } @Test public void simpleTest() { StringJDS jds = new StringJDS(); Pruner pruner = new Pruner(jds.getJournal(), jds.db); pruner.init(); putKeys(jds, "a1", "a2"); jds.put("a3"); jds.delete("a2"); pruner.feed(jds.commitUpdates(hashInt(1))); jds.put("a2"); jds.delete("a3"); pruner.feed(jds.commitUpdates(hashInt(2))); jds.delete("a2"); pruner.feed(jds.commitUpdates(hashInt(3))); Segment segment = new Segment(0, hashInt(0), hashInt(0)); segment.startTracking() .addMain(1, hashInt(1), hashInt(0)) .commit(); pruner.prune(segment); checkDb(jds, "a1", "a2", "a3"); segment = new Segment(1, hashInt(1), hashInt(0)); segment.startTracking() .addMain(2, hashInt(2), hashInt(1)) .commit(); pruner.prune(segment); checkDb(jds, "a1", "a2"); segment = new Segment(2, hashInt(2), hashInt(1)); segment.startTracking() .addMain(3, hashInt(3), hashInt(2)) .commit(); pruner.prune(segment); checkDb(jds, "a1"); assertEquals(0, ((HashMapDB) jds.journal).getStorage().size()); } @Test public void forkTest1() { StringJDS jds = new StringJDS(); Pruner pruner = new Pruner(jds.getJournal(), jds.db); pruner.init(); putKeys(jds, "a1", "a2", "a3"); pruner.feed(jds.commitUpdates(hashInt(0))); jds.put("a4"); jds.put("a1"); jds.delete("a2"); pruner.feed(jds.commitUpdates(hashInt(1))); jds.put("a5"); jds.delete("a3"); jds.put("a2"); jds.put("a1"); pruner.feed(jds.commitUpdates(hashInt(2))); pruner.feed(jds.commitUpdates(hashInt(3))); // complete segment checkDb(jds, "a1", "a2", "a3", "a4", "a5"); Segment segment = new Segment(0, hashInt(0), hashInt(0)); segment.startTracking() .addMain(0, hashInt(0), hashInt(0)) .commit(); pruner.prune(segment); segment = new Segment(0, hashInt(0), hashInt(-1)); segment.startTracking() .addMain(1, hashInt(1), hashInt(0)) .addItem(1, hashInt(2), hashInt(0)) .addMain(2, hashInt(3), hashInt(1)) .commit(); pruner.prune(segment); checkDb(jds, "a1", "a3", "a4"); assertEquals(0, ((HashMapDB) jds.journal).getStorage().size()); } @Test public void forkTest2() { StringJDS jds = new StringJDS(); Pruner pruner = new Pruner(jds.getJournal(), jds.db); pruner.init(); putKeys(jds, "a1", "a2", "a3"); jds.delete("a1"); jds.delete("a3"); pruner.feed(jds.commitUpdates(hashInt(1))); jds.put("a4"); pruner.feed(jds.commitUpdates(hashInt(2))); pruner.feed(jds.commitUpdates(hashInt(3))); jds.put("a1"); jds.delete("a2"); pruner.feed(jds.commitUpdates(hashInt(4))); jds.put("a4"); pruner.feed(jds.commitUpdates(hashInt(5))); pruner.feed(jds.commitUpdates(hashInt(6))); pruner.feed(jds.commitUpdates(hashInt(7))); jds.put("a3"); pruner.feed(jds.commitUpdates(hashInt(8))); checkDb(jds, "a1", "a2", "a3", "a4"); Segment segment = new Segment(0, hashInt(0), hashInt(0)); segment.startTracking() .addMain(1, hashInt(1), hashInt(0)) .addItem(1, hashInt(2), hashInt(0)) .addMain(2, hashInt(3), hashInt(1)) .commit(); pruner.prune(segment); checkDb(jds, "a1", "a2", "a3", "a4"); segment = new Segment(0, hashInt(0), hashInt(0)); segment.startTracking() .addMain(1, hashInt(6), hashInt(0)) .addItem(1, hashInt(4), hashInt(0)) .addItem(1, hashInt(5), hashInt(0)) .addMain(2, hashInt(7), hashInt(6)) .commit(); pruner.prune(segment); checkDb(jds, "a2", "a3"); segment = new Segment(0, hashInt(0), hashInt(0)); segment.startTracking() .addMain(1, hashInt(8), hashInt(0)) .commit(); pruner.prune(segment); checkDb(jds, "a2", "a3"); assertEquals(0, ((HashMapDB) jds.journal).getStorage().size()); } @Test public void forkTest3() { StringJDS jds = new StringJDS(); Pruner pruner = new Pruner(jds.getJournal(), jds.db); pruner.init(); putKeys(jds, "a1"); jds.put("a2"); pruner.feed(jds.commitUpdates(hashInt(1))); jds.put("a1"); jds.put("a2"); jds.put("a3"); pruner.feed(jds.commitUpdates(hashInt(2))); jds.put("a1"); jds.put("a2"); jds.put("a3"); pruner.feed(jds.commitUpdates(hashInt(3))); pruner.feed(jds.commitUpdates(hashInt(4))); checkDb(jds, "a1", "a2", "a3"); Segment segment = new Segment(0, hashInt(0), hashInt(0)); segment.startTracking() .addMain(1, hashInt(1), hashInt(0)) .addItem(1, hashInt(2), hashInt(0)) .addItem(1, hashInt(3), hashInt(0)) .addMain(2, hashInt(4), hashInt(1)) .commit(); pruner.prune(segment); checkDb(jds, "a1", "a2"); assertEquals(0, ((HashMapDB) jds.journal).getStorage().size()); } @Test public void twoStepTest1() { StringJDS jds = new StringJDS(); Pruner pruner = new Pruner(jds.getJournal(), jds.db); pruner.init(); pruner.withSecondStep(Collections.emptyList(), 100); putKeys(jds, "a1", "a2", "a3"); pruner.feed(jds.commitUpdates(hashInt(0))); jds.put("a4"); jds.put("a1"); jds.delete("a2"); pruner.feed(jds.commitUpdates(hashInt(1))); jds.put("a5"); jds.delete("a3"); jds.put("a1"); pruner.feed(jds.commitUpdates(hashInt(2))); pruner.feed(jds.commitUpdates(hashInt(3))); // complete segment checkDb(jds, "a1", "a2", "a3", "a4", "a5"); Segment segment = new Segment(0, hashInt(0), hashInt(0)); segment.startTracking() .addMain(0, hashInt(0), hashInt(0)) .commit(); pruner.prune(segment); segment = new Segment(0, hashInt(0), hashInt(-1)); segment.startTracking() .addMain(1, hashInt(1), hashInt(0)) .addItem(1, hashInt(2), hashInt(0)) .addMain(2, hashInt(3), hashInt(1)) .commit(); pruner.prune(segment); pruner.persist(hashInt(0)); checkDb(jds, "a1", "a2", "a3", "a4"); pruner.persist(hashInt(1)); checkDb(jds, "a1", "a3", "a4"); pruner.persist(hashInt(3)); assertEquals(0, ((HashMapDB) jds.journal).getStorage().size()); } @Test public void twoStepTest2() { StringJDS jds = new StringJDS(); Pruner pruner = new Pruner(jds.getJournal(), jds.db); pruner.init(); pruner.withSecondStep(Collections.emptyList(), 100); putKeys(jds, "a1", "a2", "a3"); pruner.feed(jds.commitUpdates(hashInt(0))); jds.put("a4"); jds.delete("a2"); jds.delete("a1"); pruner.feed(jds.commitUpdates(hashInt(1))); jds.put("a2"); jds.delete("a3"); pruner.feed(jds.commitUpdates(hashInt(2))); jds.put("a5"); jds.delete("a2"); pruner.feed(jds.commitUpdates(hashInt(3))); jds.put("a5"); jds.put("a6"); jds.delete("a4"); pruner.feed(jds.commitUpdates(hashInt(31))); pruner.feed(jds.commitUpdates(hashInt(4))); checkDb(jds, "a1", "a2", "a3", "a4", "a5", "a6"); Segment segment = new Segment(0, hashInt(0), hashInt(0)); segment.startTracking() .addMain(0, hashInt(0), hashInt(0)) .addMain(1, hashInt(1), hashInt(0)) .addMain(2, hashInt(2), hashInt(1)) .commit(); pruner.prune(segment); pruner.persist(hashInt(0)); checkDb(jds, "a1", "a2", "a3", "a4", "a5", "a6"); pruner.persist(hashInt(1)); checkDb(jds, "a2", "a3", "a4", "a5", "a6"); pruner.persist(hashInt(2)); checkDb(jds, "a2", "a4", "a5", "a6"); segment = new Segment(2, hashInt(2), hashInt(1)); segment.startTracking() .addMain(3, hashInt(3), hashInt(2)) .addItem(3, hashInt(31), hashInt(2)) .addMain(4, hashInt(4), hashInt(3)) .commit(); pruner.prune(segment); pruner.persist(hashInt(3)); checkDb(jds, "a4", "a5"); pruner.persist(hashInt(4)); assertEquals(0, ((HashMapDB) jds.journal).getStorage().size()); } @Test public void twoStepTest3() { StringJDS jds = new StringJDS(); Pruner pruner = new Pruner(jds.getJournal(), jds.db); pruner.init(); pruner.withSecondStep(Collections.emptyList(), 100); putKeys(jds, "a1", "a2", "a3"); pruner.feed(jds.commitUpdates(hashInt(0))); jds.put("a4"); jds.delete("a2"); jds.delete("a1"); pruner.feed(jds.commitUpdates(hashInt(1))); jds.put("a2"); jds.delete("a3"); pruner.feed(jds.commitUpdates(hashInt(2))); jds.put("a5"); jds.put("a1"); jds.delete("a2"); pruner.feed(jds.commitUpdates(hashInt(3))); jds.put("a5"); jds.put("a6"); jds.delete("a4"); pruner.feed(jds.commitUpdates(hashInt(31))); pruner.feed(jds.commitUpdates(hashInt(4))); checkDb(jds, "a1", "a2", "a3", "a4", "a5", "a6"); Segment segment = new Segment(0, hashInt(0), hashInt(0)); segment.startTracking() .addMain(0, hashInt(0), hashInt(0)) .addMain(1, hashInt(1), hashInt(0)) .addMain(2, hashInt(2), hashInt(1)) .commit(); pruner.prune(segment); pruner.persist(hashInt(0)); checkDb(jds, "a1", "a2", "a3", "a4", "a5", "a6"); pruner.persist(hashInt(1)); checkDb(jds, "a1", "a2", "a3", "a4", "a5", "a6"); pruner.persist(hashInt(2)); checkDb(jds, "a1", "a2", "a4", "a5", "a6"); segment = new Segment(2, hashInt(2), hashInt(1)); segment.startTracking() .addMain(3, hashInt(3), hashInt(2)) .addItem(3, hashInt(31), hashInt(2)) .addMain(4, hashInt(4), hashInt(3)) .commit(); pruner.prune(segment); pruner.persist(hashInt(3)); checkDb(jds, "a1", "a4", "a5"); pruner.persist(hashInt(4)); assertEquals(0, ((HashMapDB) jds.journal).getStorage().size()); } public byte[] hashInt(int i) { return HashUtil.sha3(ByteUtil.intToBytes(i)); } }
13,569
30.412037
80
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/TrieNodeSourceIntegrationTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import com.typesafe.config.ConfigFactory; import org.ethereum.config.NoAutoscan; import org.ethereum.config.SystemProperties; import org.ethereum.core.Repository; import org.ethereum.crypto.HashUtil; import org.ethereum.db.DbFlushManager; import org.ethereum.db.StateSource; import org.ethereum.db.prune.Pruner; import org.ethereum.db.prune.Segment; import org.ethereum.vm.DataWord; import org.junit.AfterClass; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.spongycastle.util.encoders.Hex; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.*; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import java.util.concurrent.ExecutionException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * @author Mikhail Kalinin * @since 05.12.2017 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class) @NoAutoscan @Ignore public class TrieNodeSourceIntegrationTest { @Autowired @Qualifier("trieNodeSource") Source<byte[], byte[]> trieNodeSource; @Autowired StateSource stateSource; @Autowired @Qualifier("defaultRepository") Repository repository; @Autowired DbFlushManager dbFlushManager; @Configuration @ComponentScan(basePackages = "org.ethereum") @NoAutoscan static class ContextConfiguration { private final String config = // no need for discovery in that small network "peer.discovery.enabled = false \n" + "sync.enabled = false \n" + "genesis = genesis-low-difficulty.json \n"; @Bean public SystemProperties systemProperties() { SystemProperties props = new SystemProperties(); props.overrideParams(ConfigFactory.parseString(config.replaceAll("'", "\""))); return props; } } @AfterClass public static void cleanup() { SystemProperties.resetToDefault(); } @Test public void testContractStorage() throws ExecutionException, InterruptedException { byte[] addr1 = Hex.decode("5c543e7ae0a1104f78406c340e9c64fd9fce5170"); byte[] addr2 = Hex.decode("8bccc9ba2e5706e24a36dda02ca2a846e39a7bbf"); byte[] k1 = HashUtil.sha3("key1".getBytes()), v1 = "value1".getBytes(); assertNull(trieNodeSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055"))); repository.addStorageRow(addr1, DataWord.of(k1), DataWord.of(v1)); repository.addStorageRow(addr2, DataWord.of(k1), DataWord.of(v1)); flushChanges(); // Logically we must get a node with key 4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055 // and reference counter equal 2, cause both addresses have that node in their storage. // Technically we get two nodes with keys produced by NodeKeyCompositor: // 4b7fc4d98630bae2133ad002f743124f01bb4fbefc0a1a699cd4c20899a2877f // 4b7fc4d98630bae2133ad002f743124fafe15fa1326e1c0fcd4b67a53eee9537 // values they hold are equal, logically it is the same value assertNull(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055"))); assertEquals("eaa1202cc45dfd615ef5099974383a7c13606186f629a558453bdb2985d005ad174e73878676616c756531", Hex.toHexString(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f01bb4fbefc0a1a699cd4c20899a2877f")))); assertEquals("eaa1202cc45dfd615ef5099974383a7c13606186f629a558453bdb2985d005ad174e73878676616c756531", Hex.toHexString(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124fafe15fa1326e1c0fcd4b67a53eee9537")))); // trieNodeSource must return that value supplied with origin key 4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055 // it does a prefix search by only first 16 bytes of the key assertEquals("eaa1202cc45dfd615ef5099974383a7c13606186f629a558453bdb2985d005ad174e73878676616c756531", Hex.toHexString(trieNodeSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055")))); // one of that storage rows is gonna be removed repository.addStorageRow(addr1, DataWord.of(k1), DataWord.ZERO); flushChanges(); // state doesn't contain a copy of node that belongs to addr1 assertNull(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f01bb4fbefc0a1a699cd4c20899a2877f"))); // but still able to pick addr2 value assertEquals("eaa1202cc45dfd615ef5099974383a7c13606186f629a558453bdb2985d005ad174e73878676616c756531", Hex.toHexString(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124fafe15fa1326e1c0fcd4b67a53eee9537")))); // trieNodeSource still able to pick a value by origin key assertEquals("eaa1202cc45dfd615ef5099974383a7c13606186f629a558453bdb2985d005ad174e73878676616c756531", Hex.toHexString(trieNodeSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055")))); // remove a copy of value stick to addr2 repository.addStorageRow(addr2, DataWord.of(k1), DataWord.ZERO); flushChanges(); // no source can resolve any of those keys assertNull(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f01bb4fbefc0a1a699cd4c20899a2877f"))); assertNull(stateSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124fafe15fa1326e1c0fcd4b67a53eee9537"))); assertNull(trieNodeSource.get(Hex.decode("4b7fc4d98630bae2133ad002f743124f2ef5d8167f094af0c2b82d3476604055"))); } @Test public void testContractCode() throws ExecutionException, InterruptedException { byte[] addr1 = Hex.decode("5c543e7ae0a1104f78406c340e9c64fd9fce5170"); byte[] addr2 = Hex.decode("8bccc9ba2e5706e24a36dda02ca2a846e39a7bbf"); byte[] code = "contract Foo {}".getBytes(); byte[] codeHash = HashUtil.sha3(code); repository.saveCode(addr1, code); flushChanges(); assertNull(stateSource.get(codeHash)); assertEquals(Hex.toHexString(code), Hex.toHexString(stateSource.get(Hex.decode("0827ccfec1b70192ffadbc46e945a9af01bb4fbefc0a1a699cd4c20899a2877f")))); assertNull(stateSource.get(Hex.decode("0827ccfec1b70192ffadbc46e945a9afafe15fa1326e1c0fcd4b67a53eee9537"))); assertEquals(Hex.toHexString(code), Hex.toHexString(trieNodeSource.get(codeHash))); repository.saveCode(addr2, code); flushChanges(); assertNull(stateSource.get(codeHash)); assertEquals(Hex.toHexString(code), Hex.toHexString(stateSource.get(Hex.decode("0827ccfec1b70192ffadbc46e945a9af01bb4fbefc0a1a699cd4c20899a2877f")))); assertEquals(Hex.toHexString(code), Hex.toHexString(stateSource.get(Hex.decode("0827ccfec1b70192ffadbc46e945a9afafe15fa1326e1c0fcd4b67a53eee9537")))); assertEquals(Hex.toHexString(code), Hex.toHexString(trieNodeSource.get(codeHash))); } private void flushChanges() throws ExecutionException, InterruptedException { repository.commit(); stateSource.getJournalSource().commitUpdates(HashUtil.EMPTY_DATA_HASH); Pruner pruner = new Pruner(stateSource.getJournalSource().getJournal(), stateSource.getNoJournalSource()); pruner.init(HashUtil.EMPTY_DATA_HASH); Segment segment = new Segment(0, HashUtil.EMPTY_DATA_HASH, HashUtil.EMPTY_DATA_HASH); segment.startTracking() .addMain(1, HashUtil.EMPTY_DATA_HASH, HashUtil.EMPTY_DATA_HASH) .commit(); pruner.prune(segment); dbFlushManager.flush().get(); } }
8,916
44.728205
138
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/SourceCodecTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.vm.DataWord; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.longToBytes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * Test for {@link SourceCodec} */ public class SourceCodecTest { private byte[] intToKey(int i) { return sha3(longToBytes(i)); } private byte[] intToValue(int i) { return (DataWord.of(i)).getData(); } private DataWord intToDataWord(int i) { return DataWord.of(i); } private DataWord intToDataWordKey(int i) { return DataWord.of(intToKey(i)); } private String str(Object obj) { if (obj == null) return null; byte[] data; if (obj instanceof DataWord) { data = ((DataWord) obj).getData(); } else { data = (byte[]) obj; } return Hex.toHexString(data); } @Test public void testDataWordKeySerializer() { Source<byte[], byte[]> parentSrc = new HashMapDB<>(); Serializer<DataWord, byte[]> keySerializer = Serializers.StorageKeySerializer; Serializer<byte[], byte[]> valueSerializer = new Serializers.Identity<>(); SourceCodec<DataWord, byte[], byte[], byte[]> src = new SourceCodec<>(parentSrc, keySerializer, valueSerializer); for (int i = 0; i < 10_000; ++i) { src.put(intToDataWordKey(i), intToValue(i)); } // Everything is in src assertEquals(str(intToValue(0)), str(src.get(intToDataWordKey(0)))); assertEquals(str(intToValue(9_999)), str(src.get(intToDataWordKey(9_999)))); // Modifying key src.put(intToDataWordKey(0), intToValue(12345)); assertEquals(str(intToValue(12345)), str(src.get(intToDataWordKey(0)))); // Testing there is no cache assertEquals(str(intToValue(9_990)), str(src.get(intToDataWordKey(9_990)))); parentSrc.delete(keySerializer.serialize(intToDataWordKey(9_990))); assertNull(src.get(intToDataWordKey(9_990))); } @Test public void testDataWordKeyValueSerializer() { Source<byte[], byte[]> parentSrc = new HashMapDB<>(); Serializer<DataWord, byte[]> keySerializer = Serializers.StorageKeySerializer; Serializer<DataWord, byte[]> valueSerializer = Serializers.StorageValueSerializer; SourceCodec<DataWord, DataWord, byte[], byte[]> src = new SourceCodec<>(parentSrc, keySerializer, valueSerializer); for (int i = 0; i < 10_000; ++i) { src.put(intToDataWordKey(i), intToDataWord(i)); } // Everything is in src assertEquals(str(intToDataWord(0)), str(src.get(intToDataWordKey(0)))); assertEquals(str(intToDataWord(9_999)), str(src.get(intToDataWordKey(9_999)))); // Modifying key src.put(intToDataWordKey(0), intToDataWord(12345)); assertEquals(str(intToDataWord(12345)), str(src.get(intToDataWordKey(0)))); } }
3,930
35.06422
123
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/ReadCacheTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.vm.DataWord; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.longToBytes; import static org.junit.Assert.*; /** * Testing {@link ReadCache} */ public class ReadCacheTest { private byte[] intToKey(int i) { return sha3(longToBytes(i)); } private byte[] intToValue(int i) { return (DataWord.of(i)).getData(); } private String str(Object obj) { if (obj == null) return null; return Hex.toHexString((byte[]) obj); } @Test public void test1() { Source<byte[], byte[]> src = new HashMapDB<>(); ReadCache<byte[], byte[]> readCache = new ReadCache.BytesKey<>(src); for (int i = 0; i < 10_000; ++i) { src.put(intToKey(i), intToValue(i)); } // Nothing is cached assertNull(readCache.getCached(intToKey(0))); assertNull(readCache.getCached(intToKey(9_999))); for (int i = 0; i < 10_000; ++i) { readCache.get(intToKey(i)); } // Everything is cached assertEquals(str(intToValue(0)), str(readCache.getCached(intToKey(0)).value())); assertEquals(str(intToValue(9_999)), str(readCache.getCached(intToKey(9_999)).value())); // Source changes doesn't affect cache src.delete(intToKey(13)); assertEquals(str(intToValue(13)), str(readCache.getCached(intToKey(13)).value())); // Flush is not implemented assertFalse(readCache.flush()); } @Test public void testMaxCapacity() { Source<byte[], byte[]> src = new HashMapDB<>(); ReadCache<byte[], byte[]> readCache = new ReadCache.BytesKey<>(src).withMaxCapacity(100); for (int i = 0; i < 10_000; ++i) { src.put(intToKey(i), intToValue(i)); readCache.get(intToKey(i)); } // Only 100 latest are cached assertNull(readCache.getCached(intToKey(0))); assertEquals(str(intToValue(0)), str(readCache.get(intToKey(0)))); assertEquals(str(intToValue(0)), str(readCache.getCached(intToKey(0)).value())); assertEquals(str(intToValue(9_999)), str(readCache.getCached(intToKey(9_999)).value())); // 99_01 - 99_99 and 0 (totally 100) assertEquals(str(intToValue(9_901)), str(readCache.getCached(intToKey(9_901)).value())); assertNull(readCache.getCached(intToKey(9_900))); } }
3,360
35.532609
97
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/BatchSourceWriterTest.java
package org.ethereum.datasource; import org.junit.Test; import java.math.BigInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; /** * @author alexbraz * @since 29/03/2019 */ public class BatchSourceWriterTest { @Test public void testFlush() { BatchSource batchSource = mock(BatchSource.class); BatchSourceWriter<String, BigInteger> bsw = new BatchSourceWriter(batchSource); bsw.put("KEY", BigInteger.ONE); assertTrue(bsw.flushImpl()); } @Test public void testValues() { BatchSource batchSource = mock(BatchSource.class); BatchSourceWriter<String, BigInteger> bsw = new BatchSourceWriter(batchSource); bsw.put("ONE", BigInteger.ONE); bsw.put("TEN", BigInteger.TEN); bsw.put("ZERO", BigInteger.ZERO); bsw.buf.forEach((K, v) -> { assertEquals(v, bsw.buf.get(K)); }); } }
988
24.358974
87
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/ReadWriteCacheTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.vm.DataWord; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.longToBytes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * Testing {@link ReadWriteCache} */ public class ReadWriteCacheTest { private byte[] intToKey(int i) { return sha3(longToBytes(i)); } private byte[] intToValue(int i) { return (DataWord.of(i)).getData(); } private String str(Object obj) { if (obj == null) return null; return Hex.toHexString((byte[]) obj); } @Test public void testSimple() { Source<byte[], byte[]> src = new HashMapDB<>(); ReadWriteCache<byte[], byte[]> cache = new ReadWriteCache.BytesKey<>(src, WriteCache.CacheType.SIMPLE); for (int i = 0; i < 10_000; ++i) { cache.put(intToKey(i), intToValue(i)); } // Everything is cached assertEquals(str(intToValue(0)), str(cache.getCached(intToKey(0)).value())); assertEquals(str(intToValue(9_999)), str(cache.getCached(intToKey(9_999)).value())); // Source is empty assertNull(src.get(intToKey(0))); assertNull(src.get(intToKey(9_999))); // After flush src is filled cache.flush(); assertEquals(str(intToValue(9_999)), str(src.get(intToKey(9_999)))); assertEquals(str(intToValue(0)), str(src.get(intToKey(0)))); // Deleting key that is currently in cache cache.put(intToKey(0), intToValue(12345)); assertEquals(str(intToValue(12345)), str(cache.getCached(intToKey(0)).value())); cache.delete(intToKey(0)); assertTrue(null == cache.getCached(intToKey(0)) || null == cache.getCached(intToKey(0)).value()); assertEquals(str(intToValue(0)), str(src.get(intToKey(0)))); cache.flush(); assertNull(src.get(intToKey(0))); // No size estimators assertEquals(0, cache.estimateCacheSize()); } }
2,988
34.583333
111
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/MultiThreadSourcesTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.datasource.leveldb.LevelDbDataSource; import org.ethereum.db.StateSource; import org.ethereum.mine.AnyFuture; import org.ethereum.util.ALock; import org.ethereum.util.ByteArrayMap; import org.ethereum.util.Utils; import org.ethereum.vm.DataWord; import org.junit.Assert; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import static java.lang.Math.max; import static java.lang.Thread.sleep; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.intToBytes; import static org.ethereum.util.ByteUtil.longToBytes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * Testing different sources and chain of sources in multi-thread environment */ public class MultiThreadSourcesTest { private byte[] intToKey(int i) { return sha3(longToBytes(i)); } private byte[] intToValue(int i) { return (DataWord.of(i)).getData(); } private String str(Object obj) { if (obj == null) return null; return Hex.toHexString((byte[]) obj); } private class TestExecutor { private Source<byte[], byte[]> cache; boolean isCounting = false; boolean noDelete = false; boolean running = true; final CountDownLatch failSema = new CountDownLatch(1); final AtomicInteger putCnt = new AtomicInteger(1); final AtomicInteger delCnt = new AtomicInteger(1); final AtomicInteger checkCnt = new AtomicInteger(0); public TestExecutor(Source cache) { this.cache = cache; } public TestExecutor(Source cache, boolean isCounting) { this.cache = cache; this.isCounting = isCounting; } public void setNoDelete(boolean noDelete) { this.noDelete = noDelete; } final Thread readThread = new Thread(() -> { try { while(running) { int curMax = putCnt.get() - 1; if (checkCnt.get() >= curMax) { sleep(10); continue; } assertEquals(str(intToValue(curMax)), str(cache.get(intToKey(curMax)))); checkCnt.set(curMax); } } catch (Throwable e) { e.printStackTrace(); failSema.countDown(); } }); final Thread delThread = new Thread(() -> { try { while(running) { int toDelete = delCnt.get(); int curMax = putCnt.get() - 1; if (toDelete > checkCnt.get() || toDelete >= curMax) { sleep(10); continue; } assertEquals(str(intToValue(toDelete)), str(cache.get(intToKey(toDelete)))); if (isCounting) { for (int i = 0; i < (toDelete % 5); ++i) { cache.delete(intToKey(toDelete)); assertEquals(str(intToValue(toDelete)), str(cache.get(intToKey(toDelete)))); } } cache.delete(intToKey(toDelete)); if (isCounting) cache.flush(); assertNull(cache.get(intToKey(toDelete))); delCnt.getAndIncrement(); } } catch (Throwable e) { e.printStackTrace(); failSema.countDown(); } }); public void run(long timeout) { new Thread(() -> { try { while(running) { int curCnt = putCnt.get(); cache.put(intToKey(curCnt), intToValue(curCnt)); if (isCounting) { for (int i = 0; i < (curCnt % 5); ++i) { cache.put(intToKey(curCnt), intToValue(curCnt)); } } putCnt.getAndIncrement(); if (curCnt == 1) { readThread.start(); if (!noDelete) { delThread.start(); } } } } catch (Throwable e) { e.printStackTrace(); failSema.countDown(); } }).start(); new Thread(() -> { try { while(running) { sleep(10); cache.flush(); } } catch (Throwable e) { e.printStackTrace(); failSema.countDown(); } }).start(); try { failSema.await(timeout, TimeUnit.SECONDS); } catch (InterruptedException ex) { running = false; throw new RuntimeException("Thrown interrupted exception", ex); } // Shutdown carefully running = false; if (failSema.getCount() == 0) { throw new RuntimeException("Test failed."); } else { System.out.println("Test passed, put counter: " + putCnt.get() + ", delete counter: " + delCnt.get()); } } } private class TestExecutor1 { private Source<byte[], byte[]> cache; public int writerThreads = 4; public int readerThreads = 8; public int deleterThreads = 0; public int flusherThreads = 2; public int maxKey = 10000; boolean stopped; Map<byte[], byte[]> map = Collections.synchronizedMap(new ByteArrayMap<byte[]>()); ReadWriteLock rwLock = new ReentrantReadWriteLock(); ALock rLock = new ALock(rwLock.readLock()); ALock wLock = new ALock(rwLock.writeLock()); public TestExecutor1(Source<byte[], byte[]> cache) { this.cache = cache; } class Writer implements Runnable { public void run() { Random rnd = new Random(0); while (!stopped) { byte[] key = key(rnd.nextInt(maxKey)); try (ALock l = wLock.lock()) { map.put(key, key); cache.put(key, key); } Utils.sleep(rnd.nextInt(1)); } } } class Reader implements Runnable { public void run() { Random rnd = new Random(0); while (!stopped) { byte[] key = key(rnd.nextInt(maxKey)); try (ALock l = rLock.lock()) { byte[] expected = map.get(key); byte[] actual = cache.get(key); Assert.assertArrayEquals(expected, actual); } } } } class Deleter implements Runnable { public void run() { Random rnd = new Random(0); while (!stopped) { byte[] key = key(rnd.nextInt(maxKey)); try (ALock l = wLock.lock()) { map.remove(key); cache.delete(key); } } } } class Flusher implements Runnable { public void run() { Random rnd = new Random(0); while (!stopped) { Utils.sleep(rnd.nextInt(50)); cache.flush(); } } } public void start(long time) throws InterruptedException, TimeoutException, ExecutionException { List<Callable<Object>> all = new ArrayList<>(); for (int i = 0; i < writerThreads; i++) { all.add(Executors.callable(new Writer())); } for (int i = 0; i < readerThreads; i++) { all.add(Executors.callable(new Reader())); } for (int i = 0; i < deleterThreads; i++) { all.add(Executors.callable(new Deleter())); } for (int i = 0; i < flusherThreads; i++) { all.add(Executors.callable(new Flusher())); } ExecutorService executor = Executors.newFixedThreadPool(all.size()); ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executor); AnyFuture<Object> anyFuture = new AnyFuture<>(); for (Callable<Object> callable : all) { ListenableFuture<Object> future = listeningExecutorService.submit(callable); anyFuture.add(future); } try { anyFuture.get(time, TimeUnit.SECONDS); } catch (TimeoutException e) { System.out.println("Passed."); } stopped = true; } } @Test public void testWriteCache() throws InterruptedException { Source<byte[], byte[]> src = new HashMapDB<>(); final WriteCache writeCache = new WriteCache.BytesKey<>(src, WriteCache.CacheType.SIMPLE); TestExecutor testExecutor = new TestExecutor(writeCache); testExecutor.run(5); } @Test public void testReadCache() throws InterruptedException { Source<byte[], byte[]> src = new HashMapDB<>(); final ReadCache readCache = new ReadCache.BytesKey<>(src); TestExecutor testExecutor = new TestExecutor(readCache); testExecutor.run(5); } @Test public void testReadWriteCache() throws InterruptedException { Source<byte[], byte[]> src = new HashMapDB<>(); final ReadWriteCache readWriteCache = new ReadWriteCache.BytesKey<>(src, WriteCache.CacheType.SIMPLE); TestExecutor testExecutor = new TestExecutor(readWriteCache); testExecutor.run(5); } @Test public void testAsyncWriteCache() throws InterruptedException, TimeoutException, ExecutionException { Source<byte[], byte[]> src = new HashMapDB<>(); AsyncWriteCache<byte[], byte[]> cache = new AsyncWriteCache<byte[], byte[]>(src) { @Override protected WriteCache<byte[], byte[]> createCache(Source<byte[], byte[]> source) { return new WriteCache.BytesKey<byte[]>(source, WriteCache.CacheType.SIMPLE) { @Override public boolean flush() { // System.out.println("Flushing started"); boolean ret = super.flush(); // System.out.println("Flushing complete"); return ret; } }; } }; // TestExecutor testExecutor = new TestExecutor(cache); TestExecutor1 testExecutor = new TestExecutor1(cache); testExecutor.start(5); } @Test public void testStateSource() throws Exception { HashMapDB<byte[]> src = new HashMapDB<>(); // LevelDbDataSource ldb = new LevelDbDataSource("test"); // ldb.init(); StateSource stateSource = new StateSource(src, false); stateSource.getReadCache().withMaxCapacity(10); TestExecutor1 testExecutor = new TestExecutor1(stateSource); testExecutor.start(10); } volatile int maxConcurrency = 0; volatile int maxWriteConcurrency = 0; volatile int maxReadWriteConcurrency = 0; @Test public void testStateSourceConcurrency() throws Exception { HashMapDB<byte[]> src = new HashMapDB<byte[]>() { AtomicInteger concurrentReads = new AtomicInteger(0); AtomicInteger concurrentWrites = new AtomicInteger(0); void checkConcurrency(boolean write) { maxConcurrency = max(concurrentReads.get() + concurrentWrites.get(), maxConcurrency); if (write) { maxWriteConcurrency = max(concurrentWrites.get(), maxWriteConcurrency); } else { maxReadWriteConcurrency = max(concurrentWrites.get(), maxReadWriteConcurrency); } } @Override public void put(byte[] key, byte[] val) { int i1 = concurrentWrites.incrementAndGet(); checkConcurrency(true); super.put(key, val); int i2 = concurrentWrites.getAndDecrement(); } @Override public byte[] get(byte[] key) { // Utils.sleep(60_000); int i1 = concurrentReads.incrementAndGet(); checkConcurrency(false); Utils.sleep(1); byte[] ret = super.get(key); int i2 = concurrentReads.getAndDecrement(); return ret; } @Override public void delete(byte[] key) { int i1 = concurrentWrites.incrementAndGet(); checkConcurrency(true); super.delete(key); int i2 = concurrentWrites.getAndDecrement(); } }; final StateSource stateSource = new StateSource(src, false); stateSource.getReadCache().withMaxCapacity(10); new Thread() { @Override public void run() { stateSource.get(key(1)); } }.start(); stateSource.get(key(2)); TestExecutor1 testExecutor = new TestExecutor1(stateSource); // testExecutor.writerThreads = 0; testExecutor.start(3); System.out.println("maxConcurrency = " + maxConcurrency + ", maxWriteConcurrency = " + maxWriteConcurrency + ", maxReadWriteConcurrency = " + maxReadWriteConcurrency); } @Test public void testCountingWriteCache() throws InterruptedException { Source<byte[], byte[]> parentSrc = new HashMapDB<>(); Source<byte[], byte[]> src = new CountingBytesSource(parentSrc); final WriteCache writeCache = new WriteCache.BytesKey<>(src, WriteCache.CacheType.COUNTING); TestExecutor testExecutor = new TestExecutor(writeCache, true); testExecutor.run(10); } private static byte[] key(int key) { return sha3(intToBytes(key)); } }
15,851
34.622472
118
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/ObjectDataSourceTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.vm.DataWord; import org.junit.Test; import org.spongycastle.util.encoders.Hex; import static org.ethereum.crypto.HashUtil.sha3; import static org.ethereum.util.ByteUtil.longToBytes; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * Test for {@link ObjectDataSource} */ public class ObjectDataSourceTest { private byte[] intToKey(int i) { return sha3(longToBytes(i)); } private byte[] intToValue(int i) { return (DataWord.of(i)).getData(); } private DataWord intToDataWord(int i) { return DataWord.of(i); } private String str(Object obj) { if (obj == null) return null; byte[] data; if (obj instanceof DataWord) { data = ((DataWord) obj).getData(); } else { data = (byte[]) obj; } return Hex.toHexString(data); } @Test public void testDummySerializer() { Source<byte[], byte[]> parentSrc = new HashMapDB<>(); Serializer<byte[], byte[]> serializer = new Serializers.Identity<>(); ObjectDataSource<byte[]> src = new ObjectDataSource<>(parentSrc, serializer, 256); for (int i = 0; i < 10_000; ++i) { src.put(intToKey(i), intToValue(i)); } // Everything is in src and parentSrc w/o flush assertEquals(str(intToValue(0)), str(src.get(intToKey(0)))); assertEquals(str(intToValue(9_999)), str(src.get(intToKey(9_999)))); assertEquals(str(intToValue(0)), str(parentSrc.get(intToKey(0)))); assertEquals(str(intToValue(9_999)), str(parentSrc.get(intToKey(9_999)))); // Testing read cache is available parentSrc.delete(intToKey(9_999)); assertEquals(str(intToValue(9_999)), str(src.get(intToKey(9_999)))); src.delete(intToKey(9_999)); // Testing src delete invalidates read cache src.delete(intToKey(9_998)); assertNull(src.get(intToKey(9_998))); // Modifying key src.put(intToKey(0), intToValue(12345)); assertEquals(str(intToValue(12345)), str(src.get(intToKey(0)))); assertEquals(str(intToValue(12345)), str(parentSrc.get(intToKey(0)))); } @Test public void testDataWordValueSerializer() { Source<byte[], byte[]> parentSrc = new HashMapDB<>(); Serializer<DataWord, byte[]> serializer = Serializers.StorageValueSerializer; ObjectDataSource<DataWord> src = new ObjectDataSource<>(parentSrc, serializer, 256); for (int i = 0; i < 10_000; ++i) { src.put(intToKey(i), intToDataWord(i)); } // Everything is in src assertEquals(str(intToDataWord(0)), str(src.get(intToKey(0)))); assertEquals(str(intToDataWord(9_999)), str(src.get(intToKey(9_999)))); // Modifying key src.put(intToKey(0), intToDataWord(12345)); assertEquals(str(intToDataWord(12345)), str(src.get(intToKey(0)))); } }
3,855
34.376147
92
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/datasource/RepoNewTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.datasource; import org.ethereum.core.AccountState; import org.ethereum.core.Repository; import org.ethereum.datasource.inmem.HashMapDB; import org.ethereum.db.RepositoryRoot; import org.ethereum.vm.DataWord; import org.junit.Assert; import org.junit.Test; import java.math.BigInteger; import static java.math.BigInteger.ONE; import static java.math.BigInteger.valueOf; import static org.spongycastle.util.encoders.Hex.decode; import static org.spongycastle.util.encoders.Hex.toHexString; /** * Created by Anton Nashatyrev on 12.10.2016. */ public class RepoNewTest { @Test public void test1() throws Exception { Source<byte[], byte[]> stateDb = new NoDeleteSource<>(new HashMapDB<byte[]>()); RepositoryRoot repo = new RepositoryRoot(stateDb, null); byte[] addr1 = decode("aaaa"); byte[] addr2 = decode("bbbb"); repo.createAccount(addr1); repo.addBalance(addr1, BigInteger.ONE); repo.createAccount(addr2); repo.addBalance(addr2, valueOf(10)); repo.commit(); byte[] root1 = repo.getRoot(); System.out.println(repo.dumpStateTrie()); System.out.println("Root: " + toHexString(root1)); // System.out.println("Storage size: " + stateDb.getStorage().size()); RepositoryRoot repo1 = new RepositoryRoot(stateDb, root1); Assert.assertEquals(repo1.getBalance(addr1), valueOf(1)); Assert.assertEquals(repo1.getBalance(addr2), valueOf(10)); repo.addBalance(addr2, valueOf(20)); repo.commit(); byte[] root2 = repo.getRoot(); System.out.println("Root: " + toHexString(root2)); // System.out.println("Storage size: " + stateDb.getStorage().size()); RepositoryRoot repo2 = new RepositoryRoot(stateDb, root1); System.out.println(repo2.dumpStateTrie()); Assert.assertEquals(repo2.getBalance(addr1), valueOf(1)); Assert.assertEquals(repo2.getBalance(addr2), valueOf(10)); repo2 = new RepositoryRoot(stateDb, root2); Assert.assertEquals(repo2.getBalance(addr1), valueOf(1)); Assert.assertEquals(repo2.getBalance(addr2), valueOf(30)); Repository repo2_1 = repo2.startTracking(); repo2_1.addBalance(addr2, valueOf(3)); byte[] addr3 = decode("cccc"); repo2_1.createAccount(addr3); repo2_1.addBalance(addr3, valueOf(333)); repo2_1.delete(addr1); Assert.assertEquals(repo2_1.getBalance(addr1), valueOf(0)); Assert.assertEquals(repo2_1.getBalance(addr2), valueOf(33)); Assert.assertEquals(repo2_1.getBalance(addr3), valueOf(333)); Assert.assertEquals(repo2.getBalance(addr1), valueOf(1)); Assert.assertEquals(repo2.getBalance(addr2), valueOf(30)); Assert.assertEquals(repo2.getBalance(addr3), valueOf(0)); repo2_1.commit(); Assert.assertEquals(repo2.getBalance(addr1), valueOf(0)); Assert.assertEquals(repo2.getBalance(addr2), valueOf(33)); Assert.assertEquals(repo2.getBalance(addr3), valueOf(333)); // byte[] root21 = repo2.getRoot(); repo2.commit(); byte[] root22 = repo2.getRoot(); Assert.assertEquals(repo2.getBalance(addr1), valueOf(0)); Assert.assertEquals(repo2.getBalance(addr2), valueOf(33)); Assert.assertEquals(repo2.getBalance(addr3), valueOf(333)); RepositoryRoot repo3 = new RepositoryRoot(stateDb, root22); System.out.println(repo3.getBalance(addr1)); System.out.println(repo3.getBalance(addr2)); System.out.println(repo3.getBalance(addr3)); Assert.assertEquals(repo3.getBalance(addr1), valueOf(0)); Assert.assertEquals(repo3.getBalance(addr2), valueOf(33)); Assert.assertEquals(repo3.getBalance(addr3), valueOf(333)); Repository repo3_1 = repo3.startTracking(); repo3_1.addBalance(addr1, valueOf(10)); Repository repo3_1_1 = repo3_1.startTracking(); repo3_1_1.addBalance(addr1, valueOf(20)); repo3_1_1.addBalance(addr2, valueOf(10)); Assert.assertEquals(repo3.getBalance(addr1), valueOf(0)); Assert.assertEquals(repo3.getBalance(addr2), valueOf(33)); Assert.assertEquals(repo3.getBalance(addr3), valueOf(333)); Assert.assertEquals(repo3_1.getBalance(addr1), valueOf(10)); Assert.assertEquals(repo3_1.getBalance(addr2), valueOf(33)); Assert.assertEquals(repo3_1.getBalance(addr3), valueOf(333)); Assert.assertEquals(repo3_1_1.getBalance(addr1), valueOf(30)); Assert.assertEquals(repo3_1_1.getBalance(addr2), valueOf(43)); Assert.assertEquals(repo3_1_1.getBalance(addr3), valueOf(333)); repo3_1_1.commit(); Assert.assertEquals(repo3.getBalance(addr1), valueOf(0)); Assert.assertEquals(repo3.getBalance(addr2), valueOf(33)); Assert.assertEquals(repo3.getBalance(addr3), valueOf(333)); Assert.assertEquals(repo3_1.getBalance(addr1), valueOf(30)); Assert.assertEquals(repo3_1.getBalance(addr2), valueOf(43)); Assert.assertEquals(repo3_1.getBalance(addr3), valueOf(333)); repo3_1.commit(); Assert.assertEquals(repo3.getBalance(addr1), valueOf(30)); Assert.assertEquals(repo3.getBalance(addr2), valueOf(43)); Assert.assertEquals(repo3.getBalance(addr3), valueOf(333)); byte[] addr4 = decode("dddd"); Repository repo3_2 = repo3.startTracking(); repo3_2.addBalance(addr4, ONE); repo3_2.rollback(); AccountState state = repo3.getAccountState(addr4); Assert.assertNull(state); Repository repo3_3 = repo3.startTracking(); repo3_3.addBalance(addr4, ONE); repo3_3.commit(); state = repo3.getAccountState(addr4); Assert.assertNotNull(state); } @Test public void testStorage1() throws Exception { HashMapDB<byte[]> stateDb = new HashMapDB<>(); RepositoryRoot repo = new RepositoryRoot(stateDb, null); byte[] addr1 = decode("aaaa"); repo.createAccount(addr1); repo.addStorageRow(addr1, DataWord.ONE, DataWord.of(111)); repo.commit(); byte[] root1 = repo.getRoot(); System.out.println(repo.dumpStateTrie()); RepositoryRoot repo2 = new RepositoryRoot(stateDb, root1); DataWord val1 = repo.getStorageValue(addr1, DataWord.ONE); assert DataWord.of(111).equals(val1); Repository repo3 = repo2.startTracking(); repo3.addStorageRow(addr1, DataWord.of(2), DataWord.of(222)); repo3.addStorageRow(addr1, DataWord.ONE, DataWord.of(333)); assert DataWord.of(333).equals(repo3.getStorageValue(addr1, DataWord.ONE)); assert DataWord.of(222).equals(repo3.getStorageValue(addr1, DataWord.of(2))); assert DataWord.of(111).equals(repo2.getStorageValue(addr1, DataWord.ONE)); Assert.assertNull(repo2.getStorageValue(addr1, DataWord.of(2))); repo3.commit(); assert DataWord.of(333).equals(repo2.getStorageValue(addr1, DataWord.ONE)); assert DataWord.of(222).equals(repo2.getStorageValue(addr1, DataWord.of(2))); repo2.commit(); RepositoryRoot repo4 = new RepositoryRoot(stateDb, repo2.getRoot()); assert DataWord.of(333).equals(repo4.getStorageValue(addr1, DataWord.ONE)); assert DataWord.of(222).equals(repo4.getStorageValue(addr1, DataWord.of(2))); } @Test public void testStorage2() throws Exception { RepositoryRoot repo = new RepositoryRoot(new HashMapDB<byte[]>()); Repository repo1 = repo.startTracking(); byte[] addr2 = decode("bbbb"); repo1.addStorageRow(addr2, DataWord.ONE, DataWord.of(111)); repo1.commit(); Assert.assertEquals(DataWord.of(111), repo.getStorageValue(addr2, DataWord.ONE)); } }
8,625
42.786802
89
java
ethereumj
ethereumj-master/ethereumj-core/src/test/java/org/ethereum/log/DecodeLogTest.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.log; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.ethereum.core.CallTransaction; import org.ethereum.solidity.Abi; import org.ethereum.util.ByteUtil; import org.ethereum.vm.DataWord; import org.ethereum.vm.LogInfo; import org.junit.Assert; import org.junit.Test; import org.spongycastle.util.encoders.Hex; public class DecodeLogTest { @Test public void decodeEventWithIndexedParamsTest() { byte[] encodedLog = Hex.decode("f89b9494d9cf9ed550a358d4576e2efd168a80075c648bf863a027772adc63db07aae765b71eb2b533064fa781bd57457e1b138592d8198d0959a0000000000000000000000000bb8492b71d933c1da7ac154b4d01bf54d6f09e99a0000000000000000000000000f84e5656d026ba9c321394a59cca7cd8e705f448a00000000000000000000000000000000000000000000000000000000000000064"); String abi = "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint128\"}],\"name\":\"Transfer\",\"type\":\"event\"}]\n"; LogInfo logInfo = new LogInfo(encodedLog); CallTransaction.Contract contract = new CallTransaction.Contract(abi); CallTransaction.Invocation invocation = contract.parseEvent(logInfo); Assert.assertEquals(3, invocation.args.length); Assert.assertArrayEquals(Hex.decode("bb8492b71d933c1da7ac154b4d01bf54d6f09e99"), (byte[]) invocation.args[0]); Assert.assertArrayEquals(Hex.decode("f84e5656d026ba9c321394a59cca7cd8e705f448"), (byte[]) invocation.args[1]); Assert.assertEquals(new BigInteger("100"), invocation.args[2]); } @Test public void testBytesIndexedParam() { String abiJson = "[{\n" + " 'anonymous': false,\n" + " 'inputs': [\n" + " {\n" + " 'indexed': true,\n" + " 'name': 'from',\n" + " 'type': 'address'\n" + " },\n" + " {\n" + " 'indexed': true,\n" + " 'name': 'to',\n" + " 'type': 'address'\n" + " },\n" + " {\n" + " 'indexed': false,\n" + " 'name': 'value',\n" + " 'type': 'uint256'\n" + " },\n" + " {\n" + " 'indexed': true,\n" + " 'name': 'data',\n" + " 'type': 'bytes'\n" + " }\n" + " ],\n" + " 'name': 'Transfer',\n" + " 'type': 'event'\n" + " }]"; CallTransaction.Contract contract = new CallTransaction.Contract(abiJson.replaceAll("'", "\"")); List<DataWord> topics = new ArrayList<>(); topics.add(DataWord.of("e19260aff97b920c7df27010903aeb9c8d2be5d310a2c67824cf3f15396e4c16")); topics.add(DataWord.of("000000000000000000000000c9ca2e8db68ffeb21978ea30a0b762f0ad2d445b")); topics.add(DataWord.of("000000000000000000000000d71ebe710322f0a95504cdd12294f613536204ce")); topics.add(DataWord.of("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")); byte[] data = Hex.decode("00000000000000000000000000000000000000000000000000002d7982473f00"); LogInfo logInfo = new LogInfo(Hex.decode("2Cc114bbE7b551d62B15C465c7bdCccd9125b182"), topics, data); CallTransaction.Invocation e = contract.parseEvent(logInfo); Assert.assertEquals(4, e.args.length); Assert.assertArrayEquals(Hex.decode("c9ca2e8db68ffeb21978ea30a0b762f0ad2d445b"), (byte[]) e.args[0]); Assert.assertArrayEquals(Hex.decode("d71ebe710322f0a95504cdd12294f613536204ce"), (byte[]) e.args[1]); Assert.assertEquals(ByteUtil.bytesToBigInteger(Hex.decode("002d7982473f00")), e.args[2]); Assert.assertArrayEquals(Hex.decode("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"), (byte[]) e.args[3]); // No exception - OK Abi abi = Abi.fromJson(abiJson.replaceAll("'", "\"")); Abi.Event event = abi.findEvent(p -> true); List<?> args = event.decode(data, topics.stream().map(DataWord::getData).collect(Collectors.toList()).toArray(new byte[0][])); Assert.assertEquals(4, args.size()); Assert.assertArrayEquals(Hex.decode("c9ca2e8db68ffeb21978ea30a0b762f0ad2d445b"), (byte[]) args.get(0)); Assert.assertArrayEquals(Hex.decode("d71ebe710322f0a95504cdd12294f613536204ce"), (byte[]) args.get(1)); Assert.assertEquals(ByteUtil.bytesToBigInteger(Hex.decode("002d7982473f00")), args.get(2)); Assert.assertArrayEquals(Hex.decode("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"), (byte[]) args.get(3)); } @Test public void testBytesIndexedParamAnonymous() { String abiJson = "[{\n" + " 'anonymous': true,\n" + " 'inputs': [\n" + " {\n" + " 'indexed': true,\n" + " 'name': 'from',\n" + " 'type': 'address'\n" + " },\n" + " {\n" + " 'indexed': true,\n" + " 'name': 'to',\n" + " 'type': 'address'\n" + " },\n" + " {\n" + " 'indexed': false,\n" + " 'name': 'value',\n" + " 'type': 'uint256'\n" + " },\n" + " {\n" + " 'indexed': true,\n" + " 'name': 'data',\n" + " 'type': 'bytes'\n" + " }\n" + " ],\n" + " 'name': 'Transfer',\n" + " 'type': 'event'\n" + " }]"; CallTransaction.Contract contract = new CallTransaction.Contract(abiJson.replaceAll("'", "\"")); List<DataWord> topics = new ArrayList<>(); topics.add(DataWord.of("000000000000000000000000c9ca2e8db68ffeb21978ea30a0b762f0ad2d445b")); topics.add(DataWord.of("000000000000000000000000d71ebe710322f0a95504cdd12294f613536204ce")); topics.add(DataWord.of("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")); byte[] data = Hex.decode("00000000000000000000000000000000000000000000000000002d7982473f00"); Abi abi = Abi.fromJson(abiJson.replaceAll("'", "\"")); Abi.Event event = abi.findEvent(p -> true); List<?> args = event.decode(data, topics.stream().map(DataWord::getData).collect(Collectors.toList()).toArray(new byte[0][])); Assert.assertEquals(4, args.size()); Assert.assertArrayEquals(Hex.decode("c9ca2e8db68ffeb21978ea30a0b762f0ad2d445b"), (byte[]) args.get(0)); Assert.assertArrayEquals(Hex.decode("d71ebe710322f0a95504cdd12294f613536204ce"), (byte[]) args.get(1)); Assert.assertEquals(ByteUtil.bytesToBigInteger(Hex.decode("002d7982473f00")), args.get(2)); Assert.assertArrayEquals(Hex.decode("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"), (byte[]) args.get(3)); } }
8,152
51.262821
351
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/ConcatKDFBytesGenerator.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum; import org.spongycastle.crypto.DataLengthException; import org.spongycastle.crypto.DerivationParameters; import org.spongycastle.crypto.Digest; import org.spongycastle.crypto.DigestDerivationFunction; import org.spongycastle.crypto.params.ISO18033KDFParameters; import org.spongycastle.crypto.params.KDFParameters; import org.spongycastle.util.Pack; /** * Basic KDF generator for derived keys and ivs as defined by NIST SP 800-56A. */ public class ConcatKDFBytesGenerator implements DigestDerivationFunction { private int counterStart; private Digest digest; private byte[] shared; private byte[] iv; /** * Construct a KDF Parameters generator. * <p> * * @param counterStart * value of counter. * @param digest * the digest to be used as the source of derived keys. */ protected ConcatKDFBytesGenerator(int counterStart, Digest digest) { this.counterStart = counterStart; this.digest = digest; } public ConcatKDFBytesGenerator(Digest digest) { this(1, digest); } public void init(DerivationParameters param) { if (param instanceof KDFParameters) { KDFParameters p = (KDFParameters)param; shared = p.getSharedSecret(); iv = p.getIV(); } else if (param instanceof ISO18033KDFParameters) { ISO18033KDFParameters p = (ISO18033KDFParameters)param; shared = p.getSeed(); iv = null; } else { throw new IllegalArgumentException("KDF parameters required for KDF2Generator"); } } /** * return the underlying digest. */ public Digest getDigest() { return digest; } /** * fill len bytes of the output buffer with bytes generated from the * derivation function. * * @throws IllegalArgumentException * if the size of the request will cause an overflow. * @throws DataLengthException * if the out buffer is too small. */ public int generateBytes(byte[] out, int outOff, int len) throws DataLengthException, IllegalArgumentException { if ((out.length - len) < outOff) { throw new DataLengthException("output buffer too small"); } long oBytes = len; int outLen = digest.getDigestSize(); // // this is at odds with the standard implementation, the // maximum value should be hBits * (2^32 - 1) where hBits // is the digest output size in bits. We can't have an // array with a long index at the moment... // if (oBytes > ((2L << 32) - 1)) { throw new IllegalArgumentException("Output length too large"); } int cThreshold = (int)((oBytes + outLen - 1) / outLen); byte[] dig = new byte[digest.getDigestSize()]; byte[] C = new byte[4]; Pack.intToBigEndian(counterStart, C, 0); int counterBase = counterStart & ~0xFF; for (int i = 0; i < cThreshold; i++) { digest.update(C, 0, C.length); digest.update(shared, 0, shared.length); if (iv != null) { digest.update(iv, 0, iv.length); } digest.doFinal(dig, 0); if (len > outLen) { System.arraycopy(dig, 0, out, outOff, outLen); outOff += outLen; len -= outLen; } else { System.arraycopy(dig, 0, out, outOff, len); } if (++C[3] == 0) { counterBase += 0x100; Pack.intToBigEndian(counterBase, C, 0); } } digest.reset(); return (int)oBytes; } }
4,737
28.067485
92
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/Start.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum; import org.ethereum.cli.CLIInterface; import org.ethereum.config.SystemProperties; import org.ethereum.mine.Ethash; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.Long.parseLong; import static org.apache.commons.lang3.StringUtils.isEmpty; import static org.apache.commons.lang3.math.NumberUtils.toInt; import static org.ethereum.facade.EthereumFactory.createEthereum; /** * @author Roman Mandeleil * @since 14.11.2014 */ public class Start { public static void main(String args[]) { CLIInterface.call(args); final SystemProperties config = SystemProperties.getDefault(); getEthashBlockNumber().ifPresent(blockNumber -> createDagFileAndExit(config, blockNumber)); getBlocksDumpPath(config).ifPresent(dumpPath -> loadDumpAndExit(config, dumpPath)); createEthereum(); } private static void disableSync(SystemProperties config) { config.setSyncEnabled(false); config.setDiscoveryEnabled(false); } private static Optional<Long> getEthashBlockNumber() { String value = System.getProperty("ethash.blockNumber"); return isEmpty(value) ? Optional.empty() : Optional.of(parseLong(value)); } /** * Creates DAG file for specified block number and terminate program execution with 0 code. * * @param config {@link SystemProperties} config instance; * @param blockNumber data set block number; */ private static void createDagFileAndExit(SystemProperties config, Long blockNumber) { disableSync(config); new Ethash(config, blockNumber).getFullDataset(); // DAG file has been created, lets exit System.exit(0); } private static Optional<Path> getBlocksDumpPath(SystemProperties config) { String blocksLoader = config.blocksLoader(); if (isEmpty(blocksLoader)) { return Optional.empty(); } else { Path path = Paths.get(blocksLoader); return Files.exists(path) ? Optional.of(path) : Optional.empty(); } } /** * Loads single or multiple block dumps from specified path, and terminate program execution.<br> * Exit code is 0 in case of successfully dumps loading, 1 otherwise. * * @param config {@link SystemProperties} config instance; * @param path file system path to dump file or directory that contains dumps; */ private static void loadDumpAndExit(SystemProperties config, Path path) { disableSync(config); boolean loaded = false; try { Pattern pattern = Pattern.compile("(\\D+)?(\\d+)?(.*)?"); Path[] paths = Files.isDirectory(path) ? Files.list(path) .sorted(Comparator.comparingInt(filePath -> { String fileName = filePath.getFileName().toString(); Matcher matcher = pattern.matcher(fileName); return matcher.matches() ? toInt(matcher.group(2)) : 0; })) .toArray(Path[]::new) : new Path[]{path}; loaded = createEthereum().getBlockLoader().loadBlocks(paths); } catch (Exception e) { e.printStackTrace(); } System.exit(loaded ? 0 : 1); } }
4,348
34.942149
101
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/cli/CLIInterface.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.cli; import org.apache.commons.lang3.BooleanUtils; import org.ethereum.config.SystemProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Roman Mandeleil * @since 13.11.2014 */ @Component public class CLIInterface { private CLIInterface() { } private static final Logger logger = LoggerFactory.getLogger("general"); public static void call(String[] args) { try { Map<String, Object> cliOptions = new HashMap<>(); for (int i = 0; i < args.length; ++i) { String arg = args[i]; processHelp(arg); // process simple option if (processConnectOnly(arg, cliOptions)) continue; // possible additional parameter if (i + 1 >= args.length) continue; // process options with additional parameter if (processDbDirectory(arg, args[i + 1], cliOptions)) continue; if (processListenPort(arg, args[i + 1], cliOptions)) continue; if (processConnect(arg, args[i + 1], cliOptions)) continue; if (processDbReset(arg, args[i + 1], cliOptions)) continue; } if (cliOptions.size() > 0) { logger.info("Overriding config file with CLI options: {}", cliOptions); } SystemProperties.getDefault().overrideParams(cliOptions); } catch (Throwable e) { logger.error("Error parsing command line: [{}]", e.getMessage()); System.exit(1); } } // show help private static void processHelp(String arg) { if ("--help".equals(arg)) { printHelp(); System.exit(1); } } private static boolean processConnectOnly(String arg, Map<String, Object> cliOptions) { if ("-connectOnly".equals(arg)) return false; cliOptions.put(SystemProperties.PROPERTY_PEER_DISCOVERY_ENABLED, false); return true; } // override the db directory private static boolean processDbDirectory(String arg, String db, Map<String, Object> cliOptions) { if (!"-db".equals(arg)) return false; logger.info("DB directory set to [{}]", db); cliOptions.put(SystemProperties.PROPERTY_DB_DIR, db); return true; } // override the listen port directory private static boolean processListenPort(String arg, String port, Map<String, Object> cliOptions) { if (!"-listen".equals(arg)) return false; logger.info("Listen port set to [{}]", port); cliOptions.put(SystemProperties.PROPERTY_LISTEN_PORT, port); return true; } // override the connect host:port directory private static boolean processConnect(String arg, String connectStr, Map<String, Object> cliOptions) throws URISyntaxException { if (!arg.startsWith("-connect")) return false; logger.info("Connect URI set to [{}]", connectStr); URI uri = new URI(connectStr); if (!"enode".equals(uri.getScheme())) throw new RuntimeException("expecting URL in the format enode://PUBKEY@HOST:PORT"); List<Map<String, String>> peerActiveList = Collections.singletonList(Collections.singletonMap("url", connectStr)); cliOptions.put(SystemProperties.PROPERTY_PEER_ACTIVE, peerActiveList); return true; } // process database reset private static boolean processDbReset(String arg, String reset, Map<String, Object> cliOptions) { if (!"-reset".equals(arg)) return false; Boolean resetFlag = interpret(reset); if (resetFlag == null) { throw new Error(String.format("Can't interpret DB reset arguments: %s %s", arg, reset)); } logger.info("Resetting db set to [{}]", resetFlag); cliOptions.put(SystemProperties.PROPERTY_DB_RESET, resetFlag.toString()); return true; } private static Boolean interpret(String arg) { return BooleanUtils.toBooleanObject(arg); } private static void printHelp() { System.out.println("--help -- this help message "); System.out.println("-reset <yes/no> -- reset yes/no the all database "); System.out.println("-db <db> -- to setup the path for the database directory "); System.out.println("-listen <port> -- port to listen on for incoming connections "); System.out.println("-connect <enode://pubKey@host:port> -- address actively connect to "); System.out.println("-connectOnly <enode://pubKey@host:port> -- like 'connect', but will not attempt to connect to other peers "); System.out.println(); System.out.println("e.g: cli -reset no -db db-1 -listen 20202 -connect enode://0be5b4@poc-7.ethdev.com:30300 "); System.out.println(); } }
6,090
32.467033
139
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/ECKey.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.crypto; /** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.ethereum.config.Constants; import org.ethereum.crypto.jce.ECKeyAgreement; import org.ethereum.crypto.jce.ECKeyFactory; import org.ethereum.crypto.jce.ECKeyPairGenerator; import org.ethereum.crypto.jce.ECSignatureFactory; import org.ethereum.crypto.jce.SpongyCastleProvider; import org.ethereum.util.ByteUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey; import org.spongycastle.jcajce.provider.asymmetric.ec.BCECPublicKey; import org.spongycastle.jce.spec.ECParameterSpec; import org.spongycastle.jce.spec.ECPrivateKeySpec; import org.spongycastle.jce.spec.ECPublicKeySpec; import org.spongycastle.asn1.ASN1InputStream; import org.spongycastle.asn1.ASN1Integer; import org.spongycastle.asn1.DLSequence; import org.spongycastle.asn1.sec.SECNamedCurves; import org.spongycastle.asn1.x9.X9ECParameters; import org.spongycastle.asn1.x9.X9IntegerConverter; import org.spongycastle.crypto.agreement.ECDHBasicAgreement; import org.spongycastle.crypto.digests.SHA256Digest; import org.spongycastle.crypto.engines.AESEngine; import org.spongycastle.crypto.modes.SICBlockCipher; import org.spongycastle.crypto.params.*; import org.spongycastle.crypto.signers.ECDSASigner; import org.spongycastle.crypto.signers.HMacDSAKCalculator; import org.spongycastle.math.ec.ECAlgorithms; import org.spongycastle.math.ec.ECCurve; import org.spongycastle.math.ec.ECPoint; import org.spongycastle.util.BigIntegers; import org.spongycastle.util.encoders.Base64; import org.spongycastle.util.encoders.Hex; import java.io.IOException; import java.io.Serializable; import java.math.BigInteger; import java.nio.charset.Charset; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.Provider; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.ECPrivateKey; import java.security.interfaces.ECPublicKey; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import javax.annotation.Nullable; import javax.crypto.KeyAgreement; import static org.ethereum.util.BIUtil.isLessThan; import static org.ethereum.util.ByteUtil.bigIntegerToBytes; import static org.ethereum.util.ByteUtil.toHexString; /** * <p>Represents an elliptic curve public and (optionally) private key, usable for digital signatures but not encryption. * 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.</p> * * <p>The ECDSA algorithm supports <i>key recovery</i> 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.</p> * * This code is borrowed from the bitcoinj project and altered to fit Ethereum.<br> * See <a href="https://github.com/bitcoinj/bitcoinj/blob/df9f5a479d28c84161de88165917a5cffcba08ca/core/src/main/java/org/bitcoinj/core/ECKey.java"> * bitcoinj on GitHub</a>. */ 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; public static final ECParameterSpec CURVE_SPEC; /** * Equal to CURVE.getN().shiftRight(1), used for canonicalising the S value of a signature. * ECDSA signatures are mutable in the sense that for a given (R, S) pair, * then both (R, S) and (R, N - S mod N) are valid signatures. * Canonical signatures are those where 1 <= S <= N/2 * * See https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#Low_S_values_in_signatures */ public static final BigInteger HALF_CURVE_ORDER; public static final ECKey DUMMY; private static final SecureRandom secureRandom; private static final long serialVersionUID = -728224901792295832L; static { // All clients must agree on the curve to use by agreement. Ethereum uses secp256k1. X9ECParameters params = SECNamedCurves.getByName("secp256k1"); CURVE = new ECDomainParameters(params.getCurve(), params.getG(), params.getN(), params.getH()); CURVE_SPEC = new ECParameterSpec(params.getCurve(), params.getG(), params.getN(), params.getH()); HALF_CURVE_ORDER = params.getN().shiftRight(1); secureRandom = new SecureRandom(); DUMMY = fromPrivate(BigInteger.ONE); } // 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. private final PrivateKey privKey; protected final ECPoint pub; // the Java Cryptographic Architecture provider to use for Signature // this is set along with the PrivateKey privKey and must be compatible // this provider will be used when selecting a Signature instance // https://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html private final Provider provider; // Transient because it's calculated on demand. transient private byte[] pubKeyHash; transient private byte[] nodeId; /** * Generates an entirely new keypair. * * BouncyCastle will be used as the Java Security Provider */ public ECKey() { this(secureRandom); } /* Convert a Java JCE ECPublicKey into a BouncyCastle ECPoint */ private static ECPoint extractPublicKey(final ECPublicKey ecPublicKey) { final java.security.spec.ECPoint publicPointW = ecPublicKey.getW(); final BigInteger xCoord = publicPointW.getAffineX(); final BigInteger yCoord = publicPointW.getAffineY(); return CURVE.getCurve().createPoint(xCoord, yCoord); } /** * Generate a new keypair using the given Java Security Provider. * * All private key operations will use the provider. */ public ECKey(Provider provider, SecureRandom secureRandom) { this.provider = provider; final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom); final KeyPair keyPair = keyPairGen.generateKeyPair(); this.privKey = keyPair.getPrivate(); final PublicKey pubKey = keyPair.getPublic(); if (pubKey instanceof BCECPublicKey) { pub = ((BCECPublicKey) pubKey).getQ(); } else if (pubKey instanceof ECPublicKey) { pub = extractPublicKey((ECPublicKey) pubKey); } else { throw new AssertionError( "Expected Provider " + provider.getName() + " to produce a subtype of ECPublicKey, found " + pubKey.getClass()); } } /** * Generates an entirely new keypair with the given {@link SecureRandom} object. * * BouncyCastle will be used as the Java Security Provider * * @param secureRandom - */ public ECKey(SecureRandom secureRandom) { this(SpongyCastleProvider.getInstance(), secureRandom); } /* Test if a generic private key is an EC private key * * it is not sufficient to check that privKey is a subtype of ECPrivateKey * as the SunPKCS11 Provider will return a generic PrivateKey instance * a fallback that covers this case is to check the key algorithm */ private static boolean isECPrivateKey(PrivateKey privKey) { return privKey instanceof ECPrivateKey || privKey.getAlgorithm().equals("EC"); } /** * Pair a private key with a public EC point. * * All private key operations will use the provider. */ public ECKey(Provider provider, @Nullable PrivateKey privKey, ECPoint pub) { this.provider = provider; if (privKey == null || isECPrivateKey(privKey)) { this.privKey = privKey; } else { throw new IllegalArgumentException( "Expected EC private key, given a private key object with class " + privKey.getClass().toString() + " and algorithm " + privKey.getAlgorithm()); } if (pub == null) { throw new IllegalArgumentException("Public key may not be null"); } if (pub.isInfinity()) { throw new IllegalArgumentException("Public key must not be a point at infinity, probably your private key is incorrect"); } this.pub = pub; } /* Convert a BigInteger into a PrivateKey object */ private static PrivateKey privateKeyFromBigInteger(BigInteger priv) { if (priv == null) { return null; } else { try { return ECKeyFactory .getInstance(SpongyCastleProvider.getInstance()) .generatePrivate(new ECPrivateKeySpec(priv, CURVE_SPEC)); } catch (InvalidKeySpecException ex) { throw new AssertionError("Assumed correct key spec statically"); } } } /** * Pair a private key integer with a public EC point * * BouncyCastle will be used as the Java Security Provider */ public ECKey(@Nullable BigInteger priv, ECPoint pub) { this( SpongyCastleProvider.getInstance(), privateKeyFromBigInteger(priv), 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. * * @param uncompressed - * * @return - * @deprecated per-point compression property will be removed in Bouncy Castle */ public static ECPoint compressPoint(ECPoint uncompressed) { return CURVE.getCurve().decodePoint(uncompressed.getEncoded(true)); } /** * Utility for decompressing an elliptic curve point. Returns the same point if it's already compressed. * See the ECKey class docs for a discussion of point compression. * * @param compressed - * * @return - * @deprecated per-point compression property will be removed in Bouncy Castle */ public static ECPoint decompressPoint(ECPoint compressed) { return CURVE.getCurve().decodePoint(compressed.getEncoded(false)); } /** * Creates an ECKey given the private key only. * * @param privKey - * * * @return - */ public static ECKey fromPrivate(BigInteger privKey) { return new ECKey(privKey, CURVE.getG().multiply(privKey)); } /** * Creates an ECKey given the private key only. * * @param privKeyBytes - * * @return - */ public static ECKey fromPrivate(byte[] privKeyBytes) { return fromPrivate(new BigInteger(1, privKeyBytes)); } /** * Creates an ECKey that simply trusts the caller to ensure that point is really the result of multiplying the * generator point by the private key. This is used to speed things up when you know you have the right values * already. The compression state of pub will be preserved. * * @param priv - * @param pub - * * @return - */ public static ECKey fromPrivateAndPrecalculatedPublic(BigInteger priv, ECPoint pub) { return new ECKey(priv, pub); } /** * Creates an ECKey that simply trusts the caller to ensure that point is really the result of multiplying the * generator point by the private key. This is used to speed things up when you know you have the right values * already. The compression state of the point will be preserved. * * @param priv - * @param pub - * @return - */ public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub) { check(priv != null, "Private key must not be null"); check(pub != null, "Public key must not be null"); return new ECKey(new BigInteger(1, priv), CURVE.getCurve().decodePoint(pub)); } /** * Creates an ECKey that cannot be used for signing, only verifying signatures, from the given point. The * compression state of pub will be preserved. * * @param pub - * @return - */ public static ECKey fromPublicOnly(ECPoint pub) { return new ECKey(null, pub); } /** * Creates an ECKey that cannot be used for signing, only verifying signatures, from the given encoded point. * The compression state of pub will be preserved. * * @param pub - * @return - */ 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. * * @return - * @deprecated per-point compression property will be removed in Bouncy Castle */ public ECKey decompress() { if (!pub.isCompressed()) return this; else return new ECKey(this.provider, this.privKey, decompressPoint(pub)); } /** * @deprecated per-point compression property will be removed in Bouncy Castle */ public ECKey compress() { if (pub.isCompressed()) return this; else return new ECKey(this.provider, this.privKey, compressPoint(pub)); } /** * Returns true if this key doesn't have access to private key bytes. This may be because it was never * given any private key bytes to begin with (a watching key). * * @return - */ public boolean isPubKeyOnly() { return privKey == null; } /** * Returns true if this key has access to private key bytes. Does the opposite of * {@link #isPubKeyOnly()}. * * @return - */ public boolean hasPrivKey() { return privKey != null; } /** * Returns public key bytes from the given private key. To convert a byte array into a BigInteger, use <tt> * new BigInteger(1, bytes);</tt> * * @param privKey - * @param compressed - * @return - */ public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed) { ECPoint point = CURVE.getG().multiply(privKey); return point.getEncoded(compressed); } /** * Compute an address from an encoded public key. * * @param pubBytes an encoded (uncompressed) public key * @return 20-byte address */ public static byte[] computeAddress(byte[] pubBytes) { return HashUtil.sha3omit12( Arrays.copyOfRange(pubBytes, 1, pubBytes.length)); } /** * Compute an address from a public point. * * @param pubPoint a public point * @return 20-byte address */ public static byte[] computeAddress(ECPoint pubPoint) { return computeAddress(pubPoint.getEncoded(/* uncompressed */ false)); } /** * Gets the address form of the public key. * * @return 20-byte address */ public byte[] getAddress() { if (pubKeyHash == null) { pubKeyHash = computeAddress(this.pub); } return pubKeyHash; } /** * Compute the encoded X, Y coordinates of a public point. * * This is the encoded public key without the leading byte. * * @param pubPoint a public point * @return 64-byte X,Y point pair */ public static byte[] pubBytesWithoutFormat(ECPoint pubPoint) { final byte[] pubBytes = pubPoint.getEncoded(/* uncompressed */ false); return Arrays.copyOfRange(pubBytes, 1, pubBytes.length); } /** * Generates the NodeID based on this key, that is the public key without first format byte */ public byte[] getNodeId() { if (nodeId == null) { nodeId = pubBytesWithoutFormat(this.pub); } return nodeId; } /** * Recover the public key from an encoded node id. * * @param nodeId a 64-byte X,Y point pair */ public static ECKey fromNodeId(byte[] nodeId) { check(nodeId.length == 64, "Expected a 64 byte node id"); byte[] pubBytes = new byte[65]; System.arraycopy(nodeId, 0, pubBytes, 1, nodeId.length); pubBytes[0] = 0x04; // uncompressed return ECKey.fromPublicOnly(pubBytes); } /** * Gets the encoded public key value. * * @return 65-byte encoded public key */ public byte[] getPubKey() { return pub.getEncoded(/* compressed */ false); } /** * Gets the public key in the form of an elliptic curve point object from Bouncy Castle. * * @return - */ public ECPoint getPubKeyPoint() { return pub; } /** * Gets the private key in the form of an integer field element. The public key is derived by performing EC * point addition this number of times (i.e. point multiplying). * * * @return - * * @throws java.lang.IllegalStateException if the private key bytes are not available. */ public BigInteger getPrivKey() { if (privKey == null) { throw new MissingPrivateKeyException(); } else if (privKey instanceof BCECPrivateKey) { return ((BCECPrivateKey) privKey).getD(); } else { throw new MissingPrivateKeyException(); } } /** * Returns whether this key is using the compressed form or not. Compressed pubkeys are only 33 bytes, not 64. * * * @return - */ public boolean isCompressed() { return pub.isCompressed(); } public String toString() { StringBuilder b = new StringBuilder(); b.append("pub:").append(toHexString(pub.getEncoded(false))); return b.toString(); } /** * Produce a string rendering of the ECKey INCLUDING the private key. * Unless you absolutely need the private key it is better for security reasons to just use toString(). * * * @return - */ public String toStringWithPrivate() { StringBuilder b = new StringBuilder(); b.append(toString()); if (privKey != null && privKey instanceof BCECPrivateKey) { b.append(" priv:").append(toHexString(((BCECPrivateKey) privKey).getD().toByteArray())); } 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 * components can be useful for doing further EC maths on them. */ public static class ECDSASignature { /** * The two components of the signature. */ public final BigInteger r, s; public byte v; /** * Constructs a signature with the given components. Does NOT automatically canonicalise the signature. * * @param r - * @param s - */ public ECDSASignature(BigInteger r, BigInteger s) { this.r = r; this.s = s; } /** *t * @param r * @param s * @return - */ private static ECDSASignature fromComponents(byte[] r, byte[] s) { return new ECDSASignature(new BigInteger(1, r), new BigInteger(1, s)); } /** * * @param r - * @param s - * @param v - * @return - */ public static ECDSASignature fromComponents(byte[] r, byte[] s, byte v) { ECDSASignature signature = fromComponents(r, s); signature.v = v; return signature; } public boolean validateComponents() { return validateComponents(r, s, v); } public static boolean validateComponents(BigInteger r, BigInteger s, byte v) { if (v != 27 && v != 28) return false; if (isLessThan(r, BigInteger.ONE)) return false; if (isLessThan(s, BigInteger.ONE)) return false; if (!isLessThan(r, Constants.getSECP256K1N())) return false; if (!isLessThan(s, Constants.getSECP256K1N())) return false; return true; } public static ECDSASignature decodeFromDER(byte[] bytes) { ASN1InputStream decoder = null; try { decoder = new ASN1InputStream(bytes); DLSequence seq = (DLSequence) decoder.readObject(); if (seq == null) throw new RuntimeException("Reached past end of ASN.1 stream."); ASN1Integer r, s; try { r = (ASN1Integer) seq.getObjectAt(0); s = (ASN1Integer) seq.getObjectAt(1); } catch (ClassCastException e) { throw new IllegalArgumentException(e); } // OpenSSL deviates from the DER spec by interpreting these values as unsigned, though they should not be // Thus, we always use the positive versions. See: http://r6.ca/blog/20111119T211504Z.html return new ECDSASignature(r.getPositiveValue(), s.getPositiveValue()); } catch (IOException e) { throw new RuntimeException(e); } finally { if (decoder != null) try { decoder.close(); } catch (IOException x) {} } } /** * Will automatically adjust the S component to be less than or equal to half the curve order, if necessary. * This is required because for every signature (r,s) the signature (r, -s (mod N)) is a valid signature of * the same message. However, we dislike the ability to modify the bits of a Ethereum transaction after it's * been signed, as that violates various assumed invariants. Thus in future only one of those forms will be * considered legal and the other will be banned. * * @return - */ public ECDSASignature toCanonicalised() { if (s.compareTo(HALF_CURVE_ORDER) > 0) { // The order of the curve is the number of valid points that exist on that curve. If S is in the upper // half of the number of valid points, then bring it back to the lower half. Otherwise, imagine that // N = 10 // s = 8, so (-8 % 10 == 2) thus both (r, 8) and (r, 2) are valid solutions. // 10 - 8 == 2, giving us always the latter solution, which is canonical. return new ECDSASignature(r, CURVE.getN().subtract(s)); } else { return this; } } /** * * @return - */ public String toBase64() { byte[] sigData = new byte[65]; // 1 header + 32 bytes for R + 32 bytes for S sigData[0] = v; System.arraycopy(bigIntegerToBytes(this.r, 32), 0, sigData, 1, 32); System.arraycopy(bigIntegerToBytes(this.s, 32), 0, sigData, 33, 32); return new String(Base64.encode(sigData), Charset.forName("UTF-8")); } public byte[] toByteArray() { final byte fixedV = this.v >= 27 ? (byte) (this.v - 27) :this.v; return ByteUtil.merge( ByteUtil.bigIntegerToBytes(this.r, 32), ByteUtil.bigIntegerToBytes(this.s, 32), new byte[]{fixedV}); } public String toHex() { return Hex.toHexString(toByteArray()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ECDSASignature signature = (ECDSASignature) o; if (!r.equals(signature.r)) return false; if (!s.equals(signature.s)) return false; return true; } @Override public int hashCode() { int result = r.hashCode(); result = 31 * result + s.hashCode(); return result; } } /** * 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 */ public ECDSASignature doSign(byte[] input) { if (input.length != 32) { throw new IllegalArgumentException("Expected 32 byte input to ECDSA signature, not " + input.length); } // No decryption of private key required. if (privKey == null) throw new MissingPrivateKeyException(); if (privKey instanceof BCECPrivateKey) { ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest())); ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters(((BCECPrivateKey) privKey).getD(), CURVE); signer.init(true, privKeyParams); BigInteger[] components = signer.generateSignature(input); return new ECDSASignature(components[0], components[1]).toCanonicalised(); } else { try { final Signature ecSig = ECSignatureFactory.getRawInstance(provider); ecSig.initSign(privKey); ecSig.update(input); final byte[] derSignature = ecSig.sign(); return ECDSASignature.decodeFromDER(derSignature).toCanonicalised(); } catch (SignatureException | InvalidKeyException ex) { throw new RuntimeException("ECKey signing error", ex); } } } /** * Takes the keccak hash (32 bytes) of data and returns the ECDSA signature * * @param messageHash - * @return - * @throws IllegalStateException if this ECKey does not have the private part. */ public ECDSASignature sign(byte[] messageHash) { ECDSASignature sig = doSign(messageHash); // Now we have to work backwards to figure out the recId needed to recover the signature. int recId = -1; byte[] thisKey = this.pub.getEncoded(/* compressed */ false); for (int i = 0; i < 4; i++) { byte[] k = ECKey.recoverPubBytesFromSignature(i, sig, messageHash); if (k != null && Arrays.equals(k, thisKey)) { recId = i; break; } } if (recId == -1) throw new RuntimeException("Could not construct a recoverable key. This should never happen."); sig.v = (byte) (recId + 27); 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 * * @return - * @throws SignatureException If the public key could not be recovered or if there was a signature format error. */ public static byte[] signatureToKeyBytes(byte[] messageHash, String signatureBase64) throws SignatureException { byte[] signatureEncoded; try { signatureEncoded = Base64.decode(signatureBase64); } catch (RuntimeException e) { // This is what you get back from Bouncy Castle if base64 doesn't decode :( throw new SignatureException("Could not decode base64", e); } // Parse the signature bytes into r/s and the selector value. if (signatureEncoded.length < 65) throw new SignatureException("Signature truncated, expected 65 bytes and got " + signatureEncoded.length); return signatureToKeyBytes( messageHash, ECDSASignature.fromComponents( Arrays.copyOfRange(signatureEncoded, 1, 33), Arrays.copyOfRange(signatureEncoded, 33, 65), (byte) (signatureEncoded[0] & 0xFF))); } public static byte[] signatureToKeyBytes(byte[] messageHash, ECDSASignature sig) throws SignatureException { check(messageHash.length == 32, "messageHash argument has length " + messageHash.length); int header = sig.v; // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y, // 0x1D = second key with even y, 0x1E = second key with odd y if (header < 27 || header > 34) throw new SignatureException("Header byte out of range: " + header); if (header >= 31) { header -= 4; } int recId = header - 27; byte[] key = ECKey.recoverPubBytesFromSignature(recId, sig, messageHash); if (key == null) throw new SignatureException("Could not recover public key from signature"); return key; } /** * Compute the address of the key that signed the given signature. * * @param messageHash 32-byte hash of message * @param signatureBase64 Base-64 encoded signature * @return 20-byte address */ public static byte[] signatureToAddress(byte[] messageHash, String signatureBase64) throws SignatureException { return computeAddress(signatureToKeyBytes(messageHash, signatureBase64)); } /** * Compute the address of the key that signed the given signature. * * @param messageHash 32-byte hash of message * @param sig - * @return 20-byte address */ public static byte[] signatureToAddress(byte[] messageHash, ECDSASignature sig) throws SignatureException { return computeAddress(signatureToKeyBytes(messageHash, sig)); } /** * Compute the key that signed the given signature. * * @param messageHash 32-byte hash of message * @param signatureBase64 Base-64 encoded signature * @return ECKey */ public static ECKey signatureToKey(byte[] messageHash, String signatureBase64) throws SignatureException { final byte[] keyBytes = signatureToKeyBytes(messageHash, signatureBase64); return ECKey.fromPublicOnly(keyBytes); } /** * Compute the key that signed the given signature. * * @param messageHash 32-byte hash of message * @param sig - * @return ECKey */ public static ECKey signatureToKey(byte[] messageHash, ECDSASignature sig) throws SignatureException { final byte[] keyBytes = signatureToKeyBytes(messageHash, sig); return ECKey.fromPublicOnly(keyBytes); } public BigInteger keyAgreement(ECPoint otherParty) { if (privKey == null) { throw new MissingPrivateKeyException(); } else if (privKey instanceof BCECPrivateKey) { final ECDHBasicAgreement agreement = new ECDHBasicAgreement(); agreement.init(new ECPrivateKeyParameters(((BCECPrivateKey) privKey).getD(), CURVE)); return agreement.calculateAgreement(new ECPublicKeyParameters(otherParty, CURVE)); } else { try { final KeyAgreement agreement = ECKeyAgreement.getInstance(this.provider); agreement.init(this.privKey); agreement.doPhase( ECKeyFactory.getInstance(this.provider) .generatePublic(new ECPublicKeySpec(otherParty, CURVE_SPEC)), /* lastPhase */ true); return new BigInteger(1, agreement.generateSecret()); } catch (IllegalStateException | InvalidKeyException | InvalidKeySpecException ex) { throw new RuntimeException("ECDH key agreement failure", ex); } } } /** * Decrypt cipher by AES in SIC(also know as CTR) mode * * @param cipher -proper cipher * @return decrypted cipher, equal length to the cipher. * @deprecated should not use EC private scalar value as an AES key */ public byte[] decryptAES(byte[] cipher){ if (privKey == null) { throw new MissingPrivateKeyException(); } if (!(privKey instanceof BCECPrivateKey)) { throw new UnsupportedOperationException("Cannot use the private key as an AES key"); } AESEngine engine = new AESEngine(); SICBlockCipher ctrEngine = new SICBlockCipher(engine); KeyParameter key = new KeyParameter(BigIntegers.asUnsignedByteArray(((BCECPrivateKey) privKey).getD())); ParametersWithIV params = new ParametersWithIV(key, new byte[16]); ctrEngine.init(false, params); int i = 0; byte[] out = new byte[cipher.length]; while(i < cipher.length){ ctrEngine.processBlock(cipher, i, out, i); i += engine.getBlockSize(); if (cipher.length - i < engine.getBlockSize()) break; } // process left bytes if (cipher.length - i > 0){ byte[] tmpBlock = new byte[16]; System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i); ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0); System.arraycopy(tmpBlock, 0, out, i, cipher.length - i); } return out; } /** * <p>Verifies the given ECDSA signature against the message bytes using the public key bytes.</p> * * <p>When using native ECDSA verification, data must be 32 bytes, and no element may be * larger than 520 bytes.</p> * * @param data Hash of the data to verify. * @param signature signature. * @param pub The public key bytes to use. * * @return - */ public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) { ECDSASigner signer = new ECDSASigner(); ECPublicKeyParameters params = new ECPublicKeyParameters(CURVE.getCurve().decodePoint(pub), CURVE); signer.init(false, params); 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. // 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; } } /** * Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key. * * @param data Hash of the data to verify. * @param signature signature. * @param pub The public key bytes to use. * * @return - */ public static boolean verify(byte[] data, byte[] signature, byte[] pub) { return verify(data, ECDSASignature.decodeFromDER(signature), pub); } /** * Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key. * * @param data Hash of the data to verify. * @param signature signature. * * @return - */ public boolean verify(byte[] data, byte[] signature) { return ECKey.verify(data, signature, getPubKey()); } /** * Verifies the given R/S pair (signature) against a hash using the public key. * * @param sigHash - * @param signature - * @return - */ public boolean verify(byte[] sigHash, ECDSASignature signature) { return ECKey.verify(sigHash, signature, getPubKey()); } /** * Returns true if this pubkey is canonical, i.e. the correct length taking into account compression. * * @return - */ public boolean isPubKeyCanonical() { return isPubKeyCanonical(pub.getEncoded(/* uncompressed */ false)); } /** * Returns true if the given pubkey is canonical, i.e. the correct length taking into account compression. * @param pubkey - * @return - */ public static boolean isPubKeyCanonical(byte[] pubkey) { if (pubkey[0] == 0x04) { // Uncompressed pubkey if (pubkey.length != 65) return false; } else if (pubkey[0] == 0x02 || pubkey[0] == 0x03) { // Compressed pubkey if (pubkey.length != 33) return false; } else return false; return true; } /** * <p>Given the components of a signature and a selector value, recover and return the public key * that generated the signature according to the algorithm in SEC1v2 section 4.1.6.</p> * * <p>The recId is an index from 0 to 3 which indicates which of the 4 possible keys is the correct one. Because * the key recovery operation yields multiple potential keys, the correct key must either be stored alongside the * signature, or you must be willing to try each recId in turn until you find one that outputs the key you are * expecting.</p> * * <p>If this method returns null it means recovery was not possible and recId should be iterated.</p> * * <p>Given the above two points, a correct usage of this method is inside a for loop from 0 to 3, and if the * output is null OR a key that is not the one you expect, you try again with the next recId.</p> * * @param recId Which possible key to recover. * @param sig the R and S components of the signature, wrapped. * @param messageHash Hash of the data that was signed. * @return 65-byte encoded public key */ @Nullable public static byte[] recoverPubBytesFromSignature(int recId, ECDSASignature sig, byte[] messageHash) { check(recId >= 0, "recId must be positive"); check(sig.r.signum() >= 0, "r must be positive"); check(sig.s.signum() >= 0, "s must be positive"); check(messageHash != null, "messageHash must not be null"); // 1.0 For j from 0 to h (h == recId here and the loop is outside this function) // 1.1 Let x = r + jn BigInteger n = CURVE.getN(); // Curve order. BigInteger i = BigInteger.valueOf((long) recId / 2); BigInteger x = sig.r.add(i.multiply(n)); // 1.2. Convert the integer x to an octet string X of length mlen using the conversion routine // specified in Section 2.3.7, where mlen = ⌈(log2 p)/8⌉ or mlen = ⌈m/8⌉. // 1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve point R using the // conversion routine specified in Section 2.3.4. If this conversion routine outputs “invalid”, then // do another iteration of Step 1. // // More concisely, what these points mean is to use X as a compressed public key. ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve(); BigInteger prime = curve.getQ(); // Bouncy Castle is not consistent about the letter it uses for the prime. if (x.compareTo(prime) >= 0) { // Cannot have point co-ordinates larger than this as everything takes place modulo Q. return null; } // Compressed keys require you to know an extra bit of data about the y-coord as there are two possibilities. // So it's encoded in the recId. ECPoint R = decompressKey(x, (recId & 1) == 1); // 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers responsibility). if (!R.multiply(n).isInfinity()) return null; // 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification. BigInteger e = new BigInteger(1, messageHash); // 1.6. For k from 1 to 2 do the following. (loop is outside this function via iterating recId) // 1.6.1. Compute a candidate public key as: // Q = mi(r) * (sR - eG) // // Where mi(x) is the modular multiplicative inverse. We transform this into the following: // Q = (mi(r) * s ** R) + (mi(r) * -e ** G) // Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n). In the above equation // ** is point multiplication and + is point addition (the EC group operator). // // We can find the additive inverse by subtracting e from zero then taking the mod. For example the additive // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8. BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n); BigInteger rInv = sig.r.modInverse(n); BigInteger srInv = rInv.multiply(sig.s).mod(n); BigInteger eInvrInv = rInv.multiply(eInv).mod(n); ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv); // result sanity check: point must not be at infinity if (q.isInfinity()) return null; return q.getEncoded(/* compressed */ false); } /** * * @param recId Which possible key to recover. * @param sig the R and S components of the signature, wrapped. * @param messageHash Hash of the data that was signed. * @return 20-byte address */ @Nullable public static byte[] recoverAddressFromSignature(int recId, ECDSASignature sig, byte[] messageHash) { final byte[] pubBytes = recoverPubBytesFromSignature(recId, sig, messageHash); if (pubBytes == null) { return null; } else { return computeAddress(pubBytes); } } /** * * @param recId Which possible key to recover. * @param sig the R and S components of the signature, wrapped. * @param messageHash Hash of the data that was signed. * @return ECKey */ @Nullable public static ECKey recoverFromSignature(int recId, ECDSASignature sig, byte[] messageHash) { final byte[] pubBytes = recoverPubBytesFromSignature(recId, sig, messageHash); if (pubBytes == null) { return null; } else { return ECKey.fromPublicOnly(pubBytes); } } /** * Decompress a compressed public key (x co-ord and low-bit of y-coord). * * @param xBN - * @param yBit - * @return - */ private static ECPoint decompressKey(BigInteger xBN, boolean yBit) { X9IntegerConverter x9 = new X9IntegerConverter(); byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE.getCurve())); compEnc[0] = (byte) (yBit ? 0x03 : 0x02); return CURVE.getCurve().decodePoint(compEnc); } /** * Returns a 32 byte array containing the private key, or null if the key is encrypted or public only * * @return - */ @Nullable public byte[] getPrivKeyBytes() { if (privKey == null) { return null; } else if (privKey instanceof BCECPrivateKey) { return bigIntegerToBytes(((BCECPrivateKey) privKey).getD(), 32); } else { return null; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof ECKey)) return false; ECKey ecKey = (ECKey) o; if (privKey != null && !privKey.equals(ecKey.privKey)) return false; if (pub != null && !pub.equals(ecKey.pub)) return false; return true; } @Override public int hashCode() { return Arrays.hashCode(getPubKey()); } @SuppressWarnings("serial") public static class MissingPrivateKeyException extends RuntimeException { } private static void check(boolean test, String message) { if (!test) throw new IllegalArgumentException(message); } }
46,166
36.903941
148
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/HashUtil.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.crypto; import org.ethereum.config.SystemProperties; import org.ethereum.crypto.jce.SpongyCastleProvider; import org.ethereum.util.RLP; import org.ethereum.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.crypto.Digest; import org.spongycastle.crypto.digests.RIPEMD160Digest; import org.spongycastle.util.encoders.Hex; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.util.Random; import static java.util.Arrays.copyOfRange; import static org.ethereum.util.ByteUtil.EMPTY_BYTE_ARRAY; import static org.ethereum.util.ByteUtil.bigIntegerToBytes; import static org.ethereum.util.ByteUtil.bytesToBigInteger; public class HashUtil { private static final Logger LOG = LoggerFactory.getLogger(HashUtil.class); public static final byte[] EMPTY_DATA_HASH; public static final byte[] EMPTY_LIST_HASH; public static final byte[] EMPTY_TRIE_HASH; private static final Provider CRYPTO_PROVIDER; private static final String HASH_256_ALGORITHM_NAME; private static final String HASH_512_ALGORITHM_NAME; static { SystemProperties props = SystemProperties.getDefault(); Security.addProvider(SpongyCastleProvider.getInstance()); CRYPTO_PROVIDER = Security.getProvider(props.getCryptoProviderName()); HASH_256_ALGORITHM_NAME = props.getHash256AlgName(); HASH_512_ALGORITHM_NAME = props.getHash512AlgName(); EMPTY_DATA_HASH = sha3(EMPTY_BYTE_ARRAY); EMPTY_LIST_HASH = sha3(RLP.encodeList()); EMPTY_TRIE_HASH = sha3(RLP.encodeElement(EMPTY_BYTE_ARRAY)); } /** * @param input * - data for hashing * @return - sha256 hash of the data */ public static byte[] sha256(byte[] input) { try { MessageDigest sha256digest = MessageDigest.getInstance("SHA-256"); return sha256digest.digest(input); } catch (NoSuchAlgorithmException e) { LOG.error("Can't find such algorithm", e); throw new RuntimeException(e); } } public static byte[] sha3(byte[] input) { MessageDigest digest; try { digest = MessageDigest.getInstance(HASH_256_ALGORITHM_NAME, CRYPTO_PROVIDER); digest.update(input); return digest.digest(); } catch (NoSuchAlgorithmException e) { LOG.error("Can't find such algorithm", e); throw new RuntimeException(e); } } public static byte[] sha3(byte[] input1, byte[] input2) { MessageDigest digest; try { digest = MessageDigest.getInstance(HASH_256_ALGORITHM_NAME, CRYPTO_PROVIDER); digest.update(input1, 0, input1.length); digest.update(input2, 0, input2.length); return digest.digest(); } catch (NoSuchAlgorithmException e) { LOG.error("Can't find such algorithm", e); throw new RuntimeException(e); } } /** * hashing chunk of the data * * @param input * - data for hash * @param start * - start of hashing chunk * @param length * - length of hashing chunk * @return - keccak hash of the chunk */ public static byte[] sha3(byte[] input, int start, int length) { MessageDigest digest; try { digest = MessageDigest.getInstance(HASH_256_ALGORITHM_NAME, CRYPTO_PROVIDER); digest.update(input, start, length); return digest.digest(); } catch (NoSuchAlgorithmException e) { LOG.error("Can't find such algorithm", e); throw new RuntimeException(e); } } public static byte[] sha512(byte[] input) { MessageDigest digest; try { digest = MessageDigest.getInstance(HASH_512_ALGORITHM_NAME, CRYPTO_PROVIDER); digest.update(input); return digest.digest(); } catch (NoSuchAlgorithmException e) { LOG.error("Can't find such algorithm", e); throw new RuntimeException(e); } } /** * @param data * - message to hash * @return - reipmd160 hash of the message */ public static byte[] ripemd160(byte[] data) { Digest digest = new RIPEMD160Digest(); if (data != null) { byte[] resBuf = new byte[digest.getDigestSize()]; digest.update(data, 0, data.length); digest.doFinal(resBuf, 0); return resBuf; } throw new NullPointerException("Can't hash a NULL value"); } /** * Calculates RIGTMOST160(SHA3(input)). This is used in address * calculations. * * * @param input * - data * @return - 20 right bytes of the hash keccak of the data */ public static byte[] sha3omit12(byte[] input) { byte[] hash = sha3(input); return copyOfRange(hash, 12, hash.length); } /** * The way to calculate new address inside ethereum * * @param addr * - creating address * @param nonce * - nonce of creating address * @return new address */ public static byte[] calcNewAddr(byte[] addr, byte[] nonce) { byte[] encSender = RLP.encodeElement(addr); byte[] encNonce = RLP.encodeBigInteger(new BigInteger(1, nonce)); return sha3omit12(RLP.encodeList(encSender, encNonce)); } /** * The way to calculate new address inside ethereum for {@link org.ethereum.vm.OpCode#CREATE2} * sha3(0xff ++ msg.sender ++ salt ++ sha3(init_code)))[12:] * * @param senderAddr - creating address * @param initCode - contract init code * @param salt - salt to make different result addresses * @return new address */ public static byte[] calcSaltAddr(byte[] senderAddr, byte[] initCode, byte[] salt) { // 1 - 0xff length, 32 bytes - keccak-256 byte[] data = new byte[1 + senderAddr.length + salt.length + 32]; data[0] = (byte) 0xff; int currentOffset = 1; System.arraycopy(senderAddr, 0, data, currentOffset, senderAddr.length); currentOffset += senderAddr.length; System.arraycopy(salt, 0, data, currentOffset, salt.length); currentOffset += salt.length; byte[] sha3InitCode = sha3(initCode); System.arraycopy(sha3InitCode, 0, data, currentOffset, sha3InitCode.length); return sha3omit12(data); } /** * @see #doubleDigest(byte[], int, int) * * @param input * - * @return - */ public static byte[] doubleDigest(byte[] input) { return doubleDigest(input, 0, input.length); } /** * Calculates the SHA-256 hash of the given byte range, and then hashes the * resulting hash again. This is standard procedure in Bitcoin. The * resulting hash is in big endian form. * * @param input * - * @param offset * - * @param length * - * @return - */ public static byte[] doubleDigest(byte[] input, int offset, int length) { try { MessageDigest sha256digest = MessageDigest.getInstance("SHA-256"); sha256digest.reset(); sha256digest.update(input, offset, length); byte[] first = sha256digest.digest(); return sha256digest.digest(first); } catch (NoSuchAlgorithmException e) { LOG.error("Can't find such algorithm", e); throw new RuntimeException(e); } } /** * @return generates random peer id for the HelloMessage */ public static byte[] randomPeerId() { byte[] peerIdBytes = new BigInteger(512, Utils.getRandom()).toByteArray(); final String peerId; if (peerIdBytes.length > 64) peerId = Hex.toHexString(peerIdBytes, 1, 64); else peerId = Hex.toHexString(peerIdBytes); return Hex.decode(peerId); } /** * @return - generate random 32 byte hash */ public static byte[] randomHash() { byte[] randomHash = new byte[32]; Random random = new Random(); random.nextBytes(randomHash); return randomHash; } public static String shortHash(byte[] hash) { return Hex.toHexString(hash).substring(0, 6); } }
9,384
32.637993
98
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/MGF1BytesGeneratorExt.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.crypto; import org.spongycastle.crypto.DataLengthException; import org.spongycastle.crypto.DerivationFunction; import org.spongycastle.crypto.DerivationParameters; import org.spongycastle.crypto.Digest; import org.spongycastle.crypto.params.MGFParameters; /** * This class is borrowed from spongycastle project * The only change made is addition of 'counterStart' parameter to * conform to Crypto++ capabilities */ public class MGF1BytesGeneratorExt implements DerivationFunction { private Digest digest; private byte[] seed; private int hLen; private int counterStart; public MGF1BytesGeneratorExt(Digest digest, int counterStart) { this.digest = digest; this.hLen = digest.getDigestSize(); this.counterStart = counterStart; } public void init(DerivationParameters param) { if(!(param instanceof MGFParameters)) { throw new IllegalArgumentException("MGF parameters required for MGF1Generator"); } else { MGFParameters p = (MGFParameters)param; this.seed = p.getSeed(); } } public Digest getDigest() { return this.digest; } private void ItoOSP(int i, byte[] sp) { sp[0] = (byte)(i >>> 24); sp[1] = (byte)(i >>> 16); sp[2] = (byte)(i >>> 8); sp[3] = (byte)(i >>> 0); } public int generateBytes(byte[] out, int outOff, int len) throws DataLengthException, IllegalArgumentException { if(out.length - len < outOff) { throw new DataLengthException("output buffer too small"); } else { byte[] hashBuf = new byte[this.hLen]; byte[] C = new byte[4]; int counter = 0; int hashCounter = counterStart; this.digest.reset(); if(len > this.hLen) { do { this.ItoOSP(hashCounter++, C); this.digest.update(this.seed, 0, this.seed.length); this.digest.update(C, 0, C.length); this.digest.doFinal(hashBuf, 0); System.arraycopy(hashBuf, 0, out, outOff + counter * this.hLen, this.hLen); ++counter; } while(counter < len / this.hLen); } if(counter * this.hLen < len) { this.ItoOSP(hashCounter, C); this.digest.update(this.seed, 0, this.seed.length); this.digest.update(C, 0, C.length); this.digest.doFinal(hashBuf, 0); System.arraycopy(hashBuf, 0, out, outOff + counter * this.hLen, len - counter * this.hLen); } return len; } } }
3,502
35.873684
116
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/ECIESCoder.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.crypto; import com.google.common.base.Throwables; import org.ethereum.ConcatKDFBytesGenerator; import org.spongycastle.crypto.AsymmetricCipherKeyPair; import org.spongycastle.crypto.BufferedBlockCipher; import org.spongycastle.crypto.InvalidCipherTextException; import org.spongycastle.crypto.KeyGenerationParameters; import org.spongycastle.crypto.agreement.ECDHBasicAgreement; import org.spongycastle.crypto.digests.SHA1Digest; import org.spongycastle.crypto.digests.SHA256Digest; import org.spongycastle.crypto.engines.AESEngine; import org.spongycastle.crypto.generators.ECKeyPairGenerator; import org.spongycastle.crypto.generators.EphemeralKeyPairGenerator; import org.spongycastle.crypto.macs.HMac; import org.spongycastle.crypto.modes.SICBlockCipher; import org.spongycastle.crypto.params.*; import org.spongycastle.crypto.parsers.ECIESPublicKeyParser; import org.spongycastle.math.ec.ECPoint; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.security.SecureRandom; import static org.ethereum.crypto.ECKey.CURVE; public class ECIESCoder { public static final int KEY_SIZE = 128; public static byte[] decrypt(BigInteger privKey, byte[] cipher) throws IOException, InvalidCipherTextException { return decrypt(privKey, cipher, null); } public static byte[] decrypt(BigInteger privKey, byte[] cipher, byte[] macData) throws IOException, InvalidCipherTextException { byte[] plaintext; ByteArrayInputStream is = new ByteArrayInputStream(cipher); byte[] ephemBytes = new byte[2*((CURVE.getCurve().getFieldSize()+7)/8) + 1]; is.read(ephemBytes); ECPoint ephem = CURVE.getCurve().decodePoint(ephemBytes); byte[] IV = new byte[KEY_SIZE /8]; is.read(IV); byte[] cipherBody = new byte[is.available()]; is.read(cipherBody); plaintext = decrypt(ephem, privKey, IV, cipherBody, macData); return plaintext; } public static byte[] decrypt(ECPoint ephem, BigInteger prv, byte[] IV, byte[] cipher, byte[] macData) throws InvalidCipherTextException { AESEngine aesFastEngine = new AESEngine(); EthereumIESEngine iesEngine = new EthereumIESEngine( new ECDHBasicAgreement(), new ConcatKDFBytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()), new SHA256Digest(), new BufferedBlockCipher(new SICBlockCipher(aesFastEngine))); byte[] d = new byte[] {}; byte[] e = new byte[] {}; IESParameters p = new IESWithCipherParameters(d, e, KEY_SIZE, KEY_SIZE); ParametersWithIV parametersWithIV = new ParametersWithIV(p, IV); iesEngine.init(false, new ECPrivateKeyParameters(prv, CURVE), new ECPublicKeyParameters(ephem, CURVE), parametersWithIV); return iesEngine.processBlock(cipher, 0, cipher.length, macData); } /** * Encryption equivalent to the Crypto++ default ECIES<ECP> settings: * * DL_KeyAgreementAlgorithm: DL_KeyAgreementAlgorithm_DH<struct ECPPoint,struct EnumToType<enum CofactorMultiplicationOption,0> > * DL_KeyDerivationAlgorithm: DL_KeyDerivationAlgorithm_P1363<struct ECPPoint,0,class P1363_KDF2<class SHA1> > * DL_SymmetricEncryptionAlgorithm: DL_EncryptionAlgorithm_Xor<class HMAC<class SHA1>,0> * DL_PrivateKey: DL_Key<ECPPoint> * DL_PrivateKey_EC<class ECP> * * Used for Whisper V3 */ public static byte[] decryptSimple(BigInteger privKey, byte[] cipher) throws IOException, InvalidCipherTextException { EthereumIESEngine iesEngine = new EthereumIESEngine( new ECDHBasicAgreement(), new MGF1BytesGeneratorExt(new SHA1Digest(), 1), new HMac(new SHA1Digest()), new SHA1Digest(), null); IESParameters p = new IESParameters(null, null, KEY_SIZE); ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[0]); iesEngine.setHashMacKey(false); iesEngine.init(new ECPrivateKeyParameters(privKey, CURVE), parametersWithIV, new ECIESPublicKeyParser(ECKey.CURVE)); return iesEngine.processBlock(cipher, 0, cipher.length); } public static byte[] encrypt(ECPoint toPub, byte[] plaintext) { return encrypt(toPub, plaintext, null); } public static byte[] encrypt(ECPoint toPub, byte[] plaintext, byte[] macData) { ECKeyPairGenerator eGen = new ECKeyPairGenerator(); SecureRandom random = new SecureRandom(); KeyGenerationParameters gParam = new ECKeyGenerationParameters(CURVE, random); eGen.init(gParam); byte[] IV = new byte[KEY_SIZE/8]; new SecureRandom().nextBytes(IV); AsymmetricCipherKeyPair ephemPair = eGen.generateKeyPair(); BigInteger prv = ((ECPrivateKeyParameters)ephemPair.getPrivate()).getD(); ECPoint pub = ((ECPublicKeyParameters)ephemPair.getPublic()).getQ(); EthereumIESEngine iesEngine = makeIESEngine(true, toPub, prv, IV); ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(CURVE, random); ECKeyPairGenerator generator = new ECKeyPairGenerator(); generator.init(keygenParams); ECKeyPairGenerator gen = new ECKeyPairGenerator(); gen.init(new ECKeyGenerationParameters(ECKey.CURVE, random)); byte[] cipher; try { cipher = iesEngine.processBlock(plaintext, 0, plaintext.length, macData); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bos.write(pub.getEncoded(false)); bos.write(IV); bos.write(cipher); return bos.toByteArray(); } catch (InvalidCipherTextException e) { throw Throwables.propagate(e); } catch (IOException e) { throw Throwables.propagate(e); } } /** * Encryption equivalent to the Crypto++ default ECIES<ECP> settings: * * DL_KeyAgreementAlgorithm: DL_KeyAgreementAlgorithm_DH<struct ECPPoint,struct EnumToType<enum CofactorMultiplicationOption,0> > * DL_KeyDerivationAlgorithm: DL_KeyDerivationAlgorithm_P1363<struct ECPPoint,0,class P1363_KDF2<class SHA1> > * DL_SymmetricEncryptionAlgorithm: DL_EncryptionAlgorithm_Xor<class HMAC<class SHA1>,0> * DL_PrivateKey: DL_Key<ECPPoint> * DL_PrivateKey_EC<class ECP> * * Used for Whisper V3 */ public static byte[] encryptSimple(ECPoint pub, byte[] plaintext) throws IOException, InvalidCipherTextException { EthereumIESEngine iesEngine = new EthereumIESEngine( new ECDHBasicAgreement(), new MGF1BytesGeneratorExt(new SHA1Digest(), 1), new HMac(new SHA1Digest()), new SHA1Digest(), null); IESParameters p = new IESParameters(null, null, KEY_SIZE); ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[0]); iesEngine.setHashMacKey(false); ECKeyPairGenerator eGen = new ECKeyPairGenerator(); SecureRandom random = new SecureRandom(); KeyGenerationParameters gParam = new ECKeyGenerationParameters(CURVE, random); eGen.init(gParam); // AsymmetricCipherKeyPairGenerator testGen = new AsymmetricCipherKeyPairGenerator() { // ECKey priv = ECKey.fromPrivate(Hex.decode("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a")); // // @Override // public void init(KeyGenerationParameters keyGenerationParameters) { // } // // @Override // public AsymmetricCipherKeyPair generateKeyPair() { // return new AsymmetricCipherKeyPair(new ECPublicKeyParameters(priv.getPubKeyPoint(), CURVE), // new ECPrivateKeyParameters(priv.getPrivKey(), CURVE)); // } // }; EphemeralKeyPairGenerator ephemeralKeyPairGenerator = new EphemeralKeyPairGenerator(/*testGen*/eGen, new ECIESPublicKeyEncoder()); iesEngine.init(new ECPublicKeyParameters(pub, CURVE), parametersWithIV, ephemeralKeyPairGenerator); return iesEngine.processBlock(plaintext, 0, plaintext.length); } private static EthereumIESEngine makeIESEngine(boolean isEncrypt, ECPoint pub, BigInteger prv, byte[] IV) { AESEngine aesFastEngine = new AESEngine(); EthereumIESEngine iesEngine = new EthereumIESEngine( new ECDHBasicAgreement(), new ConcatKDFBytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()), new SHA256Digest(), new BufferedBlockCipher(new SICBlockCipher(aesFastEngine))); byte[] d = new byte[] {}; byte[] e = new byte[] {}; IESParameters p = new IESWithCipherParameters(d, e, KEY_SIZE, KEY_SIZE); ParametersWithIV parametersWithIV = new ParametersWithIV(p, IV); iesEngine.init(isEncrypt, new ECPrivateKeyParameters(prv, CURVE), new ECPublicKeyParameters(pub, CURVE), parametersWithIV); return iesEngine; } public static int getOverhead() { // 256 bit EC public key, IV, 256 bit MAC return 65 + KEY_SIZE/8 + 32; } }
10,304
40.552419
141
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/ECIESPublicKeyEncoder.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.crypto; import org.ethereum.util.ByteUtil; import org.spongycastle.crypto.KeyEncoder; import org.spongycastle.crypto.params.AsymmetricKeyParameter; import org.spongycastle.crypto.params.ECPublicKeyParameters; /** * Created by Anton Nashatyrev on 01.10.2015. */ public class ECIESPublicKeyEncoder implements KeyEncoder { @Override public byte[] getEncoded(AsymmetricKeyParameter asymmetricKeyParameter) { return ((ECPublicKeyParameters) asymmetricKeyParameter).getQ().getEncoded(false); } }
1,325
38
89
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/EthereumIESEngine.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.crypto; import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; import org.spongycastle.crypto.*; import org.spongycastle.crypto.generators.EphemeralKeyPairGenerator; import org.spongycastle.crypto.params.*; import org.spongycastle.util.Arrays; import org.spongycastle.util.BigIntegers; import org.spongycastle.util.Pack; /** * Support class for constructing integrated encryption cipher * for doing basic message exchanges on top of key agreement ciphers. * Follows the description given in IEEE Std 1363a with a couple of changes * specific to Ethereum: * - Hash the MAC key before use * - Include the encryption IV in the MAC computation */ public class EthereumIESEngine { private final Digest hash; BasicAgreement agree; DerivationFunction kdf; Mac mac; BufferedBlockCipher cipher; byte[] macBuf; boolean forEncryption; CipherParameters privParam, pubParam; IESParameters param; byte[] V; private EphemeralKeyPairGenerator keyPairGenerator; private KeyParser keyParser; private byte[] IV; boolean hashK2 = true; /** * set up for use with stream mode, where the key derivation function * is used to provide a stream of bytes to xor with the message. * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message * @param hash hash ing function * @param cipher the actual cipher */ public EthereumIESEngine( BasicAgreement agree, DerivationFunction kdf, Mac mac, Digest hash, BufferedBlockCipher cipher) { this.agree = agree; this.kdf = kdf; this.mac = mac; this.hash = hash; this.macBuf = new byte[mac.getMacSize()]; this.cipher = cipher; } public void setHashMacKey(boolean hashK2) { this.hashK2 = hashK2; } /** * Initialise the encryptor. * * @param forEncryption whether or not this is encryption/decryption. * @param privParam our private key parameters * @param pubParam the recipient's/sender's public key parameters * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. */ public void init( boolean forEncryption, CipherParameters privParam, CipherParameters pubParam, CipherParameters params) { this.forEncryption = forEncryption; this.privParam = privParam; this.pubParam = pubParam; this.V = new byte[0]; extractParams(params); } /** * Initialise the encryptor. * * @param publicKey the recipient's/sender's public key parameters * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. * @param ephemeralKeyPairGenerator the ephemeral key pair generator to use. */ public void init(AsymmetricKeyParameter publicKey, CipherParameters params, EphemeralKeyPairGenerator ephemeralKeyPairGenerator) { this.forEncryption = true; this.pubParam = publicKey; this.keyPairGenerator = ephemeralKeyPairGenerator; extractParams(params); } /** * Initialise the encryptor. * * @param privateKey the recipient's private key. * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. * @param publicKeyParser the parser for reading the ephemeral public key. */ public void init(AsymmetricKeyParameter privateKey, CipherParameters params, KeyParser publicKeyParser) { this.forEncryption = false; this.privParam = privateKey; this.keyParser = publicKeyParser; extractParams(params); } private void extractParams(CipherParameters params) { if (params instanceof ParametersWithIV) { this.IV = ((ParametersWithIV)params).getIV(); this.param = (IESParameters)((ParametersWithIV)params).getParameters(); } else { this.IV = null; this.param = (IESParameters)params; } } public BufferedBlockCipher getCipher() { return cipher; } public Mac getMac() { return mac; } private byte[] encryptBlock( byte[] in, int inOff, int inLen, byte[] macData) throws InvalidCipherTextException { byte[] C = null, K = null, K1 = null, K2 = null; int len; if (cipher == null) { // Streaming mode. K1 = new byte[inLen]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); // if (V.length != 0) // { // System.arraycopy(K, 0, K2, 0, K2.length); // System.arraycopy(K, K2.length, K1, 0, K1.length); // } // else { System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, inLen, K2, 0, K2.length); } C = new byte[inLen]; for (int i = 0; i != inLen; i++) { C[i] = (byte)(in[inOff + i] ^ K1[i]); } len = inLen; } else { // Block cipher mode. K1 = new byte[((IESWithCipherParameters)param).getCipherKeySize() / 8]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); // If iv provided use it to initialise the cipher if (IV != null) { cipher.init(true, new ParametersWithIV(new KeyParameter(K1), IV)); } else { cipher.init(true, new KeyParameter(K1)); } C = new byte[cipher.getOutputSize(inLen)]; len = cipher.processBytes(in, inOff, inLen, C, 0); len += cipher.doFinal(C, len); } // Convert the length of the encoding vector into a byte array. byte[] P2 = param.getEncodingV(); // Apply the MAC. byte[] T = new byte[mac.getMacSize()]; byte[] K2a; if (hashK2) { K2a = new byte[hash.getDigestSize()]; hash.reset(); hash.update(K2, 0, K2.length); hash.doFinal(K2a, 0); } else { K2a = K2; } mac.init(new KeyParameter(K2a)); mac.update(IV, 0, IV.length); mac.update(C, 0, C.length); if (P2 != null) { mac.update(P2, 0, P2.length); } if (V.length != 0 && P2 != null) { byte[] L2 = new byte[4]; Pack.intToBigEndian(P2.length * 8, L2, 0); mac.update(L2, 0, L2.length); } if (macData != null) { mac.update(macData, 0, macData.length); } mac.doFinal(T, 0); // Output the triple (V,C,T). byte[] Output = new byte[V.length + len + T.length]; System.arraycopy(V, 0, Output, 0, V.length); System.arraycopy(C, 0, Output, V.length, len); System.arraycopy(T, 0, Output, V.length + len, T.length); return Output; } private byte[] decryptBlock( byte[] in_enc, int inOff, int inLen, byte[] macData) throws InvalidCipherTextException { byte[] M = null, K = null, K1 = null, K2 = null; int len; // Ensure that the length of the input is greater than the MAC in bytes if (inLen <= (param.getMacKeySize() / 8)) { throw new InvalidCipherTextException("Length of input must be greater than the MAC"); } if (cipher == null) { // Streaming mode. K1 = new byte[inLen - V.length - mac.getMacSize()]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); // if (V.length != 0) // { // System.arraycopy(K, 0, K2, 0, K2.length); // System.arraycopy(K, K2.length, K1, 0, K1.length); // } // else { System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); } M = new byte[K1.length]; for (int i = 0; i != K1.length; i++) { M[i] = (byte)(in_enc[inOff + V.length + i] ^ K1[i]); } len = K1.length; } else { // Block cipher mode. K1 = new byte[((IESWithCipherParameters)param).getCipherKeySize() / 8]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); // If IV provide use it to initialize the cipher if (IV != null) { cipher.init(false, new ParametersWithIV(new KeyParameter(K1), IV)); } else { cipher.init(false, new KeyParameter(K1)); } M = new byte[cipher.getOutputSize(inLen - V.length - mac.getMacSize())]; len = cipher.processBytes(in_enc, inOff + V.length, inLen - V.length - mac.getMacSize(), M, 0); len += cipher.doFinal(M, len); } // Convert the length of the encoding vector into a byte array. byte[] P2 = param.getEncodingV(); // Verify the MAC. int end = inOff + inLen; byte[] T1 = Arrays.copyOfRange(in_enc, end - mac.getMacSize(), end); byte[] T2 = new byte[T1.length]; byte[] K2a; if (hashK2) { K2a = new byte[hash.getDigestSize()]; hash.reset(); hash.update(K2, 0, K2.length); hash.doFinal(K2a, 0); } else { K2a = K2; } mac.init(new KeyParameter(K2a)); mac.update(IV, 0, IV.length); mac.update(in_enc, inOff + V.length, inLen - V.length - T2.length); if (P2 != null) { mac.update(P2, 0, P2.length); } if (V.length != 0 && P2 != null) { byte[] L2 = new byte[4]; Pack.intToBigEndian(P2.length * 8, L2, 0); mac.update(L2, 0, L2.length); } if (macData != null) { mac.update(macData, 0, macData.length); } mac.doFinal(T2, 0); if (!Arrays.constantTimeAreEqual(T1, T2)) { throw new InvalidCipherTextException("Invalid MAC."); } // Output the message. return Arrays.copyOfRange(M, 0, len); } public byte[] processBlock(byte[] in, int inOff, int inLen) throws InvalidCipherTextException { return processBlock(in, inOff, inLen, null); } public byte[] processBlock( byte[] in, int inOff, int inLen, byte[] macData) throws InvalidCipherTextException { if (forEncryption) { if (keyPairGenerator != null) { EphemeralKeyPair ephKeyPair = keyPairGenerator.generate(); this.privParam = ephKeyPair.getKeyPair().getPrivate(); this.V = ephKeyPair.getEncodedPublicKey(); } } else { if (keyParser != null) { ByteArrayInputStream bIn = new ByteArrayInputStream(in, inOff, inLen); try { this.pubParam = keyParser.readKey(bIn); } catch (IOException e) { throw new InvalidCipherTextException("unable to recover ephemeral public key: " + e.getMessage(), e); } int encLength = (inLen - bIn.available()); this.V = Arrays.copyOfRange(in, inOff, inOff + encLength); } } // Compute the common value and convert to byte array. agree.init(privParam); BigInteger z = agree.calculateAgreement(pubParam); byte[] Z = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z); // Create input to KDF. byte[] VZ; // if (V.length != 0) // { // VZ = new byte[V.length + Z.length]; // System.arraycopy(V, 0, VZ, 0, V.length); // System.arraycopy(Z, 0, VZ, V.length, Z.length); // } // else { VZ = Z; } // Initialise the KDF. DerivationParameters kdfParam; if (kdf instanceof MGF1BytesGeneratorExt) { kdfParam = new MGFParameters(VZ); } else { kdfParam = new KDFParameters(VZ, param.getDerivationV()); } kdf.init(kdfParam); return forEncryption ? encryptBlock(in, inOff, inLen, macData) : decryptBlock(in, inOff, inLen, macData); } }
14,452
30.148707
132
java
ethereumj
ethereumj-master/ethereumj-core/src/main/java/org/ethereum/crypto/jce/ECKeyPairGenerator.java
/* * Copyright (c) [2016] [ <ether.camp> ] * This file is part of the ethereumJ library. * * The ethereumJ library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The ethereumJ library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>. */ package org.ethereum.crypto.jce; import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.SecureRandom; import java.security.spec.ECGenParameterSpec; public final class ECKeyPairGenerator { public static final String ALGORITHM = "EC"; public static final String CURVE_NAME = "secp256k1"; private static final String algorithmAssertionMsg = "Assumed JRE supports EC key pair generation"; private static final String keySpecAssertionMsg = "Assumed correct key spec statically"; private static final ECGenParameterSpec SECP256K1_CURVE = new ECGenParameterSpec(CURVE_NAME); private ECKeyPairGenerator() { } private static class Holder { private static final KeyPairGenerator INSTANCE; static { try { INSTANCE = KeyPairGenerator.getInstance(ALGORITHM); INSTANCE.initialize(SECP256K1_CURVE); } catch (NoSuchAlgorithmException ex) { throw new AssertionError(algorithmAssertionMsg, ex); } catch (InvalidAlgorithmParameterException ex) { throw new AssertionError(keySpecAssertionMsg, ex); } } } public static KeyPair generateKeyPair() { return Holder.INSTANCE.generateKeyPair(); } public static KeyPairGenerator getInstance(final String provider, final SecureRandom random) throws NoSuchProviderException { try { final KeyPairGenerator gen = KeyPairGenerator.getInstance(ALGORITHM, provider); gen.initialize(SECP256K1_CURVE, random); return gen; } catch (NoSuchAlgorithmException ex) { throw new AssertionError(algorithmAssertionMsg, ex); } catch (InvalidAlgorithmParameterException ex) { throw new AssertionError(keySpecAssertionMsg, ex); } } public static KeyPairGenerator getInstance(final Provider provider, final SecureRandom random) { try { final KeyPairGenerator gen = KeyPairGenerator.getInstance(ALGORITHM, provider); gen.initialize(SECP256K1_CURVE, random); return gen; } catch (NoSuchAlgorithmException ex) { throw new AssertionError(algorithmAssertionMsg, ex); } catch (InvalidAlgorithmParameterException ex) { throw new AssertionError(keySpecAssertionMsg, ex); } } }
3,228
34.483516
127
java