org.spongycastle.util.Arrays Java Examples
The following examples show how to use
org.spongycastle.util.Arrays.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KeyChainGroupTest.java From green_android with GNU General Public License v3.0 | 6 votes |
@Test public void deterministicUpgradeEncrypted() throws Exception { group = new KeyChainGroup(PARAMS); final ECKey key = new ECKey(); group.importKeys(key); final KeyCrypterScrypt crypter = new KeyCrypterScrypt(); final KeyParameter aesKey = crypter.deriveKey("abc"); assertTrue(group.isDeterministicUpgradeRequired()); group.encrypt(crypter, aesKey); assertTrue(group.isDeterministicUpgradeRequired()); try { group.upgradeToDeterministic(0, null); fail(); } catch (DeterministicUpgradeRequiresPassword e) { // Expected. } group.upgradeToDeterministic(0, aesKey); assertFalse(group.isDeterministicUpgradeRequired()); final DeterministicSeed deterministicSeed = group.getActiveKeyChain().getSeed(); assertNotNull(deterministicSeed); assertTrue(deterministicSeed.isEncrypted()); byte[] entropy = checkNotNull(group.getActiveKeyChain().toDecrypted(aesKey).getSeed()).getEntropyBytes(); // Check we used the right key: oldest non rotating. byte[] truncatedBytes = Arrays.copyOfRange(key.getSecretBytes(), 0, 16); assertArrayEquals(entropy, truncatedBytes); }
Example #2
Source File: AccountsListWindow.java From ethereumj with MIT License | 6 votes |
@Override public Object getValueAt(int rowIndex, int columnIndex) { if(columnIndex == 0) { return Hex.toHexString(data.get(rowIndex).address); } else if(columnIndex == 1 ){ if(data.get(rowIndex).accountState != null) { return Denomination.toFriendlyString(data.get(rowIndex).accountState.getBalance()); } return "---"; } else { if(data.get(rowIndex).accountState != null) { if(!Arrays.areEqual(data.get(rowIndex).accountState.getCodeHash(), HashUtil.EMPTY_DATA_HASH)) return "Yes"; } return "No"; } }
Example #3
Source File: UtilsTest.java From ethereumj with MIT License | 6 votes |
@Test public void testAddressStringToBytes() { // valid address String HexStr = "6c386a4b26f73c802f34673f7248bb118f97424a"; byte[] expected = Hex.decode(HexStr); byte[] result = Utils.addressStringToBytes(HexStr); assertEquals(Arrays.areEqual(expected, result), true); // invalid address, we removed the last char so it cannot decode HexStr = "6c386a4b26f73c802f34673f7248bb118f97424"; expected = null; result = Utils.addressStringToBytes(HexStr); assertEquals(expected, result); // invalid address, longer than 20 bytes HexStr = new String(Hex.encode("I am longer than 20 bytes, i promise".getBytes())); expected = null; result = Utils.addressStringToBytes(HexStr); assertEquals(expected, result); // invalid address, shorter than 20 bytes HexStr = new String(Hex.encode("I am short".getBytes())); expected = null; result = Utils.addressStringToBytes(HexStr); assertEquals(expected, result); }
Example #4
Source File: KeyChainGroupTest.java From GreenBits with GNU General Public License v3.0 | 6 votes |
@Test public void deterministicUpgradeEncrypted() throws Exception { group = new KeyChainGroup(PARAMS); final ECKey key = new ECKey(); group.importKeys(key); final KeyCrypterScrypt crypter = new KeyCrypterScrypt(); final KeyParameter aesKey = crypter.deriveKey("abc"); assertTrue(group.isDeterministicUpgradeRequired()); group.encrypt(crypter, aesKey); assertTrue(group.isDeterministicUpgradeRequired()); try { group.upgradeToDeterministic(0, null); fail(); } catch (DeterministicUpgradeRequiresPassword e) { // Expected. } group.upgradeToDeterministic(0, aesKey); assertFalse(group.isDeterministicUpgradeRequired()); final DeterministicSeed deterministicSeed = group.getActiveKeyChain().getSeed(); assertNotNull(deterministicSeed); assertTrue(deterministicSeed.isEncrypted()); byte[] entropy = checkNotNull(group.getActiveKeyChain().toDecrypted(aesKey).getSeed()).getEntropyBytes(); // Check we used the right key: oldest non rotating. byte[] truncatedBytes = Arrays.copyOfRange(key.getSecretBytes(), 0, 16); assertArrayEquals(entropy, truncatedBytes); }
Example #5
Source File: KeyChainGroupTest.java From GreenBits with GNU General Public License v3.0 | 6 votes |
@Test public void deterministicUpgradeRotating() throws Exception { group = new KeyChainGroup(PARAMS); group.setLookaheadSize(LOOKAHEAD_SIZE); // Don't want slow tests. long now = Utils.currentTimeSeconds(); ECKey key1 = new ECKey(); Utils.rollMockClock(86400); ECKey key2 = new ECKey(); Utils.rollMockClock(86400); ECKey key3 = new ECKey(); group.importKeys(key2, key1, key3); group.upgradeToDeterministic(now + 10, null); DeterministicSeed seed = group.getActiveKeyChain().getSeed(); assertNotNull(seed); // Check we used the right key: oldest non rotating. byte[] truncatedBytes = Arrays.copyOfRange(key2.getSecretBytes(), 0, 16); assertArrayEquals(seed.getEntropyBytes(), truncatedBytes); }
Example #6
Source File: UtxoLedgerServiceImpl.java From nuls with MIT License | 6 votes |
/** * get UTXO by key * <p> * 根据key获取UTXO * * @param address * @return Coin */ @Override public List<Coin> getAllUtxo(byte[] address) { List<Coin> coinList = new ArrayList<>(); Collection<Entry<byte[], byte[]>> rawList = utxoLedgerUtxoStorageService.getAllUtxoEntryBytes(); for (Entry<byte[], byte[]> coinEntry : rawList) { Coin coin = new Coin(); try { coin.parse(coinEntry.getValue(), 0); } catch (NulsException e) { Log.info("parse coin form db error"); continue; } if (java.util.Arrays.equals(coin.getAddress(), address)) { coin.setTempOwner(coin.getOwner()); coin.setOwner(coinEntry.getKey()); coinList.add(coin); } } return coinList; }
Example #7
Source File: KeyChainGroupTest.java From green_android with GNU General Public License v3.0 | 6 votes |
@Test public void deterministicUpgradeRotating() throws Exception { group = new KeyChainGroup(PARAMS); group.setLookaheadSize(LOOKAHEAD_SIZE); // Don't want slow tests. long now = Utils.currentTimeSeconds(); ECKey key1 = new ECKey(); Utils.rollMockClock(86400); ECKey key2 = new ECKey(); Utils.rollMockClock(86400); ECKey key3 = new ECKey(); group.importKeys(key2, key1, key3); group.upgradeToDeterministic(now + 10, null); DeterministicSeed seed = group.getActiveKeyChain().getSeed(); assertNotNull(seed); // Check we used the right key: oldest non rotating. byte[] truncatedBytes = Arrays.copyOfRange(key2.getSecretBytes(), 0, 16); assertArrayEquals(seed.getEntropyBytes(), truncatedBytes); }
Example #8
Source File: TrieTest.java From gsc-core with GNU Lesser General Public License v3.0 | 6 votes |
@Test public void test1() { TrieImpl trie = new TrieImpl(); int n = 100; for (int i = 1; i < n; i++) { trie.put(RLP.encodeInt(i), String.valueOf(i).getBytes()); } byte[] rootHash1 = trie.getRootHash(); TrieImpl trie2 = new TrieImpl(); for (int i = 1; i < n; i++) { trie2.put(RLP.encodeInt(i), String.valueOf(i).getBytes()); } byte[] rootHash2 = trie2.getRootHash(); Assert.assertTrue(Arrays.areEqual(rootHash1, rootHash2)); }
Example #9
Source File: PrecompiledContractsTest.java From gsc-core with GNU Lesser General Public License v3.0 | 6 votes |
public void convertFromGSCBase58AddressNative() { // 27WnTihwXsqCqpiNedWvtKCZHsLjDt4Hfmf TestNet address DataWord word1 = new DataWord( "3237576e54696877587371437170694e65645776744b435a48734c6a44743448"); DataWord word2 = new DataWord( "666d660000000000000000000000000000000000000000000000000000000000"); byte[] data = new byte[35]; System.arraycopy(word1.getData(), 0, data, 0, word1.getData().length); System.arraycopy(Arrays.copyOfRange(word2.getData(), 0, 3), 0, data, word1.getData().length, 3); PrecompiledContract contract = createPrecompiledContract(convertFromGSCBase58AddressAddr, WITNESS_ADDRESS); byte[] solidityAddress = contract.execute(data).getRight(); Assert.assertArrayEquals(solidityAddress, new DataWord(Hex.decode(WITNESS_ADDRESS_BASE)).getData()); }
Example #10
Source File: ContractEventParser.java From gsc-core with GNU Lesser General Public License v3.0 | 6 votes |
/** * support: uint<m> (m ∈ [8, 256], m % 8 == 0), int<m> (m ∈ [8, 256], m % 8 == 0) uint (solidity * abi will auto convert to uint256) int (solidity abi will auto convert to int256) bool * <p> * otherwise, returns hexString * <p> * This is only for decode Topic. Since Topic and Data use different encode methods when deal * dynamic length types, such as bytes and string. */ protected static String parseTopic(byte[] bytes, String typeStr) { if (ArrayUtils.isEmpty(bytes) || StringUtils.isNullOrEmpty(typeStr)) { return ""; } Type type = basicType(typeStr); if (type == Type.INT_NUMBER) { return DataWord.bigIntValue(bytes); } else if (type == Type.BOOL) { return String.valueOf(!DataWord.isZero(bytes)); } else if (type == Type.ADDRESS) { byte[] last20Bytes = Arrays.copyOfRange(bytes, 12, bytes.length); return Wallet.encode58Check(MUtil.convertToGSCAddress(last20Bytes)); } return Hex.toHexString(bytes); }
Example #11
Source File: ProgramInvokeFactoryImpl.java From gsc-core with GNU Lesser General Public License v3.0 | 6 votes |
/** * This invocation created for contract call contract */ @Override public ProgramInvoke createProgramInvoke(Program program, DataWord toAddress, DataWord callerAddress, DataWord inValue, DataWord tokenValue, DataWord tokenId, long balanceInt, byte[] dataIn, Deposit deposit, boolean isStaticCall, boolean byTestingSuite, long vmStartInUs, long vmShouldEndInUs, long cpuLimit) { DataWord address = toAddress; DataWord origin = program.getOriginAddress(); DataWord caller = callerAddress; DataWord balance = new DataWord(balanceInt); DataWord callValue = inValue; byte[] data = Arrays.clone(dataIn); DataWord lastHash = program.getPrevHash(); DataWord coinbase = program.getCoinbase(); DataWord timestamp = program.getTimestamp(); DataWord number = program.getNumber(); DataWord difficulty = program.getDifficulty(); return new ProgramInvokeImpl(address, origin, caller, balance, callValue, tokenValue, tokenId, data, lastHash, coinbase, timestamp, number, difficulty, deposit, program.getCallDeep() + 1, isStaticCall, byTestingSuite, vmStartInUs, vmShouldEndInUs, cpuLimit); }
Example #12
Source File: ECKeyPair.java From BlockchainWallet-Crypto with GNU General Public License v3.0 | 5 votes |
@Override public ECKeyPair clone() throws CloneNotSupportedException { ECKeyPair c = (ECKeyPair) super.clone(); c.priv = new BigInteger(c.priv.toByteArray()); c.pub = Arrays.clone(pub); c.pubComp = Arrays.clone(pubComp); c.compressed = compressed; return c; }
Example #13
Source File: UtxoLedgerServiceImpl.java From nuls with MIT License | 5 votes |
@Override public Result rollbackUnlockTxCoinData(Transaction tx) throws NulsException { if (tx == null || tx.getCoinData() == null) { return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.NULL_PARAMETER); } try { CoinData coinData = tx.getCoinData(); List<Coin> tos = coinData.getTo(); boolean isExistLockUtxo = false; Coin needUnLockUtxo = null; int needUnLockUtxoIndex = 0; for (Coin to : tos) { if (to.getLockTime() == -1) { isExistLockUtxo = true; needUnLockUtxo = to; break; } needUnLockUtxoIndex++; } if (!isExistLockUtxo) { return ValidateResult.getFailedResult(CLASS_NAME, LedgerErrorCode.UTXO_STATUS_CHANGE); } byte[] txHashBytes = tx.getHash().serialize(); Result result = utxoLedgerUtxoStorageService.saveUtxo(Arrays.concatenate(txHashBytes, new VarInt(needUnLockUtxoIndex).encode()), needUnLockUtxo); if (result.isFailed()) { throw new NulsException(result.getErrorCode()); } return result; } catch (IOException e) { Log.error(e); throw new NulsException(KernelErrorCode.IO_ERROR); } }
Example #14
Source File: UtxoLedgerServiceImpl.java From nuls with MIT License | 5 votes |
private Result rollbackCoinData(Transaction tx) throws IOException, NulsException { byte[] txHashBytes = tx.getHash().serialize(); BatchOperation batch = utxoLedgerUtxoStorageService.createWriteBatch(); CoinData coinData = tx.getCoinData(); if (coinData != null) { // 保存utxo已花费 - from List<Coin> froms = coinData.getFrom(); Coin recovery; for (Coin from : froms) { try { NulsByteBuffer byteBuffer = new NulsByteBuffer(from.getOwner()); NulsDigestData fromTxHash = byteBuffer.readHash(); int fromIndex = (int) byteBuffer.readVarInt(); Transaction fromTx = utxoLedgerTransactionStorageService.getTx(fromTxHash); recovery = fromTx.getCoinData().getTo().get(fromIndex); recovery.setFrom(from.getFrom()); batch.put(from.getOwner(), recovery.serialize()); } catch (IOException e) { Log.error(e); return Result.getFailed(KernelErrorCode.IO_ERROR); } } // 删除utxo - to List<Coin> tos = coinData.getTo(); for (int i = 0, length = tos.size(); i < length; i++) { byte[] owner = Arrays.concatenate(txHashBytes, new VarInt(i).encode()); // Log.info("批量删除:" + Hex.encode(owner)); batch.delete(owner); } // 执行批量 Result batchResult = batch.executeBatch(); if (batchResult.isFailed()) { return batchResult; } } return Result.getSuccess(); }
Example #15
Source File: UtxoLedgerServiceImpl.java From nuls with MIT License | 5 votes |
private Result saveCoinData(Transaction tx) throws IOException { CoinData coinData = tx.getCoinData(); //TestLog+ // Log.info("=============="+tx.getClass().getSimpleName()+"交易:hash-"+tx.getHash().getDigestHex()); //TestLog- if (coinData != null) { BatchOperation batch = utxoLedgerUtxoStorageService.createWriteBatch(); // 删除utxo已花费 - from List<Coin> froms = coinData.getFrom(); for (Coin from : froms) { //TestLog+ // Coin preFrom = utxoLedgerUtxoStorageService.getUtxo(from.()); // if (preFrom != null) { // Log.info("花费:height: +" + tx.getBlockHeight() + ", “+txHash-" + tx.getHash() + ", " + Hex.encode(from.())); // } // Log.info("delete utxo:" + Hex.encode(from.())); //TestLog- batch.delete(from.getOwner()); } // 保存utxo - to byte[] txHashBytes = tx.getHash().serialize(); List<Coin> tos = coinData.getTo(); for (int i = 0, length = tos.size(); i < length; i++) { try { byte[] owner = Arrays.concatenate(txHashBytes, new VarInt(i).encode()); // Log.info("129 save utxo:::" + Hex.encode(owner)); batch.put(owner, tos.get(i).serialize()); } catch (IOException e) { Log.error(e); return Result.getFailed(KernelErrorCode.IO_ERROR); } } // 执行批量 Result batchResult = batch.executeBatch(); if (batchResult.isFailed()) { return batchResult; } } return Result.getSuccess(); }
Example #16
Source File: PerformanceLogger.java From thunder with GNU Affero General Public License v3.0 | 5 votes |
public void measure (String event) { time2 = System.currentTimeMillis(); if (Arrays.contains(Constants.LOG_LEVELS, 1)) { System.out.println((time2 - time1) + " " + event); } time1 = System.currentTimeMillis(); }
Example #17
Source File: PublicKey.java From steem-java-api-wrapper with GNU General Public License v3.0 | 5 votes |
/** * Recreate the address from the public key. * * @return The address. */ @JsonIgnore public String getAddressFromPublicKey() { try { // Recreate the address from the public key. return this.prefix + Base58.encode(Bytes.concat(this.toByteArray(), Arrays.copyOfRange(calculateChecksum(this.toByteArray()), 0, CHECKSUM_BYTES))); } catch (SteemInvalidTransactionException | NullPointerException e) { LOGGER.debug("An error occured while generating an address from a public key.", e); return ""; } }
Example #18
Source File: KeyChainGroupTest.java From GreenBits with GNU General Public License v3.0 | 5 votes |
@Test public void deterministicUpgradeUnencrypted() throws Exception { // Check that a group that contains only random keys has its HD chain created using the private key bytes of // the oldest random key, so upgrading the same wallet twice gives the same outcome. group = new KeyChainGroup(PARAMS); group.setLookaheadSize(LOOKAHEAD_SIZE); // Don't want slow tests. ECKey key1 = new ECKey(); Utils.rollMockClock(86400); ECKey key2 = new ECKey(); group.importKeys(key2, key1); List<Protos.Key> protobufs = group.serializeToProtobuf(); group.upgradeToDeterministic(0, null); assertFalse(group.isDeterministicUpgradeRequired()); DeterministicKey dkey1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicSeed seed1 = group.getActiveKeyChain().getSeed(); assertNotNull(seed1); group = KeyChainGroup.fromProtobufUnencrypted(PARAMS, protobufs); group.upgradeToDeterministic(0, null); // Should give same result as last time. DeterministicKey dkey2 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicSeed seed2 = group.getActiveKeyChain().getSeed(); assertEquals(seed1, seed2); assertEquals(dkey1, dkey2); // Check we used the right (oldest) key despite backwards import order. byte[] truncatedBytes = Arrays.copyOfRange(key1.getSecretBytes(), 0, 16); assertArrayEquals(seed1.getEntropyBytes(), truncatedBytes); }
Example #19
Source File: KeyChainGroupTest.java From green_android with GNU General Public License v3.0 | 5 votes |
@Test public void deterministicUpgradeUnencrypted() throws Exception { // Check that a group that contains only random keys has its HD chain created using the private key bytes of // the oldest random key, so upgrading the same wallet twice gives the same outcome. group = new KeyChainGroup(PARAMS); group.setLookaheadSize(LOOKAHEAD_SIZE); // Don't want slow tests. ECKey key1 = new ECKey(); Utils.rollMockClock(86400); ECKey key2 = new ECKey(); group.importKeys(key2, key1); List<Protos.Key> protobufs = group.serializeToProtobuf(); group.upgradeToDeterministic(0, null); assertFalse(group.isDeterministicUpgradeRequired()); DeterministicKey dkey1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicSeed seed1 = group.getActiveKeyChain().getSeed(); assertNotNull(seed1); group = KeyChainGroup.fromProtobufUnencrypted(PARAMS, protobufs); group.upgradeToDeterministic(0, null); // Should give same result as last time. DeterministicKey dkey2 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); DeterministicSeed seed2 = group.getActiveKeyChain().getSeed(); assertEquals(seed1, seed2); assertEquals(dkey1, dkey2); // Check we used the right (oldest) key despite backwards import order. byte[] truncatedBytes = Arrays.copyOfRange(key1.getSecretBytes(), 0, 16); assertArrayEquals(seed1.getEntropyBytes(), truncatedBytes); }
Example #20
Source File: ECKeyPair.java From BlockchainWallet-Crypto with GNU General Public License v3.0 | 5 votes |
@Override public byte[] getRawPublicKey(boolean isCompressed) { if (isCompressed) { return Arrays.clone(pubComp); } else { return Arrays.clone(pub); } }
Example #21
Source File: PerformanceLogger.java From thundernetwork with GNU Affero General Public License v3.0 | 5 votes |
public void measure (String event) { time2 = System.currentTimeMillis(); if (Arrays.contains(Constants.LOG_LEVELS, 1)) { System.out.println((time2 - time1) + " " + event); } time1 = System.currentTimeMillis(); }
Example #22
Source File: ECPublicKey.java From BlockchainWallet-Crypto with GNU General Public License v3.0 | 5 votes |
@Override public byte[] getRawPublicKey(boolean isCompressed) { if (!isCompressed) { throw new RuntimeException("No compressed public key"); } return Arrays.clone(pub); }
Example #23
Source File: DataWord.java From ethereumj with MIT License | 5 votes |
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DataWord dataWord = (DataWord) o; if (!java.util.Arrays.equals(data, dataWord.data)) return false; return true; }
Example #24
Source File: DataWord.java From gsc-core with GNU Lesser General Public License v3.0 | 5 votes |
@Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DataWord dataWord = (DataWord) o; return java.util.Arrays.equals(data, dataWord.data); }
Example #25
Source File: SerpentCompiler.java From ethereumj with MIT License | 5 votes |
/** * * @param code * @param init * @return encoded bytes */ public static byte[] encodeMachineCodeForVMRun(byte[] code, byte[] init) { if (code == null || code.length == 0) throw new RuntimeException("code can't be empty code: " + code); int numBytes = ByteUtil.numBytes(code.length + ""); byte[] lenBytes = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(code.length)); StringBuffer sb = new StringBuffer(); for (int i = 0; i < lenBytes.length; ++i) { sb.append(lenBytes[i]).append(" "); } // calc real code start position (after the init header) int pos = 10 + numBytes * 2; if (init != null) pos+=init.length; // @push_len @len PUSH1 @src_start PUSH1 0 CODECOPY @push_len @len 0 PUSH1 0 RETURN String header = String.format("[asm %s %s PUSH1 %d PUSH1 0 CODECOPY %s %s PUSH1 0 RETURN asm]", "PUSH" + numBytes, sb.toString(), pos , "PUSH" + numBytes, sb.toString()); byte[] headerMachine = compileAssemblyToMachine(header); byte[] result = init != null ? Arrays.concatenate(init, headerMachine, code) : Arrays.concatenate(headerMachine, code); return result; }
Example #26
Source File: AccountState.java From ethereumj with MIT License | 5 votes |
public String toString() { String ret = "Nonce: " + this.getNonce().toString() + "\n" + "Balance: " + Denomination.toFriendlyString(getBalance()) + "\n"; if(this.getStateRoot()!= null && !Arrays.areEqual(this.getStateRoot(), EMPTY_BYTE_ARRAY)) ret += "State Root: " + Hex.toHexString(this.getStateRoot()) + "\n"; if(this.getCodeHash() != null && !Arrays.areEqual(this.getCodeHash(), EMPTY_DATA_HASH)) ret += "Code Hash: " + Hex.toHexString(this.getCodeHash()); return ret; }
Example #27
Source File: BlockHeader.java From ethereumj with MIT License | 5 votes |
/** * Verify that block is valid for its difficulty * * @return boolean */ public boolean validateNonce() { BigInteger max = BigInteger.valueOf(2).pow(256); byte[] target = BigIntegers.asUnsignedByteArray(32, max.divide(new BigInteger(1, this.getDifficulty()))); byte[] hash = HashUtil.sha3(this.getEncodedWithoutNonce()); byte[] concat = Arrays.concatenate(hash, this.getNonce()); byte[] result = HashUtil.sha3(concat); return FastByteComparisons.compareTo(result, 0, 32, target, 0, 32) < 0; }
Example #28
Source File: TrieTest.java From gsc-core with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void test() { TrieImpl trie = new TrieImpl(); trie.put(new byte[]{1}, c.getBytes()); Assert.assertTrue(Arrays.areEqual(trie.get(RLP.encodeInt(1)), c.getBytes())); trie.put(new byte[]{1, 0}, ca.getBytes()); trie.put(new byte[]{1, 1}, cat.getBytes()); trie.put(new byte[]{1, 2}, dog.getBytes()); trie.put(RLP.encodeInt(5), doge.getBytes()); trie.put(RLP.encodeInt(6), doge.getBytes()); trie.put(RLP.encodeInt(7), doge.getBytes()); trie.put(RLP.encodeInt(11), doge.getBytes()); trie.put(RLP.encodeInt(12), dude.getBytes()); trie.put(RLP.encodeInt(13), test.getBytes()); trie.delete(RLP.encodeInt(3)); byte[] rootHash = trie.getRootHash(); TrieImpl trieCopy = new TrieImpl(trie.getCache(), rootHash); Assert.assertNull(trie.prove(RLP.encodeInt(111))); Map<byte[], Node> map = trieCopy.prove(new byte[]{1, 1}); boolean result = trie .verifyProof(trieCopy.getRootHash(), new byte[]{1, 1}, (LinkedHashMap<byte[], Node>) map); Assert.assertTrue(result); System.out.println(trieCopy.prove(RLP.encodeInt(5))); System.out.println(trieCopy.prove(RLP.encodeInt(6))); assertTrue(RLP.encodeInt(5), trieCopy); assertTrue(RLP.encodeInt(5), RLP.encodeInt(6), trieCopy); assertTrue(RLP.encodeInt(6), trieCopy); assertTrue(RLP.encodeInt(6), RLP.encodeInt(5), trieCopy); // trie.put(RLP.encodeInt(5), doge.getBytes()); byte[] rootHash2 = trie.getRootHash(); Assert.assertFalse(Arrays.areEqual(rootHash, rootHash2)); trieCopy = new TrieImpl(trie.getCache(), rootHash2); // assertTrue(RLP.encodeInt(5), trieCopy); assertFalse(RLP.encodeInt(5), RLP.encodeInt(6), trieCopy); assertTrue(RLP.encodeInt(6), trieCopy); assertFalse(RLP.encodeInt(6), RLP.encodeInt(5), trieCopy); }
Example #29
Source File: Miner.java From ethereumj with MIT License | 4 votes |
/** * Adds a nonce to given block which complies with the given difficulty * * For the PoC series, we use a simplified proof-of-work. * This is not ASIC resistant and is meant merely as a placeholder. * It utilizes the bare SHA3 hash function to secure the block chain by requiring * the SHA3 hash of the concatenation of the nonce and the header’s SHA3 hash to be * sufficiently low. It is formally defined as PoW: * * PoW(H, n) ≡ BE(SHA3(SHA3(RLP(H!n)) ◦ n)) * * where: * RLP(H!n) is the RLP encoding of the block header H, not including the * final nonce component; * SHA3 is the SHA3 hash function accepting an arbitrary length series of * bytes and evaluating to a series of 32 bytes (i.e. 256-bit); * n is the nonce, a series of 32 bytes; * o is the series concatenation operator; * BE(X) evaluates to the value equal to X when interpreted as a * big-endian-encoded integer. * * @param newBlock without a valid nonce * @param difficulty - the mining difficulty * @return true if valid nonce has been added to the block */ public boolean mine(Block newBlock, byte[] difficulty) { BigInteger max = BigInteger.valueOf(2).pow(256); byte[] target = BigIntegers.asUnsignedByteArray(32, max.divide(new BigInteger(1, difficulty))); byte[] hash = HashUtil.sha3(newBlock.getEncodedWithoutNonce()); byte[] testNonce = new byte[32]; byte[] concat; while(ByteUtil.increment(testNonce)) { concat = Arrays.concatenate(hash, testNonce); byte[] result = HashUtil.sha3(concat); if(FastByteComparisons.compareTo(result, 0, 32, target, 0, 32) < 0) { newBlock.setNonce(testNonce); // System.out.println(Hex.toHexString(newBlock.getEncoded())); return true; } } return false; // couldn't find a valid nonce }
Example #30
Source File: ProgramInvokeMockImpl.java From gsc-core with GNU Lesser General Public License v3.0 | 4 votes |
public ProgramInvokeMockImpl(byte[] msgDataRaw) { this(); this.msgData = Arrays.clone(msgDataRaw); }