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 |
|---|---|---|---|---|---|---|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/core/AbstractFullPrunedBlockChainTest.java
|
/*
* Copyright 2012 Google Inc.
* Copyright 2012 Matt Corallo.
*
* 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.
*/
package org.bitcoinj.core;
import com.google.common.collect.Lists;
import org.bitcoinj.base.Address;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.Coin;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.UnitTestParams;
import org.bitcoinj.script.Script;
import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.store.FullPrunedBlockStore;
import org.bitcoinj.utils.BlockFileLoader;
import org.bitcoinj.utils.BriefLogFormatter;
import org.bitcoinj.wallet.SendRequest;
import org.bitcoinj.wallet.Wallet;
import org.bitcoinj.wallet.WalletTransaction;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.List;
import static org.bitcoinj.base.Coin.FIFTY_COINS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
/**
* We don't do any wallet tests here, we leave that to {@link ChainSplitTest}
*/
public abstract class AbstractFullPrunedBlockChainTest {
@org.junit.Rule
public ExpectedException thrown = ExpectedException.none();
private static final Logger log = LoggerFactory.getLogger(AbstractFullPrunedBlockChainTest.class);
protected static NetworkParameters PARAMS;
private static final NetworkParameters MAINNET = MainNetParams.get();
protected FullPrunedBlockChain chain;
protected FullPrunedBlockStore store;
@BeforeClass
public static void setUpClass() {
TimeUtils.clearMockClock();
PARAMS = new UnitTestParams() {
@Override public int getInterval() {
return 10000;
}
};
}
@Before
public void setUp() {
BriefLogFormatter.init();
Context.propagate(new Context(100, Coin.ZERO, false, false));
}
public abstract FullPrunedBlockStore createStore(NetworkParameters params, int blockCount)
throws BlockStoreException;
public abstract void resetStore(FullPrunedBlockStore store) throws BlockStoreException;
@Test
public void testGeneratedChain() throws Exception {
// Tests various test cases from FullBlockTestGenerator
FullBlockTestGenerator generator = new FullBlockTestGenerator(PARAMS);
RuleList blockList = generator.getBlocksToTest(false, false, null);
store = createStore(PARAMS, blockList.maximumReorgBlockCount);
chain = new FullPrunedBlockChain(PARAMS, store);
for (Rule rule : blockList.list) {
if (!(rule instanceof FullBlockTestGenerator.BlockAndValidity))
continue;
FullBlockTestGenerator.BlockAndValidity block = (FullBlockTestGenerator.BlockAndValidity) rule;
log.info("Testing rule " + block.ruleName + " with block hash " + block.block.getHash());
boolean threw = false;
try {
if (chain.add(block.block) != block.connects) {
log.error("Block didn't match connects flag on block " + block.ruleName);
fail();
}
} catch (VerificationException e) {
threw = true;
if (!block.throwsException) {
log.error("Block didn't match throws flag on block " + block.ruleName);
throw e;
}
if (block.connects) {
log.error("Block didn't match connects flag on block " + block.ruleName);
fail();
}
}
if (!threw && block.throwsException) {
log.error("Block didn't match throws flag on block " + block.ruleName);
fail();
}
if (!chain.getChainHead().getHeader().getHash().equals(block.hashChainTipAfterBlock)) {
log.error("New block head didn't match the correct value after block " + block.ruleName);
fail();
}
if (chain.getChainHead().getHeight() != block.heightAfterBlock) {
log.error("New block head didn't match the correct height after block " + block.ruleName);
fail();
}
}
try {
store.close();
} catch (Exception e) {}
}
@Test
public void skipScripts() throws Exception {
store = createStore(PARAMS, 10);
chain = new FullPrunedBlockChain(PARAMS, store);
// Check that we aren't accidentally leaving any references
// to the full StoredUndoableBlock's lying around (ie memory leaks)
ECKey outKey = new ECKey();
int height = 1;
// Build some blocks on genesis block to create a spendable output
Block rollingBlock = PARAMS.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++);
chain.add(rollingBlock);
TransactionOutput spendableOutput = rollingBlock.getTransactions().get(0).getOutput(0);
for (int i = 1; i < PARAMS.getSpendableCoinbaseDepth(); i++) {
rollingBlock = rollingBlock.createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++);
chain.add(rollingBlock);
}
rollingBlock = rollingBlock.createNextBlock(null);
Transaction t = new Transaction();
t.addOutput(new TransactionOutput(t, FIFTY_COINS, new byte[] {}));
TransactionInput input = t.addInput(spendableOutput);
// Invalid script.
input.clearScriptBytes();
rollingBlock.addTransaction(t);
rollingBlock.solve();
chain.setRunScripts(false);
try {
chain.add(rollingBlock);
} catch (VerificationException e) {
fail();
}
try {
store.close();
} catch (Exception e) {}
}
@Test
public void testFinalizedBlocks() throws Exception {
final int UNDOABLE_BLOCKS_STORED = 10;
store = createStore(PARAMS, UNDOABLE_BLOCKS_STORED);
chain = new FullPrunedBlockChain(PARAMS, store);
// Check that we aren't accidentally leaving any references
// to the full StoredUndoableBlock's lying around (ie memory leaks)
ECKey outKey = new ECKey();
int height = 1;
// Build some blocks on genesis block to create a spendable output
Block rollingBlock = PARAMS.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++);
chain.add(rollingBlock);
TransactionOutput spendableOutput = rollingBlock.getTransactions().get(0).getOutput(0);
TransactionOutPoint transactionOutPoint = spendableOutput.getOutPointFor();
Script spendableOutputScriptPubKey = spendableOutput.getScriptPubKey();
for (int i = 1; i < PARAMS.getSpendableCoinbaseDepth(); i++) {
rollingBlock = rollingBlock.createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++);
chain.add(rollingBlock);
}
WeakReference<UTXO> out = new WeakReference<>
(store.getTransactionOutput(transactionOutPoint.hash(), transactionOutPoint.index()));
rollingBlock = rollingBlock.createNextBlock(null);
Transaction t = new Transaction();
// Entirely invalid scriptPubKey
t.addOutput(new TransactionOutput(t, FIFTY_COINS, new byte[]{}));
t.addSignedInput(transactionOutPoint, spendableOutputScriptPubKey, spendableOutput.getValue(), outKey);
rollingBlock.addTransaction(t);
rollingBlock.solve();
chain.add(rollingBlock);
WeakReference<StoredUndoableBlock> undoBlock = new WeakReference<>(store.getUndoBlock(rollingBlock.getHash()));
StoredUndoableBlock storedUndoableBlock = undoBlock.get();
assertNotNull(storedUndoableBlock);
assertNull(storedUndoableBlock.getTransactions());
WeakReference<TransactionOutputChanges> changes = new WeakReference<>(storedUndoableBlock.getTxOutChanges());
assertNotNull(changes.get());
storedUndoableBlock = null; // Blank the reference so it can be GCd.
// Create a chain longer than UNDOABLE_BLOCKS_STORED
for (int i = 0; i < UNDOABLE_BLOCKS_STORED; i++) {
rollingBlock = rollingBlock.createNextBlock(null);
chain.add(rollingBlock);
}
// Try to get the garbage collector to run
System.gc();
assertNull(undoBlock.get());
assertNull(changes.get());
assertNull(out.get());
try {
store.close();
} catch (Exception e) {}
}
@Test
public void testFirst100KBlocks() throws Exception {
File blockFile = new File(getClass().getResource("first-100k-blocks.dat").getFile());
BlockFileLoader loader = new BlockFileLoader(BitcoinNetwork.MAINNET, Arrays.asList(blockFile));
store = createStore(MAINNET, 10);
resetStore(store);
chain = new FullPrunedBlockChain(MAINNET, store);
for (Block block : loader)
chain.add(block);
try {
store.close();
} catch (Exception e) {}
}
@Test
public void testGetOpenTransactionOutputs() throws Exception {
final int UNDOABLE_BLOCKS_STORED = 10;
store = createStore(PARAMS, UNDOABLE_BLOCKS_STORED);
chain = new FullPrunedBlockChain(PARAMS, store);
// Check that we aren't accidentally leaving any references
// to the full StoredUndoableBlock's lying around (ie memory leaks)
ECKey outKey = new ECKey();
int height = 1;
// Build some blocks on genesis block to create a spendable output
Block rollingBlock = PARAMS.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++);
chain.add(rollingBlock);
Transaction transaction = rollingBlock.getTransactions().get(0);
TransactionOutput spendableOutput = transaction.getOutput(0);
TransactionOutPoint spendableOutputPoint = spendableOutput.getOutPointFor();
Script spendableOutputScriptPubKey = spendableOutput.getScriptPubKey();
for (int i = 1; i < PARAMS.getSpendableCoinbaseDepth(); i++) {
rollingBlock = rollingBlock.createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++);
chain.add(rollingBlock);
}
rollingBlock = rollingBlock.createNextBlock(null);
// Create bitcoin spend of 1 BTC.
ECKey toKey = new ECKey();
Coin amount = Coin.valueOf(100000000);
Address address = toKey.toAddress(ScriptType.P2PKH, PARAMS.network());
Coin totalAmount = Coin.ZERO;
Transaction t = new Transaction();
t.addOutput(new TransactionOutput(t, amount, toKey));
t.addSignedInput(spendableOutputPoint, spendableOutputScriptPubKey, spendableOutput.getValue(), outKey);
rollingBlock.addTransaction(t);
rollingBlock.solve();
chain.add(rollingBlock);
totalAmount = totalAmount.add(amount);
List<UTXO> outputs = store.getOpenTransactionOutputs(Lists.newArrayList(toKey));
assertNotNull(outputs);
assertEquals("Wrong Number of Outputs", 1, outputs.size());
UTXO output = outputs.get(0);
assertEquals("The address is not equal", address.toString(), output.getAddress());
assertEquals("The amount is not equal", totalAmount, output.getValue());
outputs = null;
output = null;
try {
store.close();
} catch (Exception e) {}
}
@Test
public void testUTXOProviderWithWallet() throws Exception {
final int UNDOABLE_BLOCKS_STORED = 10;
store = createStore(PARAMS, UNDOABLE_BLOCKS_STORED);
chain = new FullPrunedBlockChain(PARAMS, store);
// Check that we aren't accidentally leaving any references
// to the full StoredUndoableBlock's lying around (ie memory leaks)
ECKey outKey = new ECKey();
int height = 1;
// Build some blocks on genesis block to create a spendable output.
Block rollingBlock = PARAMS.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++);
chain.add(rollingBlock);
Transaction transaction = rollingBlock.getTransactions().get(0);
TransactionOutput spendableOutput = transaction.getOutput(0);
TransactionOutPoint spendableOutPoint = new TransactionOutPoint(0, transaction.getTxId());
Script spendableOutputScriptPubKey = spendableOutput.getScriptPubKey();
for (int i = 1; i < PARAMS.getSpendableCoinbaseDepth(); i++) {
rollingBlock = rollingBlock.createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, outKey.getPubKey(), height++);
chain.add(rollingBlock);
}
rollingBlock = rollingBlock.createNextBlock(null);
// Create 1 BTC spend to a key in this wallet (to ourselves).
Wallet wallet = Wallet.createDeterministic(PARAMS.network(), ScriptType.P2PKH);
assertEquals("Available balance is incorrect", Coin.ZERO, wallet.getBalance(Wallet.BalanceType.AVAILABLE));
assertEquals("Estimated balance is incorrect", Coin.ZERO, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
wallet.setUTXOProvider(store);
ECKey toKey = wallet.freshReceiveKey();
Coin amount = Coin.valueOf(100000000);
Transaction t = new Transaction();
t.addOutput(new TransactionOutput(t, amount, toKey));
t.addSignedInput(spendableOutPoint, spendableOutputScriptPubKey, spendableOutput.getValue(), outKey);
rollingBlock.addTransaction(t);
rollingBlock.solve();
chain.add(rollingBlock);
// Create another spend of 1/2 the value of BTC we have available using the wallet (store coin selector).
ECKey toKey2 = new ECKey();
Coin amount2 = amount.divide(2);
Address address2 = toKey2.toAddress(ScriptType.P2PKH, PARAMS.network());
SendRequest req = SendRequest.to(address2, amount2);
wallet.completeTx(req);
wallet.commitTx(req.tx);
Coin fee = Coin.ZERO;
// There should be one pending tx (our spend).
assertEquals("Wrong number of PENDING.4", 1, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
Coin totalPendingTxAmount = Coin.ZERO;
for (Transaction tx : wallet.getPendingTransactions()) {
totalPendingTxAmount = totalPendingTxAmount.add(tx.getValueSentToMe(wallet));
}
// The available balance should be the 0 (as we spent the 1 BTC that's pending) and estimated should be 1/2 - fee BTC
assertEquals("Available balance is incorrect", Coin.ZERO, wallet.getBalance(Wallet.BalanceType.AVAILABLE));
assertEquals("Estimated balance is incorrect", amount2.subtract(fee), wallet.getBalance(Wallet.BalanceType.ESTIMATED));
assertEquals("Pending tx amount is incorrect", amount2.subtract(fee), totalPendingTxAmount);
try {
store.close();
} catch (Exception e) {}
}
/**
* Test that if the block height is missing from coinbase of a version 2
* block, it's rejected.
*/
@Test
public void missingHeightFromCoinbase() throws Exception {
final int UNDOABLE_BLOCKS_STORED = PARAMS.getMajorityEnforceBlockUpgrade() + 1;
store = createStore(PARAMS, UNDOABLE_BLOCKS_STORED);
try {
chain = new FullPrunedBlockChain(PARAMS, store);
ECKey outKey = new ECKey();
int height = 1;
Block chainHead = PARAMS.getGenesisBlock();
// Build some blocks on genesis block to create a spendable output.
// Put in just enough v1 blocks to stop the v2 blocks from forming a majority
for (height = 1; height <= (PARAMS.getMajorityWindow() - PARAMS.getMajorityEnforceBlockUpgrade()); height++) {
chainHead = chainHead.createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS,
outKey.getPubKey(), height);
chain.add(chainHead);
}
// Fill the rest of the window in with v2 blocks
for (; height < PARAMS.getMajorityWindow(); height++) {
chainHead = chainHead.createNextBlockWithCoinbase(Block.BLOCK_VERSION_BIP34,
outKey.getPubKey(), height);
chain.add(chainHead);
}
// Throw a broken v2 block in before we have a supermajority to enable
// enforcement, which should validate as-is
chainHead = chainHead.createNextBlockWithCoinbase(Block.BLOCK_VERSION_BIP34,
outKey.getPubKey(), height * 2);
chain.add(chainHead);
height++;
// Trying to add a broken v2 block should now result in rejection as
// we have a v2 supermajority
thrown.expect(VerificationException.CoinbaseHeightMismatch.class);
chainHead = chainHead.createNextBlockWithCoinbase(Block.BLOCK_VERSION_BIP34,
outKey.getPubKey(), height * 2);
chain.add(chainHead);
} catch(final VerificationException ex) {
throw (Exception) ex.getCause();
} finally {
try {
store.close();
} catch(Exception e) {
// Catch and drop any exception so a break mid-test doesn't result
// in a new exception being thrown and the original lost
}
}
}
}
| 18,625
| 42.825882
| 141
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/core/BlockTest.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.core;
import com.google.common.io.ByteStreams;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.Coin;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.base.VarInt;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.base.internal.ByteUtils;
import org.bitcoinj.core.AbstractBlockChain.NewBlockType;
import org.bitcoinj.crypto.DumpedPrivateKey;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.script.ScriptOpCodes;
import org.bitcoinj.wallet.Wallet;
import org.bitcoinj.wallet.Wallet.BalanceType;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class BlockTest {
private static final NetworkParameters TESTNET = TestNet3Params.get();
private static final NetworkParameters MAINNET = MainNetParams.get();
private byte[] block700000Bytes;
private Block block700000;
@Before
public void setUp() throws Exception {
Context.propagate(new Context());
// One with some of transactions in, so a good test of the merkle tree hashing.
block700000Bytes = ByteStreams.toByteArray(BlockTest.class.getResourceAsStream("block_testnet700000.dat"));
block700000 = TESTNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(block700000Bytes));
assertEquals("000000000000406178b12a4dea3b27e13b3c4fe4510994fd667d7c1e6a3f4dc1", block700000.getHashAsString());
}
@Test
public void testWork() {
BigInteger work = TESTNET.getGenesisBlock().getWork();
double log2Work = Math.log(work.longValue()) / Math.log(2);
// This number is printed by Bitcoin Core at startup as the calculated value of chainWork on testnet:
// UpdateTip: new best=000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943 height=0 version=0x00000001 log2_work=32.000022 tx=1 date='2011-02-02 23:16:42' ...
assertEquals(32.000022, log2Work, 0.0000001);
}
@Test
public void testBlockVerification() {
Block.verify(TESTNET, block700000, Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class));
}
@Test
public void testDate() {
assertEquals("2016-02-13T22:59:39Z", TimeUtils.dateTimeFormat(block700000.time()));
}
private static class TweakableTestNet3Params extends TestNet3Params {
public void setMaxTarget(BigInteger limit) {
maxTarget = limit;
}
}
@Test
public void testProofOfWork() {
// This params accepts any difficulty target.
final TweakableTestNet3Params TWEAK_TESTNET = new TweakableTestNet3Params();
TWEAK_TESTNET.setMaxTarget(ByteUtils.decodeCompactBits(Block.EASIEST_DIFFICULTY_TARGET));
Block block = TWEAK_TESTNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(block700000Bytes));
block.setNonce(12346);
try {
Block.verify(TWEAK_TESTNET, block, Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class));
fail();
} catch (VerificationException e) {
// Expected.
}
// Blocks contain their own difficulty target. The BlockChain verification mechanism is what stops real blocks
// from containing artificially weak difficulties.
block.setDifficultyTarget(Block.EASIEST_DIFFICULTY_TARGET);
// Now it should pass.
Block.verify(TWEAK_TESTNET, block, Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class));
// Break the nonce again at the lower difficulty level so we can try solving for it.
block.setNonce(1);
try {
Block.verify(TWEAK_TESTNET, block, Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class));
fail();
} catch (VerificationException e) {
// Expected to fail as the nonce is no longer correct.
}
// Should find an acceptable nonce.
block.solve();
Block.verify(TWEAK_TESTNET, block, Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class));
}
@Test
public void testBadTransactions() {
// Re-arrange so the coinbase transaction is not first.
Transaction tx1 = block700000.transactions.get(0);
Transaction tx2 = block700000.transactions.get(1);
block700000.transactions.set(0, tx2);
block700000.transactions.set(1, tx1);
try {
Block.verify(TESTNET, block700000, Block.BLOCK_HEIGHT_GENESIS, EnumSet.noneOf(Block.VerifyFlag.class));
fail();
} catch (VerificationException e) {
// We should get here.
}
}
@Test
public void testHeaderParse() {
Block header = block700000.cloneAsHeader();
Block reparsed = TESTNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(header.serialize()));
assertEquals(reparsed, header);
}
@Test
public void testBitcoinSerialization() {
// We have to be able to reserialize everything exactly as we found it for hashing to work. This test also
// proves that transaction serialization works, along with all its subobjects like scripts and in/outpoints.
//
// NB: This tests the bitcoin serialization protocol.
assertArrayEquals(block700000Bytes, block700000.serialize());
}
@Test
public void testCoinbaseHeightTestnet() throws Exception {
// Testnet block 21066 (hash 0000000004053156021d8e42459d284220a7f6e087bf78f30179c3703ca4eefa)
// contains a coinbase transaction whose height is two bytes, which is
// shorter than we see in most other cases.
Block block = TESTNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(
ByteStreams.toByteArray(getClass().getResourceAsStream("block_testnet21066.dat"))));
// Check block.
assertEquals("0000000004053156021d8e42459d284220a7f6e087bf78f30179c3703ca4eefa", block.getHashAsString());
Block.verify(TESTNET, block, 21066, EnumSet.of(Block.VerifyFlag.HEIGHT_IN_COINBASE));
// Testnet block 32768 (hash 000000007590ba495b58338a5806c2b6f10af921a70dbd814e0da3c6957c0c03)
// contains a coinbase transaction whose height is three bytes, but could
// fit in two bytes. This test primarily ensures script encoding checks
// are applied correctly.
block = TESTNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(
ByteStreams.toByteArray(getClass().getResourceAsStream("block_testnet32768.dat"))));
// Check block.
assertEquals("000000007590ba495b58338a5806c2b6f10af921a70dbd814e0da3c6957c0c03", block.getHashAsString());
Block.verify(TESTNET, block, 32768, EnumSet.of(Block.VerifyFlag.HEIGHT_IN_COINBASE));
}
@Test
public void testReceiveCoinbaseTransaction() throws Exception {
// Block 169482 (hash 0000000000000756935f1ee9d5987857b604046f846d3df56d024cdb5f368665)
// contains coinbase transactions that are mining pool shares.
// The private key MINERS_KEY is used to check transactions are received by a wallet correctly.
// The address for this private key is 1GqtGtn4fctXuKxsVzRPSLmYWN1YioLi9y.
final String MINING_PRIVATE_KEY = "5JDxPrBRghF1EvSBjDigywqfmAjpHPmTJxYtQTYJxJRHLLQA4mG";
final long BLOCK_NONCE = 3973947400L;
final Coin BALANCE_AFTER_BLOCK = Coin.valueOf(22223642);
Block block169482 = MAINNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(
ByteStreams.toByteArray(getClass().getResourceAsStream("block169482.dat"))));
// Check block.
assertNotNull(block169482);
Block.verify(MAINNET, block169482, 169482, EnumSet.noneOf(Block.VerifyFlag.class));
assertEquals(BLOCK_NONCE, block169482.getNonce());
StoredBlock storedBlock = new StoredBlock(block169482, BigInteger.ONE, 169482); // Nonsense work - not used in test.
// Create a wallet contain the miner's key that receives a spend from a coinbase.
ECKey miningKey = DumpedPrivateKey.fromBase58(BitcoinNetwork.MAINNET, MINING_PRIVATE_KEY).getKey();
assertNotNull(miningKey);
Wallet wallet = Wallet.createDeterministic(BitcoinNetwork.MAINNET, ScriptType.P2PKH);
wallet.importKey(miningKey);
// Initial balance should be zero by construction.
assertEquals(Coin.ZERO, wallet.getBalance());
// Give the wallet the first transaction in the block - this is the coinbase tx.
List<Transaction> transactions = block169482.getTransactions();
assertNotNull(transactions);
wallet.receiveFromBlock(transactions.get(0), storedBlock, NewBlockType.BEST_CHAIN, 0);
// Coinbase transaction should have been received successfully but be unavailable to spend (too young).
assertEquals(BALANCE_AFTER_BLOCK, wallet.getBalance(BalanceType.ESTIMATED));
assertEquals(Coin.ZERO, wallet.getBalance(BalanceType.AVAILABLE));
}
@Test
public void testBlock481815_witnessCommitmentInCoinbase() throws Exception {
Block block481815 = MAINNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(
ByteStreams.toByteArray(getClass().getResourceAsStream("block481815.dat"))));
assertEquals(2097, block481815.getTransactions().size());
assertEquals("f115afa8134171a0a686bfbe9667b60ae6fb5f6a439e0265789babc315333262",
block481815.getMerkleRoot().toString());
// This block has no witnesses.
for (Transaction tx : block481815.getTransactions())
assertFalse(tx.hasWitnesses());
// Nevertheless, there is a witness commitment (but no witness reserved).
Transaction coinbase = block481815.getTransactions().get(0);
assertEquals("919a0df2253172a55bebcb9002dbe775b8511f84955b282ca6dae826fdd94f90", coinbase.getTxId().toString());
assertEquals("919a0df2253172a55bebcb9002dbe775b8511f84955b282ca6dae826fdd94f90",
coinbase.getWTxId().toString());
Sha256Hash witnessCommitment = coinbase.findWitnessCommitment();
assertEquals("3d03076733467c45b08ec503a0c5d406647b073e1914d35b5111960ed625f3b7", witnessCommitment.toString());
}
@Test
public void testBlock481829_witnessTransactions() throws Exception {
Block block481829 = MAINNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(
ByteStreams.toByteArray(getClass().getResourceAsStream("block481829.dat"))));
assertEquals(2020, block481829.getTransactions().size());
assertEquals("f06f697be2cac7af7ed8cd0b0b81eaa1a39e444c6ebd3697e35ab34461b6c58d",
block481829.getMerkleRoot().toString());
assertEquals("0a02ddb2f86a14051294f8d98dd6959dd12bf3d016ca816c3db9b32d3e24fc2d",
block481829.getWitnessRoot().toString());
Transaction coinbase = block481829.getTransactions().get(0);
assertEquals("9c1ab453283035800c43eb6461eb46682b81be110a0cb89ee923882a5fd9daa4", coinbase.getTxId().toString());
assertEquals("2bbda73aa4e561e7f849703994cc5e563e4bcf103fb0f6fef5ae44c95c7b83a6",
coinbase.getWTxId().toString());
Sha256Hash witnessCommitment = coinbase.findWitnessCommitment();
assertEquals("c3c1145d8070a57e433238e42e4c022c1e51ca2a958094af243ae1ee252ca106", witnessCommitment.toString());
byte[] witnessReserved = coinbase.getInput(0).getWitness().getPush(0);
assertEquals("0000000000000000000000000000000000000000000000000000000000000000", ByteUtils.formatHex(witnessReserved));
block481829.checkWitnessRoot();
}
@Test
public void isBIPs() throws Exception {
final Block genesis = MAINNET.getGenesisBlock();
assertFalse(genesis.isBIP34());
assertFalse(genesis.isBIP66());
assertFalse(genesis.isBIP65());
// 227835/00000000000001aa077d7aa84c532a4d69bdbff519609d1da0835261b7a74eb6: last version 1 block
final Block block227835 = MAINNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(
ByteStreams.toByteArray(getClass().getResourceAsStream("block227835.dat"))));
assertFalse(block227835.isBIP34());
assertFalse(block227835.isBIP66());
assertFalse(block227835.isBIP65());
// 227836/00000000000000d0dfd4c9d588d325dce4f32c1b31b7c0064cba7025a9b9adcc: version 2 block
final Block block227836 = MAINNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(
ByteStreams.toByteArray(getClass().getResourceAsStream("block227836.dat"))));
assertTrue(block227836.isBIP34());
assertFalse(block227836.isBIP66());
assertFalse(block227836.isBIP65());
// 363703/0000000000000000011b2a4cb91b63886ffe0d2263fd17ac5a9b902a219e0a14: version 3 block
final Block block363703 = MAINNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(
ByteStreams.toByteArray(getClass().getResourceAsStream("block363703.dat"))));
assertTrue(block363703.isBIP34());
assertTrue(block363703.isBIP66());
assertFalse(block363703.isBIP65());
// 383616/00000000000000000aab6a2b34e979b09ca185584bd1aecf204f24d150ff55e9: version 4 block
final Block block383616 = MAINNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(
ByteStreams.toByteArray(getClass().getResourceAsStream("block383616.dat"))));
assertTrue(block383616.isBIP34());
assertTrue(block383616.isBIP66());
assertTrue(block383616.isBIP65());
// 370661/00000000000000001416a613602d73bbe5c79170fd8f39d509896b829cf9021e: voted for BIP101
final Block block370661 = MAINNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(
ByteStreams.toByteArray(getClass().getResourceAsStream("block370661.dat"))));
assertTrue(block370661.isBIP34());
assertTrue(block370661.isBIP66());
assertTrue(block370661.isBIP65());
}
@Test
public void parseBlockWithHugeDeclaredTransactionsSize() {
Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true));
Block block = new Block(1, Sha256Hash.ZERO_HASH, Sha256Hash.ZERO_HASH, 1, 1, 1, new ArrayList<Transaction>()) {
@Override
protected void bitcoinSerializeToStream(OutputStream stream) throws IOException {
ByteUtils.writeInt32LE(getVersion(), stream);
stream.write(getPrevBlockHash().serialize());
stream.write(getMerkleRoot().serialize());
ByteUtils.writeInt32LE(getTimeSeconds(), stream);
ByteUtils.writeInt32LE(getDifficultyTarget(), stream);
ByteUtils.writeInt32LE(getNonce(), stream);
stream.write(VarInt.of(Integer.MAX_VALUE).serialize());
}
};
byte[] serializedBlock = block.serialize();
try {
TESTNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(serializedBlock));
fail("We expect BufferUnderflowException with the fixed code and OutOfMemoryError with the buggy code, so this is weird");
} catch (BufferUnderflowException e) {
//Expected, do nothing
}
}
@Test
public void testGenesisBlock() {
Block genesisBlock = Block.createGenesis();
genesisBlock.setDifficultyTarget(0x1d00ffffL);
genesisBlock.setTime(Instant.ofEpochSecond(1231006505L));
genesisBlock.setNonce(2083236893);
assertEquals(Sha256Hash.wrap("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"), genesisBlock.getHash());
}
}
| 16,880
| 47.789017
| 179
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/core/VersionMessageTest.java
|
/*
* Copyright 2012 Matt Corallo
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.core;
import org.bitcoinj.params.TestNet3Params;
import org.junit.Test;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.time.Instant;
import org.bitcoinj.base.internal.ByteUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class VersionMessageTest {
private static final NetworkParameters TESTNET = TestNet3Params.get();
@Test
public void decode_noRelay_bestHeight_subVer() {
// Test that we can decode version messages which miss data which some old nodes may not include
String hex = "7111010000000000000000003334a85500000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d00000000000000000f2f626974636f696e6a3a302e31332f0004000000";
VersionMessage ver = VersionMessage.read(ByteBuffer.wrap(ByteUtils.parseHex(hex)));
assertFalse(ver.relayTxesBeforeFilter);
assertEquals(1024, ver.bestHeight);
assertEquals("/bitcoinj:0.13/", ver.subVer);
}
@Test
public void decode_relay_bestHeight_subVer() {
String hex = "711101000000000000000000a634a85500000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d00000000000000000f2f626974636f696e6a3a302e31332f0004000001";
VersionMessage ver = VersionMessage.read(ByteBuffer.wrap(ByteUtils.parseHex(hex)));
assertTrue(ver.relayTxesBeforeFilter);
assertEquals(1024, ver.bestHeight);
assertEquals("/bitcoinj:0.13/", ver.subVer);
}
@Test
public void decode_relay_noBestHeight_subVer() {
String hex = "711101000000000000000000c334a85500000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d00000000000000000f2f626974636f696e6a3a302e31332f0000000001";
VersionMessage ver = VersionMessage.read(ByteBuffer.wrap(ByteUtils.parseHex(hex)));
assertTrue(ver.relayTxesBeforeFilter);
assertEquals(0, ver.bestHeight);
assertEquals("/bitcoinj:0.13/", ver.subVer);
}
@Test(expected = ProtocolException.class)
public void decode_relay_noBestHeight_noSubVer() {
String hex = "00000000000000000000000048e5e95000000000000000000000000000000000000000000000ffff7f000001479d000000000000000000000000000000000000ffff7f000001479d0000000000000000";
VersionMessage ver = VersionMessage.read(ByteBuffer.wrap(ByteUtils.parseHex(hex)));
}
@Test
public void roundTrip_ipv4() throws Exception {
VersionMessage ver = new VersionMessage(TESTNET, 1234);
ver.time = Instant.ofEpochSecond(23456);
ver.subVer = "/bitcoinj/";
ver.localServices = Services.of(1);
ver.receivingAddr = new InetSocketAddress(InetAddress.getByName("4.3.2.1"), 8333);
byte[] serialized = ver.serialize();
VersionMessage ver2 = VersionMessage.read(ByteBuffer.wrap(serialized));
assertEquals(1234, ver2.bestHeight);
assertEquals(Instant.ofEpochSecond(23456), ver2.time);
assertEquals("/bitcoinj/", ver2.subVer);
assertEquals(ProtocolVersion.CURRENT.intValue(), ver2.clientVersion);
assertEquals(1, ver2.localServices.bits());
assertEquals("4.3.2.1", ver2.receivingAddr.getHostName());
assertEquals(8333, ver2.receivingAddr.getPort());
}
@Test
public void roundTrip_ipv6() throws Exception {
VersionMessage ver = new VersionMessage(TESTNET, 1234);
ver.time = Instant.ofEpochSecond(23456);
ver.subVer = "/bitcoinj/";
ver.localServices = Services.of(1);
ver.receivingAddr = new InetSocketAddress(InetAddress.getByName("2002:db8:85a3:0:0:8a2e:370:7335"), 8333);
byte[] serialized = ver.serialize();
VersionMessage ver2 = VersionMessage.read(ByteBuffer.wrap(serialized));
assertEquals(1234, ver2.bestHeight);
assertEquals(Instant.ofEpochSecond(23456), ver2.time);
assertEquals("/bitcoinj/", ver2.subVer);
assertEquals(ProtocolVersion.CURRENT.intValue(), ver2.clientVersion);
assertEquals(1, ver2.localServices.bits());
assertEquals("2002:db8:85a3:0:0:8a2e:370:7335", ver2.receivingAddr.getHostName());
assertEquals(8333, ver2.receivingAddr.getPort());
}
}
| 5,047
| 46.622642
| 226
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/core/NetworkParametersTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.core;
import org.bitcoinj.base.BitcoinNetwork;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Test NetworkParameters
*/
public class NetworkParametersTest {
@Test
public void deprecatedMembers() {
NetworkParameters params = NetworkParameters.of(BitcoinNetwork.MAINNET);
assertEquals(70000, params.getProtocolVersionNum(ProtocolVersion.MINIMUM));
}
}
| 1,044
| 29.735294
| 83
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/core/UTXOTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.core;
public class UTXOTest {
// no tests at the moment
}
| 697
| 30.727273
| 75
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/core/LockTimeTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.core;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.bitcoinj.core.LockTime.HeightLock;
import org.bitcoinj.core.LockTime.TimeLock;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import static org.junit.Assert.*;
@RunWith(JUnitParamsRunner.class)
public class LockTimeTest {
@Test
public void ofBlockHeight() {
assertEquals(1, LockTime.ofBlockHeight(1).blockHeight());
assertEquals(499_999_999, LockTime.ofBlockHeight((int) LockTime.THRESHOLD - 1).blockHeight());
}
@Test
public void ofTimestamp() {
Instant fiftyYears = Instant.EPOCH.plus(365 * 50, ChronoUnit.DAYS);
assertEquals(fiftyYears, LockTime.ofTimestamp(fiftyYears).timestamp());
Instant almostMax = Instant.MAX.truncatedTo(ChronoUnit.SECONDS);
assertEquals(almostMax, LockTime.ofTimestamp(almostMax).timestamp());
}
@Test(expected = IllegalArgumentException.class)
public void ofTimestamp_tooLow() {
LockTime.ofTimestamp(Instant.EPOCH.plus(365, ChronoUnit.DAYS));
}
@Test(expected = IllegalArgumentException.class)
public void ofTimestamp_negative() {
LockTime.ofTimestamp(Instant.EPOCH.minusSeconds(1));
}
@Test
public void unset() {
LockTime unset = LockTime.unset();
assertTrue(unset instanceof HeightLock);
assertEquals(0, unset.rawValue());
}
@Test
public void timestampSubtype() {
LockTime timestamp = LockTime.ofTimestamp(Instant.now());
assertTrue(timestamp instanceof TimeLock);
assertTrue(((TimeLock) timestamp).timestamp().isAfter(Instant.EPOCH));
}
@Test
public void blockHeightSubtype() {
LockTime blockHeight = LockTime.ofBlockHeight(100);
assertTrue(blockHeight instanceof HeightLock);
assertTrue(((HeightLock) blockHeight).blockHeight() > 0);
}
@Test
@Parameters(method = "validValueVectors")
public void validValues(long value, Class<?> clazz) {
LockTime lockTime = LockTime.of(value);
assertTrue(clazz.isInstance(lockTime));
assertEquals(value, lockTime.rawValue());
}
@Test(expected = IllegalArgumentException.class)
@Parameters(method = "invalidValueVectors")
public void invalidValues(long value) {
LockTime lockTime = LockTime.of(value);
}
private Object[] validValueVectors() {
return new Object[] {
new Object[] { 0, HeightLock.class },
new Object[] { 1, HeightLock.class },
new Object[] { 499_999_999, HeightLock.class },
new Object[] { 500_000_000, TimeLock.class },
new Object[] { Long.MAX_VALUE, TimeLock.class },
new Object[] { Instant.now().getEpochSecond(), TimeLock.class },
new Object[] { Instant.MAX.getEpochSecond(), TimeLock.class }
};
}
private Long[] invalidValueVectors() {
return new Long[] { Long.MIN_VALUE, -1L };
}
}
| 3,712
| 33.06422
| 102
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/core/CheckpointManagerTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.core;
import org.easymock.EasyMockRunner;
import org.easymock.Mock;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.IOException;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
@RunWith(EasyMockRunner.class)
public class CheckpointManagerTest {
@Mock
NetworkParameters params;
@Test(expected = NullPointerException.class)
public void shouldThrowNullPointerExceptionWhenCheckpointsNotFound() throws IOException {
expect(params.getId()).andReturn("org/bitcoinj/core/checkpointmanagertest/notFound");
replay(params);
new CheckpointManager(params, null);
}
@Test(expected = IOException.class)
public void shouldThrowNullPointerExceptionWhenCheckpointsInUnknownFormat() throws IOException {
expect(params.getId()).andReturn("org/bitcoinj/core/checkpointmanagertest/unsupportedFormat");
replay(params);
new CheckpointManager(params, null);
}
@Test(expected = IllegalStateException.class)
public void shouldThrowIllegalStateExceptionWithNoCheckpoints() throws IOException {
expect(params.getId()).andReturn("org/bitcoinj/core/checkpointmanagertest/noCheckpoints");
replay(params);
new CheckpointManager(params, null);
}
@Test
public void canReadTextualStream() throws IOException {
expect(params.getId()).andReturn("org/bitcoinj/core/checkpointmanagertest/validTextualFormat");
replay(params);
new CheckpointManager(params, null);
}
}
| 2,186
| 33.714286
| 103
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/core/TransactionOutPointTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.core;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.bitcoinj.base.Sha256Hash;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.Random;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@RunWith(JUnitParamsRunner.class)
public class TransactionOutPointTest {
@Test
@Parameters(method = "randomOutPoints")
public void readAndWrite(TransactionOutPoint outpoint) {
ByteBuffer buf = ByteBuffer.allocate(TransactionOutPoint.BYTES);
outpoint.write(buf);
assertFalse(buf.hasRemaining());
((Buffer) buf).rewind();
TransactionOutPoint outpointCopy = TransactionOutPoint.read(buf);
assertFalse(buf.hasRemaining());
assertEquals(outpoint, outpointCopy);
}
private Iterator<TransactionOutPoint> randomOutPoints() {
Random random = new Random();
return Stream.generate(() -> {
byte[] randomBytes = new byte[Sha256Hash.LENGTH];
random.nextBytes(randomBytes);
return new TransactionOutPoint(Integer.toUnsignedLong(random.nextInt()), Sha256Hash.wrap(randomBytes));
}).limit(10).iterator();
}
@Test
public void deprecatedMembers() {
TransactionOutPoint outpoint = TransactionOutPoint.UNCONNECTED;
outpoint.getHash();
outpoint.getMessageSize();
outpoint.getIndex();
outpoint.bitcoinSerialize();
}
}
| 2,220
| 32.651515
| 115
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/testing/package-info.java
|
/**
* Various utilities for writing unit tests: also useful for testing your own code and apps that build on top of
* bitcoinj. Some of these are junit4 classes you can subclass, and others are static utility methods for building
* fake transactions and so on.
*/
package org.bitcoinj.testing;
| 297
| 48.666667
| 114
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/testing/TestWithWallet.java
|
/*
* Copyright 2013 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.
*/
package org.bitcoinj.testing;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.core.AbstractBlockChain;
import org.bitcoinj.base.Address;
import org.bitcoinj.core.Block;
import org.bitcoinj.core.BlockChain;
import org.bitcoinj.base.Coin;
import org.bitcoinj.core.Context;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.VerificationException;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.store.BlockStore;
import org.bitcoinj.store.MemoryBlockStore;
import org.bitcoinj.utils.BriefLogFormatter;
import org.bitcoinj.wallet.KeyChainGroupStructure;
import org.bitcoinj.wallet.Wallet;
import org.junit.BeforeClass;
import javax.annotation.Nullable;
import static org.bitcoinj.testing.FakeTxBuilder.createFakeBlock;
import static org.bitcoinj.testing.FakeTxBuilder.createFakeTx;
// TODO: This needs to be somewhat rewritten - the "sendMoneyToWallet" methods aren't sending via the block chain object
/**
* A utility class that you can derive from in your unit tests. TestWithWallet sets up an empty wallet,
* an in-memory block store and a block chain object. It also provides helper methods for filling the wallet
* with money in whatever ways you wish. Note that for simplicity with amounts, this class sets the default
* fee per kilobyte to zero in setUp.
*/
public class TestWithWallet {
protected static final NetworkParameters TESTNET = TestNet3Params.get();
protected static final NetworkParameters MAINNET = MainNetParams.get();
protected ECKey myKey;
protected Address myAddress;
protected Wallet wallet;
protected BlockChain chain;
protected BlockStore blockStore;
@BeforeClass
public static void setUpClass() throws Exception {
TimeUtils.clearMockClock();
}
public void setUp() throws Exception {
BriefLogFormatter.init();
Context.propagate(new Context(100, Coin.ZERO, false, true));
wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH, KeyChainGroupStructure.BIP32);
myKey = wallet.freshReceiveKey();
myAddress = wallet.freshReceiveAddress(ScriptType.P2PKH);
blockStore = new MemoryBlockStore(TESTNET.getGenesisBlock());
chain = new BlockChain(TESTNET, wallet, blockStore);
}
public void tearDown() throws Exception {
}
@Nullable
protected Transaction sendMoneyToWallet(Wallet wallet, AbstractBlockChain.NewBlockType type, Transaction... transactions)
throws VerificationException {
if (type == null) {
// Pending transaction
for (Transaction tx : transactions)
if (wallet.isPendingTransactionRelevant(tx))
wallet.receivePending(tx, null);
} else {
FakeTxBuilder.BlockPair bp = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS, transactions);
for (Transaction tx : transactions)
wallet.receiveFromBlock(tx, bp.storedBlock, type, 0);
if (type == AbstractBlockChain.NewBlockType.BEST_CHAIN)
wallet.notifyNewBestBlock(bp.storedBlock);
}
if (transactions.length == 1)
return wallet.getTransaction(transactions[0].getTxId()); // Can be null if tx is a double spend that's otherwise irrelevant.
else
return null;
}
@Nullable
protected Transaction sendMoneyToWallet(Wallet wallet, AbstractBlockChain.NewBlockType type, Coin value, Address toAddress) throws VerificationException {
return sendMoneyToWallet(wallet, type, createFakeTx(TESTNET.network(), value, toAddress));
}
@Nullable
protected Transaction sendMoneyToWallet(Wallet wallet, AbstractBlockChain.NewBlockType type, Coin value, ECKey toPubKey) throws VerificationException {
return sendMoneyToWallet(wallet, type, createFakeTx(value, toPubKey));
}
@Nullable
protected Transaction sendMoneyToWallet(AbstractBlockChain.NewBlockType type, Transaction... transactions) throws VerificationException {
return sendMoneyToWallet(this.wallet, type, transactions);
}
@Nullable
protected Transaction sendMoneyToWallet(AbstractBlockChain.NewBlockType type, Coin value) throws VerificationException {
return sendMoneyToWallet(this.wallet, type, value, myAddress);
}
@Nullable
protected Transaction sendMoneyToWallet(AbstractBlockChain.NewBlockType type, Coin value, Address toAddress) throws VerificationException {
return sendMoneyToWallet(this.wallet, type, value, toAddress);
}
@Nullable
protected Transaction sendMoneyToWallet(AbstractBlockChain.NewBlockType type, Coin value, ECKey toPubKey) throws VerificationException {
return sendMoneyToWallet(this.wallet, type, value, toPubKey);
}
}
| 5,593
| 41.06015
| 158
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/testing/FooWalletExtension.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.testing;
import org.bitcoinj.wallet.Wallet;
import org.bitcoinj.wallet.WalletExtension;
import java.util.Arrays;
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
public class FooWalletExtension implements WalletExtension {
private final byte[] data = {1, 2, 3};
private final boolean isMandatory;
private final String id;
public FooWalletExtension(String id, boolean isMandatory) {
this.isMandatory = isMandatory;
this.id = id;
}
@Override
public String getWalletExtensionID() {
return id;
}
@Override
public boolean isWalletExtensionMandatory() {
return isMandatory;
}
@Override
public byte[] serializeWalletExtension() {
return data;
}
@Override
public void deserializeWalletExtension(Wallet wallet, byte[] data) {
checkArgument(Arrays.equals(this.data, data));
}
}
| 1,550
| 26.210526
| 75
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/testing/NopTransactionSigner.java
|
/*
* Copyright 2014 Kosta Korenkov
*
* 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.
*/
package org.bitcoinj.testing;
import org.bitcoinj.signers.TransactionSigner;
import org.bitcoinj.wallet.KeyBag;
public class NopTransactionSigner implements TransactionSigner {
private boolean isReady;
public NopTransactionSigner() {
}
public NopTransactionSigner(boolean ready) {
this.isReady = ready;
}
@Override
public boolean isReady() {
return isReady;
}
@Override
public boolean signInputs(ProposedTransaction t, KeyBag keyBag) {
return false;
}
}
| 1,126
| 25.833333
| 75
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/testing/KeyChainTransactionSigner.java
|
/*
* Copyright 2014 Kosta Korenkov
*
* 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.
*/
package org.bitcoinj.testing;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDPath;
import org.bitcoinj.signers.CustomTransactionSigner;
import org.bitcoinj.wallet.DeterministicKeyChain;
import java.util.List;
/**
* <p>Transaction signer which uses provided keychain to get signing keys from. It relies on previous signer to provide
* derivation path to be used to get signing key and, once gets the key, just signs given transaction immediately.</p>
* It should not be used in test scenarios involving serialization as it doesn't have proper serialize/deserialize
* implementation.
*/
public class KeyChainTransactionSigner extends CustomTransactionSigner {
private DeterministicKeyChain keyChain;
public KeyChainTransactionSigner() {
}
public KeyChainTransactionSigner(DeterministicKeyChain keyChain) {
this.keyChain = keyChain;
}
@Override
protected SignatureAndKey getSignature(Sha256Hash sighash, List<ChildNumber> derivationPath) {
HDPath keyPath = HDPath.M(derivationPath);
DeterministicKey key = keyChain.getKeyByPath(keyPath, true);
return new SignatureAndKey(key.sign(sighash), key.dropPrivateBytes().dropParent());
}
}
| 1,907
| 35.692308
| 119
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/testing/MockTransactionBroadcaster.java
|
/*
* Copyright 2013 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.
*/
package org.bitcoinj.testing;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionBroadcast;
import org.bitcoinj.core.TransactionBroadcaster;
import org.bitcoinj.core.VerificationException;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.wallet.Wallet;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.ReentrantLock;
/**
* A mock transaction broadcaster can be used in unit tests as a stand-in for a PeerGroup. It catches any transactions
* broadcast through it and makes them available via the {@link #waitForTransaction()} method. Using that will cause
* the broadcast to be seen as if it never propagated though, so you may instead use {@link #waitForTxFuture()} and then
* set the returned future when you want the "broadcast" to be completed.
*/
public class MockTransactionBroadcaster implements TransactionBroadcaster {
private final ReentrantLock lock = Threading.lock(MockTransactionBroadcaster.class);
private final Wallet wallet;
public static class TxFuturePair {
public final Transaction tx;
public final CompletableFuture<Transaction> future;
public TxFuturePair(Transaction tx, CompletableFuture<Transaction> future) {
this.tx = tx;
this.future = future;
}
/** Tells the broadcasting code that the broadcast was a success, just does future.set(tx) */
public void succeed() {
future.complete(tx);
}
}
private final LinkedBlockingQueue<TxFuturePair> broadcasts = new LinkedBlockingQueue<>();
/** Sets this mock broadcaster on the given wallet. */
public MockTransactionBroadcaster(Wallet wallet) {
// This code achieves nothing directly, but it sets up the broadcaster/peergroup > wallet lock ordering
// so inversions can be caught.
lock.lock();
try {
this.wallet = wallet;
wallet.setTransactionBroadcaster(this);
wallet.getPendingTransactions();
} finally {
lock.unlock();
}
}
@Override
public TransactionBroadcast broadcastTransaction(Transaction tx) {
// Use a lock just to catch lock ordering inversions e.g. wallet->broadcaster.
lock.lock();
try {
CompletableFuture<Transaction> result = new CompletableFuture<>();
broadcasts.put(new TxFuturePair(tx, result));
result.whenComplete((transaction, t) -> {
if (transaction != null) {
try {
wallet.receivePending(transaction, null);
} catch (VerificationException e) {
throw new RuntimeException(e);
}
}
});
return TransactionBroadcast.createMockBroadcast(tx, result);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
public Transaction waitForTransaction() {
return waitForTxFuture().tx;
}
public Transaction waitForTransactionAndSucceed() {
TxFuturePair pair = waitForTxFuture();
pair.succeed();
return pair.tx;
}
public TxFuturePair waitForTxFuture() {
try {
return broadcasts.take();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public int size() {
return broadcasts.size();
}
}
| 4,169
| 34.641026
| 120
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/kits/WalletAppKitTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.kits;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.wallet.KeyChainGroupStructure;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
import static org.bitcoinj.base.BitcoinNetwork.REGTEST;
import static org.bitcoinj.base.ScriptType.P2WPKH;
import static org.bitcoinj.wallet.KeyChainGroupStructure.BIP43;
/**
* Test WalletAppKit
*/
public class WalletAppKitTest {
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
static final String filePrefix = "UnitTestWalletAppKit";
@Test
public void constructAndClose() throws IOException {
WalletAppKit kit = new WalletAppKit(REGTEST, P2WPKH, BIP43, tmpFolder.newFolder(), filePrefix);
kit.close();
}
@Test
public void constructAndCloseTwice() throws IOException {
WalletAppKit kit = new WalletAppKit(REGTEST, P2WPKH, BIP43, tmpFolder.newFolder(), filePrefix);
kit.close();
kit.close();
}
@Test
public void launchAndClose() throws IOException {
WalletAppKit kit = WalletAppKit.launch(REGTEST, tmpFolder.newFolder(), filePrefix);
kit.close();
}
@Test
public void launchAndCloseTwice() throws IOException {
WalletAppKit kit = WalletAppKit.launch(REGTEST, tmpFolder.newFolder(), filePrefix);
kit.close();
kit.close();
}
}
| 2,031
| 30.261538
| 103
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/wallet/BasicKeyChainTest.java
|
/*
* Copyright 2013 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.
*/
package org.bitcoinj.wallet;
import com.google.common.collect.Lists;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.core.BloomFilter;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.crypto.KeyCrypter;
import org.bitcoinj.crypto.KeyCrypterException;
import org.bitcoinj.crypto.KeyCrypterScrypt;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.wallet.listeners.AbstractKeyChainEventListener;
import org.junit.Before;
import org.junit.Test;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class BasicKeyChainTest {
private BasicKeyChain chain;
private AtomicReference<List<ECKey>> onKeysAdded;
private AtomicBoolean onKeysAddedRan;
@Before
public void setup() {
chain = new BasicKeyChain();
onKeysAdded = new AtomicReference<>();
onKeysAddedRan = new AtomicBoolean();
chain.addEventListener(new AbstractKeyChainEventListener() {
@Override
public void onKeysAdded(List<ECKey> keys2) {
onKeysAdded.set(keys2);
onKeysAddedRan.set(true);
}
}, Threading.SAME_THREAD);
}
@Test
public void importKeys() {
Instant now = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS);
TimeUtils.setMockClock(now);
final ECKey key1 = new ECKey();
TimeUtils.rollMockClock(Duration.ofDays(1));
final ECKey key2 = new ECKey();
final ArrayList<ECKey> keys = Lists.newArrayList(key1, key2);
// Import two keys, check the event is correct.
assertEquals(2, chain.importKeys(keys));
assertEquals(2, chain.numKeys());
assertTrue(onKeysAddedRan.getAndSet(false));
assertArrayEquals(keys.toArray(), onKeysAdded.get().toArray());
assertEquals(now, chain.earliestKeyCreationTime());
// Check we ignore duplicates.
final ECKey newKey = new ECKey();
keys.add(newKey);
assertEquals(1, chain.importKeys(keys));
assertTrue(onKeysAddedRan.getAndSet(false));
assertEquals(newKey, onKeysAdded.getAndSet(null).get(0));
assertEquals(0, chain.importKeys(keys));
assertFalse(onKeysAddedRan.getAndSet(false));
assertNull(onKeysAdded.get());
assertTrue(chain.hasKey(key1));
assertTrue(chain.hasKey(key2));
assertEquals(key1, chain.findKeyFromPubHash(key1.getPubKeyHash()));
assertEquals(key2, chain.findKeyFromPubKey(key2.getPubKey()));
assertNull(chain.findKeyFromPubKey(key2.getPubKeyHash()));
}
@Test
public void removeKey() {
ECKey key = new ECKey();
chain.importKeys(key);
assertEquals(1, chain.numKeys());
assertTrue(chain.removeKey(key));
assertEquals(0, chain.numKeys());
assertFalse(chain.removeKey(key));
}
@Test
public void getKey() {
ECKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertTrue(onKeysAddedRan.getAndSet(false));
assertEquals(key1, onKeysAdded.getAndSet(null).get(0));
ECKey key2 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertFalse(onKeysAddedRan.getAndSet(false));
assertEquals(key2, key1);
}
@Test(expected = IllegalStateException.class)
public void checkPasswordNoKeys() {
chain.checkPassword("test");
}
@Test(expected = IllegalStateException.class)
public void checkPasswordNotEncrypted() {
final ArrayList<ECKey> keys = Lists.newArrayList(new ECKey(), new ECKey());
chain.importKeys(keys);
chain.checkPassword("test");
}
@Test(expected = IllegalStateException.class)
public void doubleEncryptFails() {
final ArrayList<ECKey> keys = Lists.newArrayList(new ECKey(), new ECKey());
chain.importKeys(keys);
chain = chain.toEncrypted("foo");
chain.toEncrypted("foo");
}
@Test
public void encryptDecrypt() {
final ECKey key1 = new ECKey();
chain.importKeys(key1, new ECKey());
final String PASSWORD = "foobar";
chain = chain.toEncrypted(PASSWORD);
final KeyCrypter keyCrypter = chain.getKeyCrypter();
assertNotNull(keyCrypter);
assertTrue(keyCrypter instanceof KeyCrypterScrypt);
assertTrue(chain.checkPassword(PASSWORD));
assertFalse(chain.checkPassword("wrong"));
ECKey key = chain.findKeyFromPubKey(key1.getPubKey());
assertTrue(key.isEncrypted());
assertTrue(key.isPubKeyOnly());
assertFalse(key.isWatching());
assertNull(key.getSecretBytes());
try {
// Don't allow import of an unencrypted key.
chain.importKeys(new ECKey());
fail();
} catch (KeyCrypterException e) {
}
try {
chain.toDecrypted(keyCrypter.deriveKey("wrong"));
fail();
} catch (KeyCrypterException e) {}
chain = chain.toDecrypted(PASSWORD);
key = chain.findKeyFromPubKey(key1.getPubKey());
assertFalse(key.isEncrypted());
assertFalse(key.isPubKeyOnly());
assertFalse(key.isWatching());
key.getPrivKeyBytes();
}
@Test(expected = KeyCrypterException.class)
public void cannotImportEncryptedKey() {
final ECKey key1 = new ECKey();
chain.importKeys(Collections.singletonList(key1));
chain = chain.toEncrypted("foobar");
ECKey encryptedKey = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertTrue(encryptedKey.isEncrypted());
BasicKeyChain chain2 = new BasicKeyChain();
chain2.importKeys(Collections.singletonList(encryptedKey));
}
@Test(expected = KeyCrypterException.class)
public void cannotMixParams() {
chain = chain.toEncrypted("foobar");
KeyCrypterScrypt scrypter = new KeyCrypterScrypt(2); // Some bogus params.
ECKey key1 = new ECKey().encrypt(scrypter, scrypter.deriveKey("other stuff"));
chain.importKeys(key1);
}
@Test
public void serializationUnencrypted() throws UnreadableWalletException {
TimeUtils.setMockClock();
Instant now = TimeUtils.currentTime();
final ECKey key1 = new ECKey();
TimeUtils.rollMockClock(Duration.ofSeconds(5000));
final ECKey key2 = new ECKey();
chain.importKeys(Arrays.asList(key1, key2));
List<Protos.Key> keys = chain.serializeToProtobuf();
assertEquals(2, keys.size());
assertArrayEquals(key1.getPubKey(), keys.get(0).getPublicKey().toByteArray());
assertArrayEquals(key2.getPubKey(), keys.get(1).getPublicKey().toByteArray());
assertArrayEquals(key1.getPrivKeyBytes(), keys.get(0).getSecretBytes().toByteArray());
assertArrayEquals(key2.getPrivKeyBytes(), keys.get(1).getSecretBytes().toByteArray());
Instant normTime = now.truncatedTo(ChronoUnit.SECONDS);
assertEquals(normTime, Instant.ofEpochMilli(keys.get(0).getCreationTimestamp()));
assertEquals(normTime.plusSeconds(5000), Instant.ofEpochMilli(keys.get(1).getCreationTimestamp()));
chain = BasicKeyChain.fromProtobufUnencrypted(keys);
assertEquals(2, chain.getKeys().size());
assertEquals(key1, chain.getKeys().get(0));
assertEquals(key2, chain.getKeys().get(1));
}
@Test
public void serializationEncrypted() throws UnreadableWalletException {
ECKey key1 = new ECKey();
chain.importKeys(key1);
chain = chain.toEncrypted("foo bar");
key1 = chain.getKeys().get(0);
List<Protos.Key> keys = chain.serializeToProtobuf();
assertEquals(1, keys.size());
assertArrayEquals(key1.getPubKey(), keys.get(0).getPublicKey().toByteArray());
assertFalse(keys.get(0).hasSecretBytes());
assertTrue(keys.get(0).hasEncryptedData());
chain = BasicKeyChain.fromProtobufEncrypted(keys, Objects.requireNonNull(chain.getKeyCrypter()));
assertEquals(key1.getEncryptedPrivateKey(), chain.getKeys().get(0).getEncryptedPrivateKey());
assertTrue(chain.checkPassword("foo bar"));
}
@Test
public void watching() throws UnreadableWalletException {
ECKey key1 = new ECKey();
ECKey pub = ECKey.fromPublicOnly(key1);
chain.importKeys(pub);
assertEquals(1, chain.numKeys());
List<Protos.Key> keys = chain.serializeToProtobuf();
assertEquals(1, keys.size());
assertTrue(keys.get(0).hasPublicKey());
assertFalse(keys.get(0).hasSecretBytes());
chain = BasicKeyChain.fromProtobufUnencrypted(keys);
assertEquals(1, chain.numKeys());
assertFalse(chain.findKeyFromPubKey(pub.getPubKey()).hasPrivKey());
}
@Test
public void bloom() {
ECKey key1 = new ECKey();
ECKey key2 = new ECKey();
chain.importKeys(key1, key2);
assertEquals(2, chain.numKeys());
assertEquals(4, chain.numBloomFilterEntries());
final double FALSE_POSITIVE_RATE = 0.001;
BloomFilter filter = chain.getFilter(4, FALSE_POSITIVE_RATE, 100);
assertTrue(filter.contains(key1.getPubKey()));
assertTrue(filter.contains(key1.getPubKeyHash()));
assertTrue(filter.contains(key2.getPubKey()));
assertTrue(filter.contains(key2.getPubKeyHash()));
final int COUNT = 10000;
int falsePositives = 0;
for (int i = 0; i < COUNT; i++) {
ECKey key = new ECKey();
if (filter.contains(key.getPubKey()))
falsePositives++;
}
double actualRate = (double) falsePositives / COUNT;
assertTrue("roughly expected: " + FALSE_POSITIVE_RATE + ", actual: " + actualRate,
actualRate < FALSE_POSITIVE_RATE * 8);
}
@Test
public void keysBeforeAndAfter() {
TimeUtils.setMockClock();
Instant now = TimeUtils.currentTime();
final ECKey key1 = new ECKey();
TimeUtils.rollMockClock(Duration.ofDays(1));
final ECKey key2 = new ECKey();
final List<ECKey> keys = Lists.newArrayList(key1, key2);
assertEquals(2, chain.importKeys(keys));
assertFalse(chain.findOldestKeyAfter(now.plus(2, ChronoUnit.DAYS)).isPresent());
assertEquals(key1, chain.findOldestKeyAfter(now.minusSeconds(1)).get());
assertEquals(key2, chain.findOldestKeyAfter(now.plus(1, ChronoUnit.DAYS).minusSeconds(1)).get());
assertEquals(2, chain.findKeysBefore(now.plus(2, ChronoUnit.DAYS)).size());
assertEquals(1, chain.findKeysBefore(now.plusSeconds(1)).size());
assertEquals(0, chain.findKeysBefore(now.minusSeconds(1)).size());
}
}
| 11,866
| 38.822148
| 107
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/wallet/KeyChainGroupTest.java
|
/*
* Copyright 2014 Mike Hearn
* Copyright 2019 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.wallet;
import org.bitcoinj.base.Address;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.crypto.AesKey;
import org.bitcoinj.core.BloomFilter;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.KeyCrypterException;
import org.bitcoinj.crypto.KeyCrypterScrypt;
import org.bitcoinj.crypto.MnemonicCode;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.utils.BriefLogFormatter;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.wallet.KeyChain.KeyPurpose;
import org.bitcoinj.wallet.listeners.KeyChainEventListener;
import org.junit.Before;
import org.junit.Test;
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class KeyChainGroupTest {
// Number of initial keys in this tests HD wallet, including interior keys.
private static final int INITIAL_KEYS = 4;
private static final int LOOKAHEAD_SIZE = 5;
private static final String XPUB = "xpub68KFnj3bqUx1s7mHejLDBPywCAKdJEu1b49uniEEn2WSbHmZ7xbLqFTjJbtx1LUcAt1DwhoqWHmo2s5WMJp6wi38CiF2hYD49qVViKVvAoi";
private static final byte[] ENTROPY = Sha256Hash.hash("don't use a string seed like this in real life".getBytes());
private static final KeyCrypterScrypt KEY_CRYPTER = new KeyCrypterScrypt(2);
private static final AesKey AES_KEY = KEY_CRYPTER.deriveKey("password");
private static final double LOW_FALSE_POSITIVE_RATE = 0.00001;
private KeyChainGroup group;
private DeterministicKey watchingAccountKey;
@Before
public void setup() {
BriefLogFormatter.init();
TimeUtils.setMockClock();
group = KeyChainGroup.builder(BitcoinNetwork.MAINNET).lookaheadSize(LOOKAHEAD_SIZE).fromRandom(ScriptType.P2PKH)
.build();
group.getActiveKeyChain(); // Force create a chain.
watchingAccountKey = DeterministicKey.deserializeB58(null, XPUB, BitcoinNetwork.MAINNET);
}
@Test
public void createDeterministic_P2PKH() {
KeyChainGroup kcg = KeyChainGroup.builder(BitcoinNetwork.MAINNET).fromRandom(ScriptType.P2PKH).build();
// check default
Address address = kcg.currentAddress(KeyPurpose.RECEIVE_FUNDS);
assertEquals(ScriptType.P2PKH, address.getOutputScriptType());
}
@Test
public void createDeterministic_P2WPKH() {
KeyChainGroup kcg = KeyChainGroup.builder(BitcoinNetwork.MAINNET).fromRandom(ScriptType.P2WPKH).build();
// check default
Address address = kcg.currentAddress(KeyPurpose.RECEIVE_FUNDS);
assertEquals(ScriptType.P2WPKH, address.getOutputScriptType());
// check fallback (this will go away at some point)
address = kcg.freshAddress(KeyPurpose.RECEIVE_FUNDS, ScriptType.P2PKH, null);
assertEquals(ScriptType.P2PKH, address.getOutputScriptType());
}
@Test
public void freshCurrentKeys() {
int numKeys = ((group.getLookaheadSize() + group.getLookaheadThreshold()) * 2) // * 2 because of internal/external
+ 1 // keys issued
+ group.getActiveKeyChain().getAccountPath().size() + 2 /* account key + int/ext parent keys */;
assertEquals(numKeys, group.numKeys());
assertEquals(2 * numKeys, group.getBloomFilterElementCount());
ECKey r1 = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertEquals(numKeys, group.numKeys());
assertEquals(2 * numKeys, group.getBloomFilterElementCount());
ECKey i1 = new ECKey();
group.importKeys(i1);
numKeys++;
assertEquals(numKeys, group.numKeys());
assertEquals(2 * numKeys, group.getBloomFilterElementCount());
ECKey r2 = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertEquals(r1, r2);
ECKey c1 = group.currentKey(KeyChain.KeyPurpose.CHANGE);
assertNotEquals(r1, c1);
ECKey r3 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertNotEquals(r1, r3);
ECKey c2 = group.freshKey(KeyChain.KeyPurpose.CHANGE);
assertNotEquals(r3, c2);
// Current key has not moved and will not under marked as used.
ECKey r4 = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertEquals(r2, r4);
ECKey c3 = group.currentKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(c1, c3);
// Mark as used. Current key is now different.
group.markPubKeyAsUsed(r4.getPubKey());
ECKey r5 = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertNotEquals(r4, r5);
}
@Test
public void imports() {
ECKey key1 = new ECKey();
int numKeys = group.numKeys();
assertFalse(group.removeImportedKey(key1));
assertEquals(1, group.importKeys(Collections.singletonList(key1)));
assertEquals(numKeys + 1, group.numKeys()); // Lookahead is triggered by requesting a key, so none yet.
group.removeImportedKey(key1);
assertEquals(numKeys, group.numKeys());
}
@Test
public void findKey() {
ECKey a = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
ECKey b = group.freshKey(KeyChain.KeyPurpose.CHANGE);
ECKey c = new ECKey();
ECKey d = new ECKey(); // Not imported.
group.importKeys(c);
assertTrue(group.hasKey(a));
assertTrue(group.hasKey(b));
assertTrue(group.hasKey(c));
assertFalse(group.hasKey(d));
ECKey result = group.findKeyFromPubKey(a.getPubKey());
assertEquals(a, result);
result = group.findKeyFromPubKey(b.getPubKey());
assertEquals(b, result);
result = group.findKeyFromPubKeyHash(a.getPubKeyHash(), null);
assertEquals(a, result);
result = group.findKeyFromPubKeyHash(b.getPubKeyHash(), null);
assertEquals(b, result);
result = group.findKeyFromPubKey(c.getPubKey());
assertEquals(c, result);
result = group.findKeyFromPubKeyHash(c.getPubKeyHash(), null);
assertEquals(c, result);
assertNull(group.findKeyFromPubKey(d.getPubKey()));
assertNull(group.findKeyFromPubKeyHash(d.getPubKeyHash(), null));
}
// Check encryption with and without a basic keychain.
@Test
public void encryptionWithoutImported() {
encryption(false);
}
@Test
public void encryptionWithImported() {
encryption(true);
}
private void encryption(boolean withImported) {
Instant now = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS);
TimeUtils.setMockClock(now);
ECKey a = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertEquals(now, group.earliestKeyCreationTime());
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
TimeUtils.setMockClock(yesterday);
ECKey b = new ECKey();
assertFalse(group.isEncrypted());
try {
group.checkPassword("foo"); // Cannot check password of an unencrypted group.
fail();
} catch (IllegalStateException e) {
}
if (withImported) {
assertEquals(now, group.earliestKeyCreationTime());
group.importKeys(b);
assertEquals(yesterday, group.earliestKeyCreationTime());
}
group.encrypt(KEY_CRYPTER, AES_KEY);
assertTrue(group.isEncrypted());
assertTrue(group.checkPassword("password"));
assertFalse(group.checkPassword("wrong password"));
final ECKey ea = group.findKeyFromPubKey(a.getPubKey());
assertTrue(Objects.requireNonNull(ea).isEncrypted());
if (withImported) {
assertTrue(Objects.requireNonNull(group.findKeyFromPubKey(b.getPubKey())).isEncrypted());
assertEquals(yesterday, group.earliestKeyCreationTime());
} else {
assertEquals(now, group.earliestKeyCreationTime());
}
try {
ea.sign(Sha256Hash.ZERO_HASH);
fail();
} catch (ECKey.KeyIsEncryptedException e) {
// Ignored.
}
if (withImported) {
ECKey c = new ECKey();
try {
group.importKeys(c);
fail();
} catch (KeyCrypterException e) {
}
group.importKeysAndEncrypt(Collections.singletonList(c), AES_KEY);
ECKey ec = group.findKeyFromPubKey(c.getPubKey());
try {
group.importKeysAndEncrypt(Collections.singletonList(ec), AES_KEY);
fail();
} catch (IllegalArgumentException e) {
}
}
try {
group.decrypt(KEY_CRYPTER.deriveKey("WRONG PASSWORD"));
fail();
} catch (KeyCrypterException e) {
}
group.decrypt(AES_KEY);
assertFalse(group.isEncrypted());
assertFalse(Objects.requireNonNull(group.findKeyFromPubKey(a.getPubKey())).isEncrypted());
if (withImported) {
assertFalse(Objects.requireNonNull(group.findKeyFromPubKey(b.getPubKey())).isEncrypted());
assertEquals(yesterday, group.earliestKeyCreationTime());
} else {
assertEquals(now, group.earliestKeyCreationTime());
}
}
@Test
public void encryptionWhilstEmpty() {
group = KeyChainGroup.builder(BitcoinNetwork.MAINNET).lookaheadSize(5).fromRandom(ScriptType.P2PKH).build();
group.encrypt(KEY_CRYPTER, AES_KEY);
assertTrue(group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).isEncrypted());
final ECKey key = group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
group.decrypt(AES_KEY);
assertFalse(Objects.requireNonNull(group.findKeyFromPubKey(key.getPubKey())).isEncrypted());
}
@Test
public void bloom() {
ECKey key1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
ECKey key2 = new ECKey();
BloomFilter filter = group.getBloomFilter(group.getBloomFilterElementCount(), LOW_FALSE_POSITIVE_RATE, new Random().nextInt());
assertTrue(filter.contains(key1.getPubKeyHash()));
assertTrue(filter.contains(key1.getPubKey()));
assertFalse(filter.contains(key2.getPubKey()));
// Check that the filter contains the lookahead buffer and threshold zone.
for (int i = 0; i < LOOKAHEAD_SIZE + group.getLookaheadThreshold(); i++) {
ECKey k = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertTrue(filter.contains(k.getPubKeyHash()));
}
// We ran ahead of the lookahead buffer.
assertFalse(filter.contains(group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKey()));
group.importKeys(key2);
filter = group.getBloomFilter(group.getBloomFilterElementCount(), LOW_FALSE_POSITIVE_RATE, new Random().nextInt());
assertTrue(filter.contains(key1.getPubKeyHash()));
assertTrue(filter.contains(key1.getPubKey()));
assertTrue(filter.contains(key2.getPubKey()));
}
@Test
public void earliestKeyTime() {
Instant now = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS);
TimeUtils.setMockClock(now);
assertEquals(now, group.earliestKeyCreationTime());
TimeUtils.rollMockClock(Duration.ofSeconds(10_000));
group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
TimeUtils.rollMockClock(Duration.ofSeconds(10_000));
group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
// Check that all keys are assumed to be created at the same instant the seed is.
assertEquals(now, group.earliestKeyCreationTime());
ECKey key = new ECKey();
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
key.setCreationTime(yesterday);
group.importKeys(key);
assertEquals(yesterday, group.earliestKeyCreationTime());
}
@Test
public void events() {
// Check that events are registered with the right chains and that if a chain is added, it gets the event
// listeners attached properly even post-hoc.
final AtomicReference<ECKey> ran = new AtomicReference<>(null);
final KeyChainEventListener listener = keys -> ran.set(keys.get(0));
group.addEventListener(listener, Threading.SAME_THREAD);
ECKey key = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertEquals(key, ran.getAndSet(null));
ECKey key2 = new ECKey();
group.importKeys(key2);
assertEquals(key2, ran.getAndSet(null));
group.removeEventListener(listener);
ECKey key3 = new ECKey();
group.importKeys(key3);
assertNull(ran.get());
}
@Test
public void serialization() throws Exception {
int initialKeys = INITIAL_KEYS + group.getActiveKeyChain().getAccountPath().size() - 1;
assertEquals(initialKeys + 1 /* for the seed */, group.serializeToProtobuf().size());
group = KeyChainGroup.fromProtobufUnencrypted(BitcoinNetwork.MAINNET, group.serializeToProtobuf());
group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key2 = group.freshKey(KeyChain.KeyPurpose.CHANGE);
group.getBloomFilterElementCount();
List<Protos.Key> protoKeys1 = group.serializeToProtobuf();
assertEquals(initialKeys + ((LOOKAHEAD_SIZE + 1) * 2) + 1 /* for the seed */ + 1, protoKeys1.size());
group.importKeys(new ECKey());
List<Protos.Key> protoKeys2 = group.serializeToProtobuf();
assertEquals(initialKeys + ((LOOKAHEAD_SIZE + 1) * 2) + 1 /* for the seed */ + 2, protoKeys2.size());
group = KeyChainGroup.fromProtobufUnencrypted(BitcoinNetwork.MAINNET, protoKeys1);
assertEquals(initialKeys + ((LOOKAHEAD_SIZE + 1) * 2) + 1 /* for the seed */ + 1, protoKeys1.size());
assertTrue(group.hasKey(key1));
assertTrue(group.hasKey(key2));
assertEquals(key2, group.currentKey(KeyChain.KeyPurpose.CHANGE));
assertEquals(key1, group.currentKey(KeyChain.KeyPurpose.RECEIVE_FUNDS));
group = KeyChainGroup.fromProtobufUnencrypted(BitcoinNetwork.MAINNET, protoKeys2);
assertEquals(initialKeys + ((LOOKAHEAD_SIZE + 1) * 2) + 1 /* for the seed */ + 2, protoKeys2.size());
assertTrue(group.hasKey(key1));
assertTrue(group.hasKey(key2));
group.encrypt(KEY_CRYPTER, AES_KEY);
List<Protos.Key> protoKeys3 = group.serializeToProtobuf();
group = KeyChainGroup.fromProtobufEncrypted(BitcoinNetwork.MAINNET, protoKeys3, KEY_CRYPTER);
assertTrue(group.isEncrypted());
assertTrue(group.checkPassword("password"));
group.decrypt(AES_KEY);
// No need for extensive contents testing here, as that's done in the keychain class tests.
}
@Test
public void serializeWatching() throws Exception {
group = KeyChainGroup.builder(BitcoinNetwork.MAINNET).lookaheadSize(LOOKAHEAD_SIZE).addChain(DeterministicKeyChain.builder()
.watch(watchingAccountKey).outputScriptType(ScriptType.P2PKH).build()).build();
group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
group.freshKey(KeyChain.KeyPurpose.CHANGE);
group.getBloomFilterElementCount(); // Force lookahead.
List<Protos.Key> protoKeys1 = group.serializeToProtobuf();
assertEquals(3 + (group.getLookaheadSize() + group.getLookaheadThreshold() + 1) * 2, protoKeys1.size());
group = KeyChainGroup.fromProtobufUnencrypted(BitcoinNetwork.MAINNET, protoKeys1);
assertEquals(3 + (group.getLookaheadSize() + group.getLookaheadThreshold() + 1) * 2, group.serializeToProtobuf().size());
}
@Test
public void constructFromSeed() {
ECKey key1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
final DeterministicSeed seed = Objects.requireNonNull(group.getActiveKeyChain().getSeed());
KeyChainGroup group2 = KeyChainGroup.builder(BitcoinNetwork.MAINNET).lookaheadSize(5)
.addChain(DeterministicKeyChain.builder().seed(seed).outputScriptType(ScriptType.P2PKH).build())
.build();
ECKey key2 = group2.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertEquals(key1, key2);
}
@Test
public void addAndActivateHDChain_freshCurrentAddress() {
DeterministicSeed seed = DeterministicSeed.ofEntropy(ENTROPY, "");
DeterministicKeyChain chain1 = DeterministicKeyChain.builder().seed(seed)
.accountPath(DeterministicKeyChain.ACCOUNT_ZERO_PATH).outputScriptType(ScriptType.P2PKH).build();
group = KeyChainGroup.builder(BitcoinNetwork.MAINNET).addChain(chain1).build();
assertEquals("1M5T5k9yKtGWRtWYMjQtGx3K2sshrABzCT", group.currentAddress(KeyPurpose.RECEIVE_FUNDS).toString());
final DeterministicKeyChain chain2 = DeterministicKeyChain.builder().seed(seed)
.accountPath(DeterministicKeyChain.ACCOUNT_ONE_PATH).outputScriptType(ScriptType.P2PKH).build();
group.addAndActivateHDChain(chain2);
assertEquals("1JLnjJEXcyByAaW6sqSxNvGiiSEWRhdvPb", group.currentAddress(KeyPurpose.RECEIVE_FUNDS).toString());
final DeterministicKeyChain chain3 = DeterministicKeyChain.builder().seed(seed)
.accountPath(DeterministicKeyChain.BIP44_ACCOUNT_ZERO_PATH).outputScriptType(ScriptType.P2WPKH)
.build();
group.addAndActivateHDChain(chain3);
assertEquals("bc1q5fa84aghxd6uzk5g2ywkppmzlut5d77vg8cd20",
group.currentAddress(KeyPurpose.RECEIVE_FUNDS).toString());
}
@Test(expected = DeterministicUpgradeRequiredException.class)
public void deterministicUpgradeRequired() {
// Check that if we try to use HD features in a KCG that only has random keys, we get an exception.
group = KeyChainGroup.builder(BitcoinNetwork.MAINNET).build();
group.importKeys(new ECKey(), new ECKey());
assertTrue(group.isDeterministicUpgradeRequired(ScriptType.P2PKH, null));
assertTrue(group.isDeterministicUpgradeRequired(ScriptType.P2WPKH, null));
group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS); // throws
}
@Test
public void deterministicUpgradeUnencrypted() throws Exception {
group = KeyChainGroup.builder(BitcoinNetwork.MAINNET).fromRandom(ScriptType.P2PKH).lookaheadSize(LOOKAHEAD_SIZE).build();
List<Protos.Key> protobufs = group.serializeToProtobuf();
group.upgradeToDeterministic(ScriptType.P2PKH, KeyChainGroupStructure.BIP32, null, null);
assertFalse(group.isEncrypted());
assertFalse(group.isDeterministicUpgradeRequired(ScriptType.P2PKH, null));
assertTrue(group.isDeterministicUpgradeRequired(ScriptType.P2WPKH, null));
DeterministicKey dkey1 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicSeed seed1 = group.getActiveKeyChain().getSeed();
assertNotNull(seed1);
group = KeyChainGroup.fromProtobufUnencrypted(BitcoinNetwork.MAINNET, protobufs);
group.upgradeToDeterministic(ScriptType.P2PKH, KeyChainGroupStructure.BIP32, null, null); // Should give same result as last time.
assertFalse(group.isEncrypted());
assertFalse(group.isDeterministicUpgradeRequired(ScriptType.P2PKH, null));
assertTrue(group.isDeterministicUpgradeRequired(ScriptType.P2WPKH, null));
DeterministicKey dkey2 = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicSeed seed2 = group.getActiveKeyChain().getSeed();
assertEquals(seed1, seed2);
assertEquals(dkey1, dkey2);
}
@Test
public void deterministicUpgradeEncrypted() throws Exception {
group = KeyChainGroup.builder(BitcoinNetwork.MAINNET).fromRandom(ScriptType.P2PKH).build();
group.encrypt(KEY_CRYPTER, AES_KEY);
assertTrue(group.isEncrypted());
assertFalse(group.isDeterministicUpgradeRequired(ScriptType.P2PKH, null));
assertTrue(group.isDeterministicUpgradeRequired(ScriptType.P2WPKH, null));
final DeterministicSeed deterministicSeed = group.getActiveKeyChain().getSeed();
assertNotNull(deterministicSeed);
assertTrue(deterministicSeed.isEncrypted());
byte[] entropy = Objects.requireNonNull(group.getActiveKeyChain().toDecrypted(AES_KEY).getSeed()).getEntropyBytes();
}
@Test
public void markAsUsed() {
Address addr1 = group.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
Address addr2 = group.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertEquals(addr1, addr2);
group.markPubKeyHashAsUsed(addr1.getHash());
Address addr3 = group.currentAddress(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertNotEquals(addr2, addr3);
}
@Test
public void isNotWatching() {
group = KeyChainGroup.builder(BitcoinNetwork.MAINNET).fromRandom(ScriptType.P2PKH).build();
final ECKey key = ECKey.fromPrivate(BigInteger.TEN);
group.importKeys(key);
assertFalse(group.isWatching());
}
@Test
public void isWatching() {
group = KeyChainGroup.builder(BitcoinNetwork.MAINNET)
.addChain(DeterministicKeyChain.builder().watch(DeterministicKey.deserializeB58(
"xpub69bjfJ91ikC5ghsqsVDHNq2dRGaV2HHVx7Y9LXi27LN9BWWAXPTQr4u8U3wAtap8bLdHdkqPpAcZmhMS5SnrMQC4ccaoBccFhh315P4UYzo",
BitcoinNetwork.MAINNET)).outputScriptType(ScriptType.P2PKH).build())
.build();
final ECKey watchingKey = ECKey.fromPublicOnly(new ECKey());
group.importKeys(watchingKey);
assertTrue(group.isWatching());
}
@Test(expected = IllegalStateException.class)
public void isWatchingNoKeys() {
group = KeyChainGroup.builder(BitcoinNetwork.MAINNET).build();
group.isWatching();
}
@Test(expected = IllegalStateException.class)
public void isWatchingMixedKeys() {
group = KeyChainGroup.builder(BitcoinNetwork.MAINNET)
.addChain(DeterministicKeyChain.builder().watch(DeterministicKey.deserializeB58(
"xpub69bjfJ91ikC5ghsqsVDHNq2dRGaV2HHVx7Y9LXi27LN9BWWAXPTQr4u8U3wAtap8bLdHdkqPpAcZmhMS5SnrMQC4ccaoBccFhh315P4UYzo",
BitcoinNetwork.MAINNET)).outputScriptType(ScriptType.P2PKH).build())
.build();
final ECKey key = ECKey.fromPrivate(BigInteger.TEN);
group.importKeys(key);
group.isWatching();
}
@Test
public void segwitKeyChainGroup() throws Exception {
group = KeyChainGroup.builder(BitcoinNetwork.MAINNET).lookaheadSize(LOOKAHEAD_SIZE)
.addChain(DeterministicKeyChain.builder().entropy(ENTROPY, TimeUtils.currentTime()).outputScriptType(ScriptType.P2WPKH)
.accountPath(DeterministicKeyChain.ACCOUNT_ONE_PATH).build())
.build();
assertEquals(ScriptType.P2WPKH, group.getActiveKeyChain().getOutputScriptType());
assertEquals("bc1qhcurdec849thpjjp3e27atvya43gy2snrechd9",
group.currentAddress(KeyPurpose.RECEIVE_FUNDS).toString());
assertEquals("bc1qw8sf3mwuwn74qnhj83gjg0cwkk78fun2pxl9t2", group.currentAddress(KeyPurpose.CHANGE).toString());
// round-trip through protobuf
group = KeyChainGroup.fromProtobufUnencrypted(BitcoinNetwork.MAINNET, group.serializeToProtobuf());
assertEquals(ScriptType.P2WPKH, group.getActiveKeyChain().getOutputScriptType());
assertEquals("bc1qhcurdec849thpjjp3e27atvya43gy2snrechd9",
group.currentAddress(KeyPurpose.RECEIVE_FUNDS).toString());
assertEquals("bc1qw8sf3mwuwn74qnhj83gjg0cwkk78fun2pxl9t2", group.currentAddress(KeyPurpose.CHANGE).toString());
// encryption
group.encrypt(KEY_CRYPTER, AES_KEY);
assertEquals(ScriptType.P2WPKH, group.getActiveKeyChain().getOutputScriptType());
assertEquals("bc1qhcurdec849thpjjp3e27atvya43gy2snrechd9",
group.currentAddress(KeyPurpose.RECEIVE_FUNDS).toString());
assertEquals("bc1qw8sf3mwuwn74qnhj83gjg0cwkk78fun2pxl9t2", group.currentAddress(KeyPurpose.CHANGE).toString());
// round-trip encrypted again, then dectypt
group = KeyChainGroup.fromProtobufEncrypted(BitcoinNetwork.MAINNET, group.serializeToProtobuf(), KEY_CRYPTER);
group.decrypt(AES_KEY);
assertEquals(ScriptType.P2WPKH, group.getActiveKeyChain().getOutputScriptType());
assertEquals("bc1qhcurdec849thpjjp3e27atvya43gy2snrechd9",
group.currentAddress(KeyPurpose.RECEIVE_FUNDS).toString());
assertEquals("bc1qw8sf3mwuwn74qnhj83gjg0cwkk78fun2pxl9t2", group.currentAddress(KeyPurpose.CHANGE).toString());
}
@Test
public void onlyBasicKeyEncryptionAndDecryption() {
group = KeyChainGroup.createBasic(BitcoinNetwork.MAINNET);
final ECKey key = ECKey.fromPrivate(BigInteger.TEN);
group.importKeys(key);
group.encrypt(KEY_CRYPTER, AES_KEY);
group.decrypt(AES_KEY);
}
}
| 26,337
| 47.415441
| 153
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/wallet/DeterministicKeyChainTest.java
|
/*
* Copyright 2013 Google Inc.
* Copyright 2018 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.wallet;
import com.google.common.collect.Lists;
import org.bitcoinj.base.Network;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.Address;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.crypto.AesKey;
import org.bitcoinj.core.BloomFilter;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.base.LegacyAddress;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDKeyDerivation;
import org.bitcoinj.crypto.HDPath;
import org.bitcoinj.utils.BriefLogFormatter;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.wallet.listeners.AbstractKeyChainEventListener;
import org.junit.Before;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static org.bitcoinj.base.BitcoinNetwork.MAINNET;
import static org.bitcoinj.base.BitcoinNetwork.TESTNET;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class DeterministicKeyChainTest {
private DeterministicKeyChain chain;
private DeterministicKeyChain segwitChain;
private DeterministicKeyChain bip44chain;
private final byte[] ENTROPY = Sha256Hash.hash("don't use a string seed like this in real life".getBytes());
private static final HDPath BIP44_COIN_1_ACCOUNT_ZERO_PATH = HDPath.M(new ChildNumber(44, true),
new ChildNumber(1, true), ChildNumber.ZERO_HARDENED);
@Before
public void setup() {
BriefLogFormatter.init();
// You should use a random seed instead. The secs constant comes from the unit test file, so we can compare
// serialized data properly.
Instant secs = Instant.ofEpochSecond(1389353062L);
chain = DeterministicKeyChain.builder().entropy(ENTROPY, secs)
.accountPath(DeterministicKeyChain.ACCOUNT_ZERO_PATH).outputScriptType(ScriptType.P2PKH).build();
chain.setLookaheadSize(10);
segwitChain = DeterministicKeyChain.builder().entropy(ENTROPY, secs)
.accountPath(DeterministicKeyChain.ACCOUNT_ONE_PATH).outputScriptType(ScriptType.P2WPKH).build();
segwitChain.setLookaheadSize(10);
bip44chain = DeterministicKeyChain.builder().entropy(ENTROPY, secs).accountPath(BIP44_COIN_1_ACCOUNT_ZERO_PATH)
.outputScriptType(ScriptType.P2PKH).build();
bip44chain.setLookaheadSize(10);
}
@Test
public void derive() {
ECKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertFalse(key1.isPubKeyOnly());
ECKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertFalse(key2.isPubKeyOnly());
final Address address = LegacyAddress.fromBase58("n1bQNoEx8uhmCzzA5JPG6sFdtsUQhwiQJV", TESTNET);
assertEquals(address, key1.toAddress(ScriptType.P2PKH, TESTNET));
assertEquals("mnHUcqUVvrfi5kAaXJDQzBb9HsWs78b42R", key2.toAddress(ScriptType.P2PKH, TESTNET).toString());
assertEquals(key1, chain.findKeyFromPubHash(address.getHash()));
assertEquals(key2, chain.findKeyFromPubKey(key2.getPubKey()));
key1.sign(Sha256Hash.ZERO_HASH);
assertFalse(key1.isPubKeyOnly());
ECKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertFalse(key3.isPubKeyOnly());
assertEquals("mqumHgVDqNzuXNrszBmi7A2UpmwaPMx4HQ", key3.toAddress(ScriptType.P2PKH, TESTNET).toString());
key3.sign(Sha256Hash.ZERO_HASH);
assertFalse(key3.isPubKeyOnly());
}
@Test
public void getKeys() {
chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
chain.getKey(KeyChain.KeyPurpose.CHANGE);
chain.maybeLookAhead();
assertEquals(2, chain.getKeys(false, false).size());
}
@Test
public void deriveAccountOne() {
final Instant secs = Instant.ofEpochSecond(1389353062L);
final HDPath accountOne = HDPath.M(ChildNumber.ONE);
DeterministicKeyChain chain1 = DeterministicKeyChain.builder().accountPath(accountOne)
.entropy(ENTROPY, secs).build();
ECKey key1 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
ECKey key2 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
final Address address = LegacyAddress.fromBase58("n2nHHRHs7TiZScTuVhZUkzZfTfVgGYwy6X", TESTNET);
assertEquals(address, key1.toAddress(ScriptType.P2PKH, TESTNET));
assertEquals("mnp2j9za5zMuz44vNxrJCXXhZsCdh89QXn", key2.toAddress(ScriptType.P2PKH, TESTNET).toString());
assertEquals(key1, chain1.findKeyFromPubHash(address.getHash()));
assertEquals(key2, chain1.findKeyFromPubKey(key2.getPubKey()));
key1.sign(Sha256Hash.ZERO_HASH);
ECKey key3 = chain1.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals("mpjRhk13rvV7vmnszcUQVYVQzy4HLTPTQU", key3.toAddress(ScriptType.P2PKH, TESTNET).toString());
key3.sign(Sha256Hash.ZERO_HASH);
}
@Test
public void serializeAccountOne() throws Exception {
Instant secs = Instant.ofEpochSecond(1389353062L);
final HDPath accountOne = HDPath.M(ChildNumber.ONE);
DeterministicKeyChain chain1 = DeterministicKeyChain.builder().accountPath(accountOne)
.entropy(ENTROPY, secs).build();
ECKey key1 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
final Address address = LegacyAddress.fromBase58("n2nHHRHs7TiZScTuVhZUkzZfTfVgGYwy6X", TESTNET);
assertEquals(address, key1.toAddress(ScriptType.P2PKH, TESTNET));
DeterministicKey watching = chain1.getWatchingKey();
List<Protos.Key> keys = chain1.serializeToProtobuf();
chain1 = DeterministicKeyChain.fromProtobuf(keys, null).get(0);
assertEquals(accountOne, chain1.getAccountPath());
ECKey key2 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertEquals("mnp2j9za5zMuz44vNxrJCXXhZsCdh89QXn", key2.toAddress(ScriptType.P2PKH, TESTNET).toString());
assertEquals(key1, chain1.findKeyFromPubHash(address.getHash()));
assertEquals(key2, chain1.findKeyFromPubKey(key2.getPubKey()));
key1.sign(Sha256Hash.ZERO_HASH);
ECKey key3 = chain1.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals("mpjRhk13rvV7vmnszcUQVYVQzy4HLTPTQU", key3.toAddress(ScriptType.P2PKH, TESTNET).toString());
key3.sign(Sha256Hash.ZERO_HASH);
assertEquals(watching, chain1.getWatchingKey());
}
@Test
public void signMessage() throws Exception {
ECKey key = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
key.verifyMessage("test", key.signMessage("test"));
}
@Test
public void events() {
// Check that we get the right events at the right time.
final List<List<ECKey>> listenerKeys = new ArrayList<>();
Instant secs = Instant.ofEpochSecond(1389353062L);
chain = DeterministicKeyChain.builder().entropy(ENTROPY, secs).outputScriptType(ScriptType.P2PKH)
.build();
chain.addEventListener(new AbstractKeyChainEventListener() {
@Override
public void onKeysAdded(List<ECKey> keys) {
listenerKeys.add(keys);
}
}, Threading.SAME_THREAD);
assertEquals(0, listenerKeys.size());
chain.setLookaheadSize(5);
assertEquals(0, listenerKeys.size());
ECKey key = chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(1, listenerKeys.size()); // 1 event
final List<ECKey> firstEvent = listenerKeys.get(0);
assertEquals(1, firstEvent.size());
assertTrue(firstEvent.contains(key)); // order is not specified.
listenerKeys.clear();
chain.maybeLookAhead();
final List<ECKey> secondEvent = listenerKeys.get(0);
assertEquals(12, secondEvent.size()); // (5 lookahead keys, +1 lookahead threshold) * 2 chains
listenerKeys.clear();
chain.getKey(KeyChain.KeyPurpose.CHANGE);
// At this point we've entered the threshold zone so more keys won't immediately trigger more generations.
assertEquals(0, listenerKeys.size()); // 1 event
final int lookaheadThreshold = chain.getLookaheadThreshold() + chain.getLookaheadSize();
for (int i = 0; i < lookaheadThreshold; i++)
chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(1, listenerKeys.size()); // 1 event
assertEquals(1, listenerKeys.get(0).size()); // 1 key.
}
@Test
public void random() {
// Can't test much here but verify the constructor worked and the class is functional. The other tests rely on
// a fixed seed to be deterministic.
chain = DeterministicKeyChain.builder().random(new SecureRandom(), 384).build();
chain.setLookaheadSize(10);
chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).sign(Sha256Hash.ZERO_HASH);
chain.getKey(KeyChain.KeyPurpose.CHANGE).sign(Sha256Hash.ZERO_HASH);
}
@Test
public void serializeUnencrypted() throws UnreadableWalletException {
chain.maybeLookAhead();
DeterministicKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
List<Protos.Key> keys = chain.serializeToProtobuf();
// 1 mnemonic/seed, 1 master key, 1 account key, 2 internal keys, 3 derived, 20 lookahead and 5 lookahead threshold.
int numItems =
1 // mnemonic/seed
+ 1 // master key
+ 1 // account key
+ 2 // ext/int parent keys
+ (chain.getLookaheadSize() + chain.getLookaheadThreshold()) * 2 // lookahead zone on each chain
;
assertEquals(numItems, keys.size());
// Get another key that will be lost during round-tripping, to ensure we can derive it again.
DeterministicKey key4 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
final String EXPECTED_SERIALIZATION = checkSerialization(keys, "deterministic-wallet-serialization.txt");
// Round trip the data back and forth to check it is preserved.
int oldLookaheadSize = chain.getLookaheadSize();
chain = DeterministicKeyChain.fromProtobuf(keys, null).get(0);
assertEquals(DeterministicKeyChain.ACCOUNT_ZERO_PATH, chain.getAccountPath());
assertEquals(EXPECTED_SERIALIZATION, protoToString(chain.serializeToProtobuf()));
assertEquals(key1, chain.findKeyFromPubHash(key1.getPubKeyHash()));
assertEquals(key2, chain.findKeyFromPubHash(key2.getPubKeyHash()));
assertEquals(key3, chain.findKeyFromPubHash(key3.getPubKeyHash()));
assertEquals(key4, chain.getKey(KeyChain.KeyPurpose.CHANGE));
key1.sign(Sha256Hash.ZERO_HASH);
key2.sign(Sha256Hash.ZERO_HASH);
key3.sign(Sha256Hash.ZERO_HASH);
key4.sign(Sha256Hash.ZERO_HASH);
assertEquals(oldLookaheadSize, chain.getLookaheadSize());
}
@Test
public void serializeSegwitUnencrypted() throws UnreadableWalletException {
segwitChain.maybeLookAhead();
DeterministicKey key1 = segwitChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key2 = segwitChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key3 = segwitChain.getKey(KeyChain.KeyPurpose.CHANGE);
List<Protos.Key> keys = segwitChain.serializeToProtobuf();
// 1 mnemonic/seed, 1 master key, 1 account key, 2 internal keys, 3 derived, 20 lookahead and 5 lookahead threshold.
int numItems =
1 // mnemonic/seed
+ 1 // master key
+ 1 // account key
+ 2 // ext/int parent keys
+ (segwitChain.getLookaheadSize() + segwitChain.getLookaheadThreshold()) * 2 // lookahead zone on each chain
;
assertEquals(numItems, keys.size());
// Get another key that will be lost during round-tripping, to ensure we can derive it again.
DeterministicKey key4 = segwitChain.getKey(KeyChain.KeyPurpose.CHANGE);
final String EXPECTED_SERIALIZATION = checkSerialization(keys, "deterministic-wallet-segwit-serialization.txt");
// Round trip the data back and forth to check it is preserved.
int oldLookaheadSize = segwitChain.getLookaheadSize();
segwitChain = DeterministicKeyChain.fromProtobuf(keys, null).get(0);
assertEquals(EXPECTED_SERIALIZATION, protoToString(segwitChain.serializeToProtobuf()));
assertEquals(key1, segwitChain.findKeyFromPubHash(key1.getPubKeyHash()));
assertEquals(key2, segwitChain.findKeyFromPubHash(key2.getPubKeyHash()));
assertEquals(key3, segwitChain.findKeyFromPubHash(key3.getPubKeyHash()));
assertEquals(key4, segwitChain.getKey(KeyChain.KeyPurpose.CHANGE));
key1.sign(Sha256Hash.ZERO_HASH);
key2.sign(Sha256Hash.ZERO_HASH);
key3.sign(Sha256Hash.ZERO_HASH);
key4.sign(Sha256Hash.ZERO_HASH);
assertEquals(oldLookaheadSize, segwitChain.getLookaheadSize());
}
@Test
public void serializeUnencryptedBIP44() throws UnreadableWalletException {
bip44chain.maybeLookAhead();
DeterministicKey key1 = bip44chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key2 = bip44chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key3 = bip44chain.getKey(KeyChain.KeyPurpose.CHANGE);
List<Protos.Key> keys = bip44chain.serializeToProtobuf();
// 1 mnemonic/seed, 1 master key, 1 account key, 2 internal keys, 3 derived, 20 lookahead and 5 lookahead
// threshold.
int numItems = 3 // mnemonic/seed
+ 1 // master key
+ 1 // account key
+ 2 // ext/int parent keys
+ (bip44chain.getLookaheadSize() + bip44chain.getLookaheadThreshold()) * 2 // lookahead zone on each chain
;
assertEquals(numItems, keys.size());
// Get another key that will be lost during round-tripping, to ensure we can derive it again.
DeterministicKey key4 = bip44chain.getKey(KeyChain.KeyPurpose.CHANGE);
final String EXPECTED_SERIALIZATION = checkSerialization(keys, "deterministic-wallet-bip44-serialization.txt");
// Round trip the data back and forth to check it is preserved.
int oldLookaheadSize = bip44chain.getLookaheadSize();
bip44chain = DeterministicKeyChain.fromProtobuf(keys, null).get(0);
assertEquals(BIP44_COIN_1_ACCOUNT_ZERO_PATH, bip44chain.getAccountPath());
assertEquals(EXPECTED_SERIALIZATION, protoToString(bip44chain.serializeToProtobuf()));
assertEquals(key1, bip44chain.findKeyFromPubHash(key1.getPubKeyHash()));
assertEquals(key2, bip44chain.findKeyFromPubHash(key2.getPubKeyHash()));
assertEquals(key3, bip44chain.findKeyFromPubHash(key3.getPubKeyHash()));
assertEquals(key4, bip44chain.getKey(KeyChain.KeyPurpose.CHANGE));
key1.sign(Sha256Hash.ZERO_HASH);
key2.sign(Sha256Hash.ZERO_HASH);
key3.sign(Sha256Hash.ZERO_HASH);
key4.sign(Sha256Hash.ZERO_HASH);
assertEquals(oldLookaheadSize, bip44chain.getLookaheadSize());
}
@Test(expected = IllegalStateException.class)
public void notEncrypted() {
chain.toDecrypted("fail");
}
@Test(expected = IllegalStateException.class)
public void encryptTwice() {
chain = chain.toEncrypted("once");
chain = chain.toEncrypted("twice");
}
private void checkEncryptedKeyChain(DeterministicKeyChain encChain, DeterministicKey key1) {
// Check we can look keys up and extend the chain without the AES key being provided.
DeterministicKey encKey1 = encChain.findKeyFromPubKey(key1.getPubKey());
DeterministicKey encKey2 = encChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertFalse(key1.isEncrypted());
assertTrue(encKey1.isEncrypted());
assertEquals(encKey1.getPubKeyPoint(), key1.getPubKeyPoint());
final AesKey aesKey = Objects.requireNonNull(encChain.getKeyCrypter()).deriveKey("open secret");
encKey1.sign(Sha256Hash.ZERO_HASH, aesKey);
encKey2.sign(Sha256Hash.ZERO_HASH, aesKey);
assertTrue(encChain.checkAESKey(aesKey));
assertFalse(encChain.checkPassword("access denied"));
assertTrue(encChain.checkPassword("open secret"));
}
@Test
public void encryption() throws UnreadableWalletException {
DeterministicKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKeyChain encChain = chain.toEncrypted("open secret");
DeterministicKey encKey1 = encChain.findKeyFromPubKey(key1.getPubKey());
checkEncryptedKeyChain(encChain, key1);
// Round-trip to ensure de/serialization works and that we can store two chains and they both deserialize.
List<Protos.Key> serialized = encChain.serializeToProtobuf();
List<Protos.Key> doubled = Lists.newArrayListWithExpectedSize(serialized.size() * 2);
doubled.addAll(serialized);
doubled.addAll(serialized);
final List<DeterministicKeyChain> chains = DeterministicKeyChain.fromProtobuf(doubled, encChain.getKeyCrypter());
assertEquals(2, chains.size());
encChain = chains.get(0);
checkEncryptedKeyChain(encChain, chain.findKeyFromPubKey(key1.getPubKey()));
encChain = chains.get(1);
checkEncryptedKeyChain(encChain, chain.findKeyFromPubKey(key1.getPubKey()));
DeterministicKey encKey2 = encChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
// Decrypt and check the keys match.
DeterministicKeyChain decChain = encChain.toDecrypted("open secret");
DeterministicKey decKey1 = decChain.findKeyFromPubHash(encKey1.getPubKeyHash());
DeterministicKey decKey2 = decChain.findKeyFromPubHash(encKey2.getPubKeyHash());
assertEquals(decKey1.getPubKeyPoint(), encKey1.getPubKeyPoint());
assertEquals(decKey2.getPubKeyPoint(), encKey2.getPubKeyPoint());
assertFalse(decKey1.isEncrypted());
assertFalse(decKey2.isEncrypted());
assertNotEquals(encKey1.getParent(), decKey1.getParent()); // parts of a different hierarchy
// Check we can once again derive keys from the decrypted chain.
decChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).sign(Sha256Hash.ZERO_HASH);
decChain.getKey(KeyChain.KeyPurpose.CHANGE).sign(Sha256Hash.ZERO_HASH);
}
@Test
public void watchingChain() throws UnreadableWalletException {
TimeUtils.setMockClock();
DeterministicKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
DeterministicKey key4 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
DeterministicKey watchingKey = chain.getWatchingKey();
final String pub58 = watchingKey.serializePubB58(MAINNET);
assertEquals("xpub69KR9epSNBM59KLuasxMU5CyKytMJjBP5HEZ5p8YoGUCpM6cM9hqxB9DDPCpUUtqmw5duTckvPfwpoWGQUFPmRLpxs5jYiTf2u6xRMcdhDf", pub58);
watchingKey = DeterministicKey.deserializeB58(null, pub58, MAINNET);
watchingKey.setCreationTime(Instant.ofEpochSecond(100000));
chain = DeterministicKeyChain.builder().watch(watchingKey).outputScriptType(chain.getOutputScriptType())
.build();
assertEquals(Instant.ofEpochSecond(100000), chain.earliestKeyCreationTime());
chain.setLookaheadSize(10);
chain.maybeLookAhead();
assertEquals(key1.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
assertEquals(key2.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
final DeterministicKey key = chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(key3.getPubKeyPoint(), key.getPubKeyPoint());
try {
// Can't sign with a key from a watching chain.
key.sign(Sha256Hash.ZERO_HASH);
fail();
} catch (ECKey.MissingPrivateKeyException e) {
// Ignored.
}
// Test we can serialize and deserialize a watching chain OK.
List<Protos.Key> serialization = chain.serializeToProtobuf();
checkSerialization(serialization, "watching-wallet-serialization.txt");
chain = DeterministicKeyChain.fromProtobuf(serialization, null).get(0);
assertEquals(DeterministicKeyChain.ACCOUNT_ZERO_PATH, chain.getAccountPath());
final DeterministicKey rekey4 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(key4.getPubKeyPoint(), rekey4.getPubKeyPoint());
}
@Test
public void watchingChainArbitraryPath() throws UnreadableWalletException {
TimeUtils.setMockClock();
DeterministicKey key1 = bip44chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key2 = bip44chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key3 = bip44chain.getKey(KeyChain.KeyPurpose.CHANGE);
DeterministicKey key4 = bip44chain.getKey(KeyChain.KeyPurpose.CHANGE);
DeterministicKey watchingKey = bip44chain.getWatchingKey();
watchingKey = watchingKey.dropPrivateBytes().dropParent();
watchingKey.setCreationTime(Instant.ofEpochSecond(100000));
chain = DeterministicKeyChain.builder().watch(watchingKey).outputScriptType(bip44chain.getOutputScriptType())
.build();
assertEquals(Instant.ofEpochSecond(100000), chain.earliestKeyCreationTime());
chain.setLookaheadSize(10);
chain.maybeLookAhead();
assertEquals(key1.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
assertEquals(key2.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
final DeterministicKey key = chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(key3.getPubKeyPoint(), key.getPubKeyPoint());
try {
// Can't sign with a key from a watching chain.
key.sign(Sha256Hash.ZERO_HASH);
fail();
} catch (ECKey.MissingPrivateKeyException e) {
// Ignored.
}
// Test we can serialize and deserialize a watching chain OK.
List<Protos.Key> serialization = chain.serializeToProtobuf();
checkSerialization(serialization, "watching-wallet-arbitrary-path-serialization.txt");
chain = DeterministicKeyChain.fromProtobuf(serialization, null).get(0);
assertEquals(BIP44_COIN_1_ACCOUNT_ZERO_PATH, chain.getAccountPath());
final DeterministicKey rekey4 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(key4.getPubKeyPoint(), rekey4.getPubKeyPoint());
}
@Test
public void watchingChainAccountOne() throws UnreadableWalletException {
TimeUtils.setMockClock();
final HDPath accountOne = HDPath.M(ChildNumber.ONE);
DeterministicKeyChain chain1 = DeterministicKeyChain.builder().accountPath(accountOne)
.seed(chain.getSeed()).build();
DeterministicKey key1 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key2 = chain1.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key3 = chain1.getKey(KeyChain.KeyPurpose.CHANGE);
DeterministicKey key4 = chain1.getKey(KeyChain.KeyPurpose.CHANGE);
DeterministicKey watchingKey = chain1.getWatchingKey();
final String pub58 = watchingKey.serializePubB58(MAINNET);
assertEquals("xpub69KR9epJ2Wp6ywiv4Xu5WfBUpX4GLu6D5NUMd4oUkCFoZoRNyk3ZCxfKPDkkGvCPa16dPgEdY63qoyLqEa5TQQy1nmfSmgWcagRzimyV7uA", pub58);
watchingKey = DeterministicKey.deserializeB58(null, pub58, MAINNET);
watchingKey.setCreationTime(Instant.ofEpochSecond(100000));
chain = DeterministicKeyChain.builder().watch(watchingKey).outputScriptType(chain1.getOutputScriptType())
.build();
assertEquals(accountOne, chain.getAccountPath());
assertEquals(Instant.ofEpochSecond(100000), chain.earliestKeyCreationTime());
chain.setLookaheadSize(10);
chain.maybeLookAhead();
assertEquals(key1.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
assertEquals(key2.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
final DeterministicKey key = chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(key3.getPubKeyPoint(), key.getPubKeyPoint());
try {
// Can't sign with a key from a watching chain.
key.sign(Sha256Hash.ZERO_HASH);
fail();
} catch (ECKey.MissingPrivateKeyException e) {
// Ignored.
}
// Test we can serialize and deserialize a watching chain OK.
List<Protos.Key> serialization = chain.serializeToProtobuf();
checkSerialization(serialization, "watching-wallet-serialization-account-one.txt");
chain = DeterministicKeyChain.fromProtobuf(serialization, null).get(0);
assertEquals(accountOne, chain.getAccountPath());
final DeterministicKey rekey4 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(key4.getPubKeyPoint(), rekey4.getPubKeyPoint());
}
@Test
public void watchingSegwitChain() throws UnreadableWalletException {
TimeUtils.setMockClock();
DeterministicKey key1 = segwitChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key2 = segwitChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key3 = segwitChain.getKey(KeyChain.KeyPurpose.CHANGE);
DeterministicKey key4 = segwitChain.getKey(KeyChain.KeyPurpose.CHANGE);
DeterministicKey watchingKey = segwitChain.getWatchingKey();
final String xpub58 = watchingKey.serializePubB58(MAINNET);
assertEquals("xpub69KR9epSNBM5B7rReBBuMcrhbHTEmEuLJ1FbSjrjgcMS1kVCNULE7PTEg2wxoomtcbmQ5uGcQ1dWBdJn4ycW2VTWQhxb114PLaRwFYeHuui", xpub58);
final String zpub58 = watchingKey.serializePubB58(MAINNET, segwitChain.getOutputScriptType());
assertEquals("zpub6nywkzAGfYS2siEfJtm9mo3hwDk8eUtL8EJ31XeWSd7C7x7esnfMMWmWiSs8od5jRt11arTjKLLbxCXuWNSXcxpi9PMSAphMt2ZE2gLnXGE", zpub58);
watchingKey = DeterministicKey.deserializeB58(null, xpub58, MAINNET);
watchingKey.setCreationTime(Instant.ofEpochSecond(100000));
segwitChain = DeterministicKeyChain.builder().watch(watchingKey)
.outputScriptType(segwitChain.getOutputScriptType()).build();
assertEquals(Instant.ofEpochSecond(100000), segwitChain.earliestKeyCreationTime());
segwitChain.setLookaheadSize(10);
segwitChain.maybeLookAhead();
assertEquals(key1.getPubKeyPoint(), segwitChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
assertEquals(key2.getPubKeyPoint(), segwitChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
final DeterministicKey key = segwitChain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(key3.getPubKeyPoint(), key.getPubKeyPoint());
try {
// Can't sign with a key from a watching chain.
key.sign(Sha256Hash.ZERO_HASH);
fail();
} catch (ECKey.MissingPrivateKeyException e) {
// Ignored.
}
// Test we can serialize and deserialize a watching chain OK.
List<Protos.Key> serialization = segwitChain.serializeToProtobuf();
checkSerialization(serialization, "watching-wallet-p2wpkh-serialization.txt");
final DeterministicKeyChain chain = DeterministicKeyChain.fromProtobuf(serialization, null).get(0);
assertEquals(DeterministicKeyChain.ACCOUNT_ONE_PATH, chain.getAccountPath());
assertEquals(ScriptType.P2WPKH, chain.getOutputScriptType());
final DeterministicKey rekey4 = segwitChain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(key4.getPubKeyPoint(), rekey4.getPubKeyPoint());
}
@Test
public void spendingChain() throws UnreadableWalletException {
TimeUtils.setMockClock();
DeterministicKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
DeterministicKey key4 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
Network network = MAINNET;
DeterministicKey watchingKey = chain.getWatchingKey();
final String prv58 = watchingKey.serializePrivB58(network);
assertEquals("xprv9vL4k9HYXonmvqGSUrRM6wGEmx3ruGTXi4JxHRiwEvwDwYmTocPbQNpjN89gpqPrFofmfvALwgnNFBCH2grse1YDf8ERAwgdvbjRtoMfsbV", prv58);
watchingKey = DeterministicKey.deserializeB58(null, prv58, network);
watchingKey.setCreationTime(Instant.ofEpochSecond(100000));
chain = DeterministicKeyChain.builder().spend(watchingKey).outputScriptType(chain.getOutputScriptType())
.build();
assertEquals(Instant.ofEpochSecond(100000), chain.earliestKeyCreationTime());
chain.setLookaheadSize(10);
chain.maybeLookAhead();
assertEquals(key1.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
assertEquals(key2.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
final DeterministicKey key = chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(key3.getPubKeyPoint(), key.getPubKeyPoint());
try {
// We can sign with a key from a spending chain.
key.sign(Sha256Hash.ZERO_HASH);
} catch (ECKey.MissingPrivateKeyException e) {
fail();
}
// Test we can serialize and deserialize a watching chain OK.
List<Protos.Key> serialization = chain.serializeToProtobuf();
checkSerialization(serialization, "spending-wallet-serialization.txt");
chain = DeterministicKeyChain.fromProtobuf(serialization, null).get(0);
assertEquals(DeterministicKeyChain.ACCOUNT_ZERO_PATH, chain.getAccountPath());
final DeterministicKey rekey4 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(key4.getPubKeyPoint(), rekey4.getPubKeyPoint());
}
@Test
public void spendingChainAccountTwo() throws UnreadableWalletException {
TimeUtils.setMockClock();
Instant secs = Instant.ofEpochSecond(1389353062L);
final HDPath accountTwo = HDPath.M(new ChildNumber(2, true));
chain = DeterministicKeyChain.builder().accountPath(accountTwo).entropy(ENTROPY, secs).build();
DeterministicKey firstReceiveKey = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey secondReceiveKey = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey firstChangeKey = chain.getKey(KeyChain.KeyPurpose.CHANGE);
DeterministicKey secondChangeKey = chain.getKey(KeyChain.KeyPurpose.CHANGE);
Network network = MAINNET;
DeterministicKey watchingKey = chain.getWatchingKey();
final String prv58 = watchingKey.serializePrivB58(network);
assertEquals("xprv9vL4k9HYXonmzR7UC1ngJ3hTjxkmjLLUo3RexSfUGSWcACHzghWBLJAwW6xzs59XeFizQxFQWtscoTfrF9PSXrUgAtBgr13Nuojax8xTBRz", prv58);
watchingKey = DeterministicKey.deserializeB58(null, prv58, network);
watchingKey.setCreationTime(secs);
chain = DeterministicKeyChain.builder().spend(watchingKey).outputScriptType(chain.getOutputScriptType())
.build();
assertEquals(accountTwo, chain.getAccountPath());
assertEquals(secs, chain.earliestKeyCreationTime());
chain.setLookaheadSize(10);
chain.maybeLookAhead();
verifySpendableKeyChain(firstReceiveKey, secondReceiveKey, firstChangeKey, secondChangeKey, chain, "spending-wallet-account-two-serialization.txt");
}
@Test
public void masterKeyAccount() throws UnreadableWalletException {
TimeUtils.setMockClock();
Instant secs = Instant.ofEpochSecond(1389353062L);
DeterministicKey firstReceiveKey = bip44chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey secondReceiveKey = bip44chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey firstChangeKey = bip44chain.getKey(KeyChain.KeyPurpose.CHANGE);
DeterministicKey secondChangeKey = bip44chain.getKey(KeyChain.KeyPurpose.CHANGE);
Network network = MAINNET;
DeterministicKey watchingKey = bip44chain.getWatchingKey(); //m/44'/1'/0'
DeterministicKey coinLevelKey = bip44chain.getWatchingKey().getParent(); //m/44'/1'
//Simulate Wallet.fromSpendingKeyB58(PARAMS, prv58, secs)
final String prv58 = watchingKey.serializePrivB58(network);
assertEquals("xprv9yYQhynAmWWuz62PScx5Q2frBET2F1raaXna5A2E9Lj8XWgmKBL7S98Yand8F736j9UCTNWQeiB4yL5pLZP7JDY2tY8eszGQkiKDwBkezeS", prv58);
watchingKey = DeterministicKey.deserializeB58(null, prv58, network);
watchingKey.setCreationTime(secs);
DeterministicKeyChain fromPrivBase58Chain = DeterministicKeyChain.builder().spend(watchingKey)
.outputScriptType(bip44chain.getOutputScriptType()).build();
assertEquals(secs, fromPrivBase58Chain.earliestKeyCreationTime());
fromPrivBase58Chain.setLookaheadSize(10);
fromPrivBase58Chain.maybeLookAhead();
verifySpendableKeyChain(firstReceiveKey, secondReceiveKey, firstChangeKey, secondChangeKey, fromPrivBase58Chain, "spending-wallet-from-bip44-serialization.txt");
//Simulate Wallet.fromMasterKey(params, coinLevelKey, 0)
DeterministicKey accountKey = HDKeyDerivation.deriveChildKey(coinLevelKey, new ChildNumber(0, true));
accountKey = accountKey.dropParent();
accountKey.setCreationTime(watchingKey.creationTime().get());
KeyChainGroup group = KeyChainGroup.builder(network).addChain(DeterministicKeyChain.builder().spend(accountKey)
.outputScriptType(bip44chain.getOutputScriptType()).build()).build();
DeterministicKeyChain fromMasterKeyChain = group.getActiveKeyChain();
assertEquals(BIP44_COIN_1_ACCOUNT_ZERO_PATH, fromMasterKeyChain.getAccountPath());
assertEquals(secs, fromMasterKeyChain.earliestKeyCreationTime());
fromMasterKeyChain.setLookaheadSize(10);
fromMasterKeyChain.maybeLookAhead();
verifySpendableKeyChain(firstReceiveKey, secondReceiveKey, firstChangeKey, secondChangeKey, fromMasterKeyChain, "spending-wallet-from-bip44-serialization-two.txt");
}
/**
* verifySpendableKeyChain
*
* firstReceiveKey and secondReceiveKey are the first two keys of the external chain of a known key chain
* firstChangeKey and secondChangeKey are the first two keys of the internal chain of a known key chain
* keyChain is a DeterministicKeyChain loaded from a serialized format or derived in some other way from
* the known key chain
*
* This method verifies that known keys match a newly created keyChain and that keyChain's protobuf
* matches the serializationFile.
*/
private void verifySpendableKeyChain(DeterministicKey firstReceiveKey, DeterministicKey secondReceiveKey,
DeterministicKey firstChangeKey, DeterministicKey secondChangeKey,
DeterministicKeyChain keyChain, String serializationFile) throws UnreadableWalletException {
//verify that the keys are the same as the keyChain
assertEquals(firstReceiveKey.getPubKeyPoint(), keyChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
assertEquals(secondReceiveKey.getPubKeyPoint(), keyChain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
final DeterministicKey key = keyChain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(firstChangeKey.getPubKeyPoint(), key.getPubKeyPoint());
try {
key.sign(Sha256Hash.ZERO_HASH);
} catch (ECKey.MissingPrivateKeyException e) {
// We can sign with a key from a spending chain.
fail();
}
// Test we can serialize and deserialize the chain OK
List<Protos.Key> serialization = keyChain.serializeToProtobuf();
checkSerialization(serialization, serializationFile);
// Check that the second change key matches after loading from the serialization, serializing and deserializing
Instant secs = keyChain.earliestKeyCreationTime();
keyChain = DeterministicKeyChain.fromProtobuf(serialization, null).get(0);
serialization = keyChain.serializeToProtobuf();
checkSerialization(serialization, serializationFile);
assertEquals(secs, keyChain.earliestKeyCreationTime());
final DeterministicKey nextChangeKey = keyChain.getKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(secondChangeKey.getPubKeyPoint(), nextChangeKey.getPubKeyPoint());
}
@Test(expected = IllegalStateException.class)
public void watchingCannotEncrypt() {
final DeterministicKey accountKey = chain.getKeyByPath(DeterministicKeyChain.ACCOUNT_ZERO_PATH);
chain = DeterministicKeyChain.builder().watch(accountKey.dropPrivateBytes().dropParent())
.outputScriptType(chain.getOutputScriptType()).build();
assertEquals(DeterministicKeyChain.ACCOUNT_ZERO_PATH, chain.getAccountPath());
chain = chain.toEncrypted("this doesn't make any sense");
}
@Test
public void bloom1() {
DeterministicKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
DeterministicKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
int numEntries =
(((chain.getLookaheadSize() + chain.getLookaheadThreshold()) * 2) // * 2 because of internal/external
+ chain.numLeafKeysIssued()
+ 4 // one root key + one account key + two chain keys (internal/external)
) * 2; // because the filter contains keys and key hashes.
assertEquals(numEntries, chain.numBloomFilterEntries());
BloomFilter filter = chain.getFilter(numEntries, 0.001, 1);
assertTrue(filter.contains(key1.getPubKey()));
assertTrue(filter.contains(key1.getPubKeyHash()));
assertTrue(filter.contains(key2.getPubKey()));
assertTrue(filter.contains(key2.getPubKeyHash()));
// The lookahead zone is tested in bloom2 and via KeyChainGroupTest.bloom
}
@Test
public void bloom2() {
// Verify that if when we watch a key, the filter contains at least 100 keys.
DeterministicKey[] keys = new DeterministicKey[100];
for (int i = 0; i < keys.length; i++)
keys[i] = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
chain = DeterministicKeyChain.builder().watch(chain.getWatchingKey().dropPrivateBytes().dropParent())
.outputScriptType(chain.getOutputScriptType()).build();
int e = chain.numBloomFilterEntries();
BloomFilter filter = chain.getFilter(e, 0.001, 1);
for (DeterministicKey key : keys)
assertTrue("key " + key, filter.contains(key.getPubKeyHash()));
}
private String protoToString(List<Protos.Key> keys) {
StringBuilder sb = new StringBuilder();
for (Protos.Key key : keys) {
String keyString = serializeKey(key);
sb.append(keyString);
}
return sb.toString().trim();
}
private String serializeKey(Protos.Key key) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new StringReader(key.toString()));
String line;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("#"))
sb.append(line).append('\n');
}
sb.append('\n');
reader.close();
} catch (IOException e) {
throw new RuntimeException(e); // cannot happen
}
return sb.toString();
}
private String checkSerialization(List<Protos.Key> keys, String filename) {
String sb = protoToString(keys);
String expected = readResourceFile(filename);
assertEquals(expected, sb);
return expected;
}
private String readResourceFile(String filename) {
try {
Path path = Paths.get(getClass().getResource(filename).toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
return String.join("\n", lines);
} catch (IOException | URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
| 42,169
| 51.778473
| 172
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/wallet/WalletTest.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.wallet;
import com.google.common.collect.Lists;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.crypto.AesKey;
import org.bitcoinj.base.internal.ByteUtils;
import org.bitcoinj.core.AbstractBlockChain;
import org.bitcoinj.base.Address;
import org.bitcoinj.core.Block;
import org.bitcoinj.core.BlockChain;
import org.bitcoinj.base.Coin;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.core.InsufficientMoneyException;
import org.bitcoinj.base.LegacyAddress;
import org.bitcoinj.core.PeerAddress;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.core.StoredBlock;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence;
import org.bitcoinj.core.TransactionConfidence.ConfidenceType;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutPoint;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.core.TransactionWitness;
import org.bitcoinj.core.VerificationException;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.HDPath;
import org.bitcoinj.crypto.KeyCrypter;
import org.bitcoinj.crypto.KeyCrypterException;
import org.bitcoinj.crypto.KeyCrypterScrypt;
import org.bitcoinj.crypto.MnemonicCode;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.crypto.TransactionSignature;
import org.bitcoinj.crypto.internal.CryptoUtils;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.ScriptBuilder;
import org.bitcoinj.script.ScriptChunk;
import org.bitcoinj.script.ScriptPattern;
import org.bitcoinj.signers.TransactionSigner;
import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.store.MemoryBlockStore;
import org.bitcoinj.testing.FakeTxBuilder;
import org.bitcoinj.testing.KeyChainTransactionSigner;
import org.bitcoinj.testing.MockTransactionBroadcaster;
import org.bitcoinj.testing.NopTransactionSigner;
import org.bitcoinj.testing.TestWithWallet;
import org.bitcoinj.utils.ExchangeRate;
import org.bitcoinj.base.utils.Fiat;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.wallet.KeyChain.KeyPurpose;
import org.bitcoinj.wallet.Protos.Wallet.EncryptionType;
import org.bitcoinj.wallet.Wallet.BalanceType;
import org.bitcoinj.wallet.WalletTransaction.Pool;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.math.BigInteger;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.bitcoinj.base.Coin.CENT;
import static org.bitcoinj.base.Coin.COIN;
import static org.bitcoinj.base.Coin.MILLICOIN;
import static org.bitcoinj.base.Coin.SATOSHI;
import static org.bitcoinj.base.Coin.ZERO;
import static org.bitcoinj.base.Coin.valueOf;
import static org.bitcoinj.testing.FakeTxBuilder.createFakeBlock;
import static org.bitcoinj.testing.FakeTxBuilder.createFakeTx;
import static org.bitcoinj.testing.FakeTxBuilder.createFakeTxWithoutChangeAddress;
import static org.bitcoinj.testing.FakeTxBuilder.makeSolvedTestBlock;
import static org.bitcoinj.testing.FakeTxBuilder.roundTripTransaction;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.replay;
import static org.hamcrest.Matchers.closeTo;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(JUnitParamsRunner.class)
public class WalletTest extends TestWithWallet {
private static final Logger log = LoggerFactory.getLogger(WalletTest.class);
private static final int SCRYPT_ITERATIONS = 256;
private static final CharSequence PASSWORD1 = "my helicopter contains eels";
private static final CharSequence WRONG_PASSWORD = "nothing noone nobody nowhere";
private final Address OTHER_ADDRESS = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
private final Address OTHER_SEGWIT_ADDRESS = new ECKey().toAddress(ScriptType.P2WPKH, BitcoinNetwork.TESTNET);
@Before
@Override
public void setUp() throws Exception {
super.setUp();
}
@After
@Override
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void createBasic() {
Wallet wallet = Wallet.createBasic(BitcoinNetwork.TESTNET);
assertEquals(0, wallet.getKeyChainGroupSize());
wallet.importKey(new ECKey());
assertEquals(1, wallet.getKeyChainGroupSize());
}
@Test(expected = IllegalStateException.class)
public void createBasic_noDerivation() {
Wallet wallet = Wallet.createBasic(BitcoinNetwork.TESTNET);
wallet.currentReceiveAddress();
}
@Test
public void getSeedAsWords1() {
// Can't verify much here as the wallet is random each time. We could fix the RNG for the unit tests and solve.
assertEquals(12, wallet.getKeyChainSeed().getMnemonicCode().size());
}
@Test
public void checkSeed() throws MnemonicException {
wallet.getKeyChainSeed().check();
}
@Test
public void basicSpending() throws Exception {
basicSpendingCommon(wallet, myAddress, OTHER_ADDRESS, null);
}
@Test
public void basicSpendingToP2SH() throws Exception {
Address destination = LegacyAddress.fromScriptHash(BitcoinNetwork.TESTNET, ByteUtils.parseHex("4a22c3c4cbb31e4d03b15550636762bda0baf85a"));
basicSpendingCommon(wallet, myAddress, destination, null);
}
@Test
public void basicSpendingWithEncryptedWallet() throws Exception {
Wallet encryptedWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
encryptedWallet.encrypt(PASSWORD1);
Address myEncryptedAddress = encryptedWallet.freshReceiveKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
basicSpendingCommon(encryptedWallet, myEncryptedAddress, OTHER_ADDRESS, encryptedWallet);
}
@Test
public void encryptDecryptWalletWithArbitraryPathAndScriptType() throws Exception {
final byte[] ENTROPY = Sha256Hash.hash("don't use a string seed like this in real life".getBytes());
KeyChainGroup keyChainGroup = KeyChainGroup.builder(BitcoinNetwork.TESTNET)
.addChain(DeterministicKeyChain.builder().seed(DeterministicSeed.ofEntropy(ENTROPY, "", Instant.ofEpochSecond(1389353062L)))
.outputScriptType(ScriptType.P2WPKH)
.accountPath(DeterministicKeyChain.BIP44_ACCOUNT_ZERO_PATH).build())
.build();
Wallet encryptedWallet = new Wallet(BitcoinNetwork.TESTNET, keyChainGroup);
encryptedWallet = roundTrip(encryptedWallet);
encryptedWallet.encrypt(PASSWORD1);
encryptedWallet = roundTrip(encryptedWallet);
encryptedWallet.decrypt(PASSWORD1);
encryptedWallet = roundTrip(encryptedWallet);
}
@Test
public void spendingWithIncompatibleSigners() throws Exception {
wallet.addTransactionSigner(new NopTransactionSigner(true));
basicSpendingCommon(wallet, myAddress, OTHER_ADDRESS, null);
}
static class TestRiskAnalysis implements RiskAnalysis {
private final boolean risky;
public TestRiskAnalysis(boolean risky) {
this.risky = risky;
}
@Override
public Result analyze() {
return risky ? Result.NON_FINAL : Result.OK;
}
public static class Analyzer implements RiskAnalysis.Analyzer {
private final Transaction riskyTx;
Analyzer(Transaction riskyTx) {
this.riskyTx = riskyTx;
}
@Override
public RiskAnalysis create(Wallet wallet, Transaction tx, List<Transaction> dependencies) {
return new TestRiskAnalysis(tx == riskyTx);
}
}
}
static class TestCoinSelector extends DefaultCoinSelector {
@Override
protected boolean shouldSelect(Transaction tx) {
return true;
}
}
private Transaction cleanupCommon(Address destination) throws Exception {
receiveATransaction(wallet, myAddress);
Coin v2 = valueOf(0, 50);
SendRequest req = SendRequest.to(destination, v2);
wallet.completeTx(req);
Transaction t2 = req.tx;
// Broadcast the transaction and commit.
broadcastAndCommit(wallet, t2);
// At this point we have one pending and one spent
Coin v1 = valueOf(0, 10);
Transaction t = sendMoneyToWallet(null, v1, myAddress);
Threading.waitForUserCode();
sendMoneyToWallet(null, t);
assertEquals("Wrong number of PENDING", 2, wallet.getPoolSize(Pool.PENDING));
assertEquals("Wrong number of UNSPENT", 0, wallet.getPoolSize(Pool.UNSPENT));
assertEquals("Wrong number of ALL", 3, wallet.getTransactions(true).size());
assertEquals(valueOf(0, 60), wallet.getBalance(Wallet.BalanceType.ESTIMATED));
// Now we have another incoming pending
return t;
}
@Test
public void cleanup() throws Exception {
Transaction t = cleanupCommon(OTHER_ADDRESS);
// Consider the new pending as risky and remove it from the wallet
wallet.setRiskAnalyzer(new TestRiskAnalysis.Analyzer(t));
wallet.cleanup();
assertTrue(wallet.isConsistent());
assertEquals("Wrong number of PENDING", 1, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
assertEquals("Wrong number of UNSPENT", 0, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals("Wrong number of ALL", 2, wallet.getTransactions(true).size());
assertEquals(valueOf(0, 50), wallet.getBalance(Wallet.BalanceType.ESTIMATED));
}
@Test
public void cleanupFailsDueToSpend() throws Exception {
Transaction t = cleanupCommon(OTHER_ADDRESS);
// Now we have another incoming pending. Spend everything.
Coin v3 = valueOf(0, 60);
SendRequest req = SendRequest.to(OTHER_ADDRESS, v3);
// Force selection of the incoming coin so that we can spend it
req.coinSelector = new TestCoinSelector();
wallet.completeTx(req);
wallet.commitTx(req.tx);
assertEquals("Wrong number of PENDING", 3, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
assertEquals("Wrong number of UNSPENT", 0, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals("Wrong number of ALL", 4, wallet.getTransactions(true).size());
// Consider the new pending as risky and try to remove it from the wallet
wallet.setRiskAnalyzer(new TestRiskAnalysis.Analyzer(t));
wallet.cleanup();
assertTrue(wallet.isConsistent());
// The removal should have failed
assertEquals("Wrong number of PENDING", 3, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
assertEquals("Wrong number of UNSPENT", 0, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals("Wrong number of ALL", 4, wallet.getTransactions(true).size());
assertEquals(ZERO, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
}
private void basicSpendingCommon(Wallet wallet, Address toAddress, Address destination, Wallet encryptedWallet) throws Exception {
// We'll set up a wallet that receives a coin, then sends a coin of lesser value and keeps the change. We
// will attach a small fee. Because the Bitcoin protocol makes it difficult to determine the fee of an
// arbitrary transaction in isolation, we'll check that the fee was set by examining the size of the change.
// Receive some money as a pending transaction.
receiveATransaction(wallet, toAddress);
// Try to send too much and fail.
Coin vHuge = valueOf(10, 0);
SendRequest req = SendRequest.to(destination, vHuge);
try {
wallet.completeTx(req);
fail();
} catch (InsufficientMoneyException e) {
assertEquals(valueOf(9, 0), e.missing);
}
// Prepare to send.
Coin v2 = valueOf(0, 50);
req = SendRequest.to(destination, v2);
if (encryptedWallet != null) {
KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter();
AesKey aesKey = keyCrypter.deriveKey(PASSWORD1);
AesKey wrongAesKey = keyCrypter.deriveKey(WRONG_PASSWORD);
// Try to create a send with a fee but no password (this should fail).
try {
wallet.completeTx(req);
fail();
} catch (ECKey.MissingPrivateKeyException kce) {
}
assertEquals("Wrong number of UNSPENT", 1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals("Wrong number of ALL", 1, wallet.getTransactions(true).size());
// Try to create a send with a fee but the wrong password (this should fail).
req = SendRequest.to(destination, v2);
req.aesKey = wrongAesKey;
try {
wallet.completeTx(req);
fail("No exception was thrown trying to sign an encrypted key with the wrong password supplied.");
} catch (Wallet.BadWalletEncryptionKeyException e) {
// Expected.
}
assertEquals("Wrong number of UNSPENT", 1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals("Wrong number of ALL", 1, wallet.getTransactions(true).size());
// Create a send with a fee with the correct password (this should succeed).
req = SendRequest.to(destination, v2);
req.aesKey = aesKey;
}
// Complete the transaction successfully.
req.shuffleOutputs = false;
wallet.completeTx(req);
Transaction t2 = req.tx;
assertEquals("Wrong number of UNSPENT", 1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals("Wrong number of ALL", 1, wallet.getTransactions(true).size());
assertEquals(TransactionConfidence.Source.SELF, t2.getConfidence().getSource());
assertEquals(Transaction.Purpose.USER_PAYMENT, t2.getPurpose());
// Do some basic sanity checks.
basicSanityChecks(wallet, t2, destination);
// Broadcast the transaction and commit.
List<TransactionOutput> unspents1 = wallet.getUnspents();
assertEquals(1, unspents1.size());
broadcastAndCommit(wallet, t2);
List<TransactionOutput> unspents2 = wallet.getUnspents();
assertNotSame(unspents1, unspents2);
// Now check that we can spend the unconfirmed change, with a new change address of our own selection.
// (req.aesKey is null for unencrypted / the correct aesKey for encrypted.)
wallet = spendUnconfirmedChange(wallet, t2, req.aesKey);
assertNotEquals(unspents2, wallet.getUnspents());
}
private void receiveATransaction(Wallet wallet, Address toAddress) throws Exception {
receiveATransactionAmount(wallet, toAddress, COIN);
}
private void receiveATransactionAmount(Wallet wallet, Address toAddress, Coin amount) {
final CompletableFuture<Coin> availFuture = wallet.getBalanceFuture(amount, Wallet.BalanceType.AVAILABLE);
final CompletableFuture<Coin> estimatedFuture = wallet.getBalanceFuture(amount, Wallet.BalanceType.ESTIMATED);
assertFalse(availFuture.isDone());
assertFalse(estimatedFuture.isDone());
// Send some pending coins to the wallet.
Transaction t1 = sendMoneyToWallet(wallet, null, amount, toAddress);
Threading.waitForUserCode();
final CompletableFuture<TransactionConfidence> depthFuture = t1.getConfidence().getDepthFuture(1);
assertFalse(depthFuture.isDone());
assertEquals(ZERO, wallet.getBalance(Wallet.BalanceType.AVAILABLE));
assertEquals(amount, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
assertFalse(availFuture.isDone());
// Our estimated balance has reached the requested level.
assertTrue(estimatedFuture.isDone());
assertEquals(1, wallet.getPoolSize(Pool.PENDING));
assertEquals(0, wallet.getPoolSize(Pool.UNSPENT));
// Confirm the coins.
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, t1);
assertEquals("Incorrect confirmed tx balance", amount, wallet.getBalance());
assertEquals("Incorrect confirmed tx PENDING pool size", 0, wallet.getPoolSize(Pool.PENDING));
assertEquals("Incorrect confirmed tx UNSPENT pool size", 1, wallet.getPoolSize(Pool.UNSPENT));
assertEquals("Incorrect confirmed tx ALL pool size", 1, wallet.getTransactions(true).size());
Threading.waitForUserCode();
assertTrue(availFuture.isDone());
assertTrue(estimatedFuture.isDone());
assertTrue(depthFuture.isDone());
}
private void basicSanityChecks(Wallet wallet, Transaction t, Address destination) throws VerificationException {
assertEquals("Wrong number of tx inputs", 1, t.getInputs().size());
assertEquals("Wrong number of tx outputs",2, t.getOutputs().size());
assertEquals(destination, t.getOutput(0).getScriptPubKey().getToAddress(BitcoinNetwork.TESTNET));
assertEquals(wallet.currentChangeAddress(), t.getOutput(1).getScriptPubKey().getToAddress(BitcoinNetwork.TESTNET));
assertEquals(valueOf(0, 50), t.getOutput(1).getValue());
// Check the script runs and signatures verify.
t.getInput(0).verify();
}
private static void broadcastAndCommit(Wallet wallet, Transaction t) throws Exception {
final LinkedList<Transaction> txns = new LinkedList<>();
wallet.addCoinsSentEventListener((wallet1, tx, prevBalance, newBalance) -> txns.add(tx));
t.getConfidence().markBroadcastBy(PeerAddress.simple(InetAddress.getByAddress(new byte[]{1,2,3,4}), TESTNET.getPort()));
t.getConfidence().markBroadcastBy(PeerAddress.simple(InetAddress.getByAddress(new byte[]{10,2,3,4}), TESTNET.getPort()));
wallet.commitTx(t);
Threading.waitForUserCode();
assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.SPENT));
assertEquals(2, wallet.getTransactions(true).size());
assertEquals(t, txns.getFirst());
assertEquals(1, txns.size());
}
private Wallet spendUnconfirmedChange(Wallet wallet, Transaction t2, AesKey aesKey) throws Exception {
if (wallet.getTransactionSigners().size() == 1) // don't bother reconfiguring the p2sh wallet
wallet = roundTrip(wallet);
Coin v3 = valueOf(0, 50);
assertEquals(v3, wallet.getBalance());
SendRequest req = SendRequest.to(OTHER_ADDRESS, valueOf(0, 48));
req.aesKey = aesKey;
req.shuffleOutputs = false;
wallet.completeTx(req);
Transaction t3 = req.tx;
assertNotEquals(t2.getOutput(1).getScriptPubKey().getToAddress(BitcoinNetwork.TESTNET),
t3.getOutput(1).getScriptPubKey().getToAddress(BitcoinNetwork.TESTNET));
assertNotNull(t3);
wallet.commitTx(t3);
assertTrue(wallet.isConsistent());
// t2 and t3 gets confirmed in the same block.
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, t2, t3);
assertTrue(wallet.isConsistent());
return wallet;
}
@Test
public void customTransactionSpending() throws Exception {
// We'll set up a wallet that receives a coin, then sends a coin of lesser value and keeps the change.
Coin v1 = valueOf(3, 0);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, v1);
assertEquals(v1, wallet.getBalance());
assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals(1, wallet.getTransactions(true).size());
Coin v2 = valueOf(0, 50);
Coin v3 = valueOf(0, 75);
Coin v4 = valueOf(1, 25);
Transaction t2 = new Transaction();
t2.addOutput(v2, OTHER_ADDRESS);
t2.addOutput(v3, OTHER_ADDRESS);
t2.addOutput(v4, OTHER_ADDRESS);
SendRequest req = SendRequest.forTx(t2);
wallet.completeTx(req);
// Do some basic sanity checks.
assertEquals(1, t2.getInputs().size());
List<ScriptChunk> scriptSigChunks = t2.getInput(0).getScriptSig().chunks();
// check 'from address' -- in a unit test this is fine
assertEquals(2, scriptSigChunks.size());
assertEquals(myAddress, LegacyAddress.fromPubKeyHash(BitcoinNetwork.TESTNET, CryptoUtils.sha256hash160(scriptSigChunks.get(1).data)));
assertEquals(TransactionConfidence.ConfidenceType.UNKNOWN, t2.getConfidence().getConfidenceType());
// We have NOT proven that the signature is correct!
wallet.commitTx(t2);
assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.SPENT));
assertEquals(2, wallet.getTransactions(true).size());
}
@Test
public void sideChain() {
// The wallet receives a coin on the best chain, then on a side chain. Balance is equal to both added together
// as we assume the side chain tx is pending and will be included shortly.
Coin v1 = COIN;
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, v1);
assertEquals(v1, wallet.getBalance());
assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals(1, wallet.getTransactions(true).size());
Coin v2 = valueOf(0, 50);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.SIDE_CHAIN, v2);
assertEquals(2, wallet.getTransactions(true).size());
assertEquals(v1, wallet.getBalance());
assertEquals(v1.add(v2), wallet.getBalance(Wallet.BalanceType.ESTIMATED));
}
@Test
public void balance() throws Exception {
// Receive 5 coins then half a coin.
Coin v1 = valueOf(5, 0);
Coin v2 = valueOf(0, 50);
Coin expected = valueOf(5, 50);
assertEquals(0, wallet.getTransactions(true).size());
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, v1);
assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, v2);
assertEquals(2, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals(expected, wallet.getBalance());
// Now spend one coin.
Coin v3 = COIN;
Transaction spend = wallet.createSend(OTHER_ADDRESS, v3);
wallet.commitTx(spend);
assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
// Available and estimated balances should not be the same. We don't check the exact available balance here
// because it depends on the coin selection algorithm.
assertEquals(valueOf(4, 50), wallet.getBalance(Wallet.BalanceType.ESTIMATED));
assertFalse(wallet.getBalance(Wallet.BalanceType.AVAILABLE).equals(
wallet.getBalance(Wallet.BalanceType.ESTIMATED)));
// Now confirm the transaction by including it into a block.
sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, spend);
// Change is confirmed. We started with 5.50 so we should have 4.50 left.
Coin v4 = valueOf(4, 50);
assertEquals(v4, wallet.getBalance(Wallet.BalanceType.AVAILABLE));
}
@Test
public void balanceWithIdenticalOutputs() {
assertEquals(Coin.ZERO, wallet.getBalance(BalanceType.ESTIMATED));
Transaction tx = new Transaction();
tx.addOutput(Coin.COIN, myAddress);
tx.addOutput(Coin.COIN, myAddress); // identical to the above
wallet.addWalletTransaction(new WalletTransaction(Pool.UNSPENT, tx));
assertEquals(Coin.COIN.plus(Coin.COIN), wallet.getBalance(BalanceType.ESTIMATED));
}
// Intuitively you'd expect to be able to create a transaction with identical inputs and outputs and get an
// identical result to Bitcoin Core. However the signatures are not deterministic - signing the same data
// with the same key twice gives two different outputs. So we cannot prove bit-for-bit compatibility in this test
// suite.
@Test
public void blockChainCatchup() throws Exception {
// Test that we correctly process transactions arriving from the chain, with callbacks for inbound and outbound.
final Coin[] bigints = new Coin[4];
final Transaction[] txn = new Transaction[2];
final LinkedList<Transaction> confTxns = new LinkedList<>();
wallet.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> {
bigints[0] = prevBalance;
bigints[1] = newBalance;
txn[0] = tx;
});
wallet.addCoinsSentEventListener((wallet, tx, prevBalance, newBalance) -> {
bigints[2] = prevBalance;
bigints[3] = newBalance;
txn[1] = tx;
});
wallet.addTransactionConfidenceEventListener((wallet, tx) -> confTxns.add(tx));
// Receive some money.
Coin oneCoin = COIN;
Transaction tx1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, oneCoin);
Threading.waitForUserCode();
assertEquals(null, txn[1]); // onCoinsSent not called.
assertEquals(tx1, confTxns.getFirst()); // onTransactionConfidenceChanged called
assertEquals(txn[0].getTxId(), tx1.getTxId());
assertEquals(ZERO, bigints[0]);
assertEquals(oneCoin, bigints[1]);
assertEquals(TransactionConfidence.ConfidenceType.BUILDING, tx1.getConfidence().getConfidenceType());
assertEquals(1, tx1.getConfidence().getAppearedAtChainHeight());
// Send 0.10 to somebody else.
Transaction send1 = wallet.createSend(OTHER_ADDRESS, valueOf(0, 10));
// Pretend it makes it into the block chain, our wallet state is cleared but we still have the keys, and we
// want to get back to our previous state. We can do this by just not confirming the transaction as
// createSend is stateless.
txn[0] = txn[1] = null;
confTxns.clear();
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send1);
Threading.waitForUserCode();
assertEquals(Coin.valueOf(0, 90), wallet.getBalance());
assertEquals(null, txn[0]);
assertEquals(2, confTxns.size());
assertEquals(txn[1].getTxId(), send1.getTxId());
assertEquals(Coin.COIN, bigints[2]);
assertEquals(Coin.valueOf(0, 90), bigints[3]);
// And we do it again after the catchup.
Transaction send2 = wallet.createSend(OTHER_ADDRESS, valueOf(0, 10));
// What we'd really like to do is prove Bitcoin Core would accept it .... no such luck unfortunately.
wallet.commitTx(send2);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send2);
assertEquals(Coin.valueOf(0, 80), wallet.getBalance());
Threading.waitForUserCode();
FakeTxBuilder.BlockPair b4 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS);
confTxns.clear();
wallet.notifyNewBestBlock(b4.storedBlock);
Threading.waitForUserCode();
assertEquals(3, confTxns.size());
}
@Test
public void balances() throws Exception {
Coin nanos = COIN;
Transaction tx1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, nanos);
assertEquals(nanos, tx1.getValueSentToMe(wallet));
assertTrue(tx1.getWalletOutputs(wallet).size() >= 1);
// Send 0.10 to somebody else.
Transaction send1 = wallet.createSend(OTHER_ADDRESS, valueOf(0, 10));
// Reserialize.
Transaction send2 = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(send1.serialize()));
assertEquals(nanos, send2.getValueSentFromMe(wallet));
assertEquals(ZERO.subtract(valueOf(0, 10)), send2.getValue(wallet));
}
@Test
public void isConsistent_duplicates() {
// This test ensures that isConsistent catches duplicate transactions, eg, because we submitted the same block
// twice (this is not allowed).
Transaction tx = createFakeTx(TESTNET.network(), COIN, myAddress);
TransactionOutput output = new TransactionOutput(tx, valueOf(0, 5), OTHER_ADDRESS);
tx.addOutput(output);
wallet.receiveFromBlock(tx, null, BlockChain.NewBlockType.BEST_CHAIN, 0);
assertTrue(wallet.isConsistent());
Transaction txClone = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(tx.serialize()));
try {
wallet.receiveFromBlock(txClone, null, BlockChain.NewBlockType.BEST_CHAIN, 0);
fail("Illegal argument not thrown when it should have been.");
} catch (IllegalStateException ex) {
// expected
}
}
@Test
public void isConsistent_pools() {
// This test ensures that isConsistent catches transactions that are in incompatible pools.
Transaction tx = createFakeTx(TESTNET.network(), COIN, myAddress);
TransactionOutput output = new TransactionOutput(tx, valueOf(0, 5), OTHER_ADDRESS);
tx.addOutput(output);
wallet.receiveFromBlock(tx, null, BlockChain.NewBlockType.BEST_CHAIN, 0);
assertTrue(wallet.isConsistent());
wallet.addWalletTransaction(new WalletTransaction(Pool.PENDING, tx));
assertFalse(wallet.isConsistent());
}
@Test
public void isConsistent_spent() {
// This test ensures that isConsistent catches transactions that are marked spent when
// they aren't.
Transaction tx = createFakeTx(TESTNET.network(), COIN, myAddress);
TransactionOutput output = new TransactionOutput(tx, valueOf(0, 5), OTHER_ADDRESS);
tx.addOutput(output);
assertTrue(wallet.isConsistent());
wallet.addWalletTransaction(new WalletTransaction(Pool.SPENT, tx));
assertFalse(wallet.isConsistent());
}
@Test
public void isTxConsistentReturnsFalseAsExpected() {
Wallet wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
TransactionOutput to = createMock(TransactionOutput.class);
EasyMock.expect(to.isAvailableForSpending()).andReturn(true);
EasyMock.expect(to.isMineOrWatched(wallet)).andReturn(true);
EasyMock.expect(to.getSpentBy()).andReturn(
new TransactionInput(null, new byte[0], TransactionOutPoint.UNCONNECTED));
Transaction tx = FakeTxBuilder.createFakeTxWithoutChange(to);
replay(to);
boolean isConsistent = wallet.isTxConsistent(tx, false);
assertFalse(isConsistent);
}
@Test
public void isTxConsistentReturnsFalseAsExpected_WhenAvailableForSpendingEqualsFalse() {
Wallet wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
TransactionOutput to = createMock(TransactionOutput.class);
EasyMock.expect(to.isAvailableForSpending()).andReturn(false);
EasyMock.expect(to.getSpentBy()).andReturn(null);
Transaction tx = FakeTxBuilder.createFakeTxWithoutChange(to);
replay(to);
boolean isConsistent = wallet.isTxConsistent(tx, false);
assertFalse(isConsistent);
}
@Test
public void transactions() {
// This test covers a bug in which Transaction.getValueSentFromMe was calculating incorrectly.
Transaction tx = createFakeTx(TESTNET.network(), COIN, myAddress);
// Now add another output (ie, change) that goes to some other address.
TransactionOutput output = new TransactionOutput(tx, valueOf(0, 5), OTHER_ADDRESS);
tx.addOutput(output);
// Note that tx is no longer valid: it spends more than it imports. However checking transactions balance
// correctly isn't possible in SPV mode because value is a property of outputs not inputs. Without all
// transactions you can't check they add up.
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx);
// Now the other guy creates a transaction which spends that change.
Transaction tx2 = new Transaction();
tx2.addInput(output);
tx2.addOutput(new TransactionOutput(tx2, valueOf(0, 5), myAddress));
// tx2 doesn't send any coins from us, even though the output is in the wallet.
assertEquals(ZERO, tx2.getValueSentFromMe(wallet));
}
@Test
public void bounce() throws Exception {
// This test covers bug 64 (False double spends). Check that if we create a spend and it's immediately sent
// back to us, this isn't considered as a double spend.
Coin coin1 = COIN;
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, coin1);
// Send half to some other guy. Sending only half then waiting for a confirm is important to ensure the tx is
// in the unspent pool, not pending or spent.
Coin coinHalf = valueOf(0, 50);
assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals(1, wallet.getTransactions(true).size());
SendRequest req = SendRequest.to(OTHER_ADDRESS, coinHalf);
req.shuffleOutputs = false;
wallet.completeTx(req);
Transaction outbound1 = req.tx;
wallet.commitTx(outbound1);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, outbound1);
assertTrue(outbound1.getWalletOutputs(wallet).size() <= 1); //the change address at most
// That other guy gives us the coins right back.
Transaction inbound2 = new Transaction();
inbound2.addOutput(new TransactionOutput(inbound2, coinHalf, myAddress));
assertTrue(outbound1.getWalletOutputs(wallet).size() >= 1);
inbound2.addInput(outbound1.getOutput(0));
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, inbound2);
assertEquals(coin1, wallet.getBalance());
}
@Test
public void doubleSpendUnspendsOtherInputs() throws Exception {
// Test another Finney attack, but this time the killed transaction was also spending some other outputs in
// our wallet which were not themselves double spent. This test ensures the death of the pending transaction
// frees up the other outputs and makes them spendable again.
// Receive 1 coin and then 2 coins in separate transactions.
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
// Create a send to a merchant of all our coins.
Transaction send1 = wallet.createSend(OTHER_ADDRESS, valueOf(2, 90));
// Create a double spend of just the first one.
Address BAD_GUY = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
Transaction send2 = wallet.createSend(BAD_GUY, COIN);
send2 = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(send2.serialize()));
// Broadcast send1, it's now pending.
wallet.commitTx(send1);
assertEquals(ZERO, wallet.getBalance()); // change of 10 cents is not yet mined so not included in the balance.
// Receive a block that overrides the send1 using send2.
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send2);
// send1 got rolled back and replaced with a smaller send that only used one of our received coins, thus ...
assertEquals(valueOf(2, 0), wallet.getBalance());
assertTrue(wallet.isConsistent());
}
@Test
public void doubleSpends() throws Exception {
// Test the case where two semantically identical but bitwise different transactions double spend each other.
// We call the second transaction a "mutant" of the first.
//
// This can (and has!) happened when a wallet is cloned between devices, and both devices decide to make the
// same spend simultaneously - for example due a re-keying operation. It can also happen if there are malicious
// nodes in the P2P network that are mutating transactions on the fly as occurred during Feb 2014.
final Coin value = COIN;
final Coin value2 = valueOf(2, 0);
// Give us three coins and make sure we have some change.
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, value.add(value2));
Transaction send1 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, value2));
Transaction send2 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, value2));
byte[] buf = send1.serialize();
buf[43] = 0; // Break the signature: bitcoinj won't check in SPV mode and this is easier than other mutations.
send1 = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(buf));
wallet.commitTx(send2);
assertEquals(value, wallet.getBalance(BalanceType.ESTIMATED));
// Now spend the change. This transaction should die permanently when the mutant appears in the chain.
Transaction send3 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, value, true));
wallet.commitTx(send3);
assertEquals(ZERO, wallet.getBalance(BalanceType.AVAILABLE));
final LinkedList<TransactionConfidence> dead = new LinkedList<>();
final TransactionConfidence.Listener listener = (confidence, reason) -> {
final ConfidenceType type = confidence.getConfidenceType();
if (reason == TransactionConfidence.Listener.ChangeReason.TYPE && type == ConfidenceType.DEAD)
dead.add(confidence);
};
send2.getConfidence().addEventListener(Threading.SAME_THREAD, listener);
send3.getConfidence().addEventListener(Threading.SAME_THREAD, listener);
// Double spend!
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send1);
// Back to having one coin.
assertEquals(value, wallet.getBalance(BalanceType.AVAILABLE));
assertEquals(send2.getTxId(), dead.poll().getTransactionHash());
assertEquals(send3.getTxId(), dead.poll().getTransactionHash());
}
@Test
public void doubleSpendFinneyAttack() throws Exception {
// A Finney attack is where a miner includes a transaction spending coins to themselves but does not
// broadcast it. When they find a solved block, they hold it back temporarily whilst they buy something with
// those same coins. After purchasing, they broadcast the block thus reversing the transaction. It can be
// done by any miner for products that can be bought at a chosen time and very quickly (as every second you
// withold your block means somebody else might find it first, invalidating your work).
//
// Test that we handle the attack correctly: a double spend on the chain moves transactions from pending to dead.
// This needs to work both for transactions we create, and that we receive from others.
final Transaction[] eventDead = new Transaction[1];
final Transaction[] eventReplacement = new Transaction[1];
final int[] eventWalletChanged = new int[1];
wallet.addTransactionConfidenceEventListener((wallet, tx) -> {
if (tx.getConfidence().getConfidenceType() ==
ConfidenceType.DEAD) {
eventDead[0] = tx;
eventReplacement[0] = tx.getConfidence().getOverridingTransaction();
}
});
wallet.addChangeEventListener(wallet -> eventWalletChanged[0]++);
// Receive 1 BTC.
Coin nanos = COIN;
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, nanos);
Transaction received = wallet.getTransactions(false).iterator().next();
// Create a send to a merchant.
Transaction send1 = wallet.createSend(OTHER_ADDRESS, valueOf(0, 50));
// Create a double spend.
Address BAD_GUY = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
Transaction send2 = wallet.createSend(BAD_GUY, valueOf(0, 50));
send2 = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(send2.serialize()));
// Broadcast send1.
wallet.commitTx(send1);
assertEquals(send1, received.getOutput(0).getSpentBy().getParentTransaction());
// Receive a block that overrides it.
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send2);
Threading.waitForUserCode();
assertEquals(send1, eventDead[0]);
assertEquals(send2, eventReplacement[0]);
assertEquals(TransactionConfidence.ConfidenceType.DEAD,
send1.getConfidence().getConfidenceType());
assertEquals(send2, received.getOutput(0).getSpentBy().getParentTransaction());
FakeTxBuilder.DoubleSpends doubleSpends = FakeTxBuilder.createFakeDoubleSpendTxns(myAddress);
// t1 spends to our wallet. t2 double spends somewhere else.
wallet.receivePending(doubleSpends.t1, null);
assertEquals(TransactionConfidence.ConfidenceType.PENDING,
doubleSpends.t1.getConfidence().getConfidenceType());
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, doubleSpends.t2);
Threading.waitForUserCode();
assertEquals(TransactionConfidence.ConfidenceType.DEAD,
doubleSpends.t1.getConfidence().getConfidenceType());
assertEquals(doubleSpends.t2, doubleSpends.t1.getConfidence().getOverridingTransaction());
assertEquals(5, eventWalletChanged[0]);
}
@Test
public void doubleSpendWeCreate() throws Exception {
// Test we keep pending double spends in IN_CONFLICT until one of them is included in a block
// and we handle reorgs and dependency chains properly.
// The following graph shows the txns we use in this test and how they are related
// (Eg txA1 spends txARoot outputs, txC1 spends txA1 and txB1 outputs, etc).
// txARoot (10) -> txA1 (1) -+
// |--> txC1 (0.10) -> txD1 (0.01)
// txBRoot (100) -> txB1 (11) -+
//
// txARoot (10) -> txA2 (2) -+
// |--> txC2 (0.20) -> txD2 (0.02)
// txBRoot (100) -> txB2 (22) -+
//
// txARoot (10) -> txA3 (3)
//
// txA1 is in conflict with txA2 and txA3. txB1 is in conflict with txB2.
Transaction txARoot = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(10, 0));
SendRequest a1Req = SendRequest.to(OTHER_ADDRESS, valueOf(1, 0));
a1Req.tx.addInput(txARoot.getOutput(0));
a1Req.shuffleOutputs = false;
wallet.completeTx(a1Req);
Transaction txA1 = a1Req.tx;
SendRequest a2Req = SendRequest.to(OTHER_ADDRESS, valueOf(2, 0));
a2Req.tx.addInput(txARoot.getOutput(0));
a2Req.shuffleOutputs = false;
wallet.completeTx(a2Req);
Transaction txA2 = a2Req.tx;
SendRequest a3Req = SendRequest.to(OTHER_ADDRESS, valueOf(3, 0));
a3Req.tx.addInput(txARoot.getOutput(0));
a3Req.shuffleOutputs = false;
wallet.completeTx(a3Req);
Transaction txA3 = a3Req.tx;
wallet.commitTx(txA1);
wallet.commitTx(txA2);
wallet.commitTx(txA3);
Transaction txBRoot = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(100, 0));
SendRequest b1Req = SendRequest.to(OTHER_ADDRESS, valueOf(11, 0));
b1Req.tx.addInput(txBRoot.getOutput(0));
b1Req.shuffleOutputs = false;
wallet.completeTx(b1Req);
Transaction txB1 = b1Req.tx;
SendRequest b2Req = SendRequest.to(OTHER_ADDRESS, valueOf(22, 0));
b2Req.tx.addInput(txBRoot.getOutput(0));
b2Req.shuffleOutputs = false;
wallet.completeTx(b2Req);
Transaction txB2 = b2Req.tx;
wallet.commitTx(txB1);
wallet.commitTx(txB2);
SendRequest c1Req = SendRequest.to(OTHER_ADDRESS, valueOf(0, 10));
c1Req.tx.addInput(txA1.getOutput(1));
c1Req.tx.addInput(txB1.getOutput(1));
c1Req.shuffleOutputs = false;
wallet.completeTx(c1Req);
Transaction txC1 = c1Req.tx;
SendRequest c2Req = SendRequest.to(OTHER_ADDRESS, valueOf(0, 20));
c2Req.tx.addInput(txA2.getOutput(1));
c2Req.tx.addInput(txB2.getOutput(1));
c2Req.shuffleOutputs = false;
wallet.completeTx(c2Req);
Transaction txC2 = c2Req.tx;
wallet.commitTx(txC1);
wallet.commitTx(txC2);
SendRequest d1Req = SendRequest.to(OTHER_ADDRESS, valueOf(0, 1));
d1Req.tx.addInput(txC1.getOutput(1));
d1Req.shuffleOutputs = false;
wallet.completeTx(d1Req);
Transaction txD1 = d1Req.tx;
SendRequest d2Req = SendRequest.to(OTHER_ADDRESS, valueOf(0, 2));
d2Req.tx.addInput(txC2.getOutput(1));
d2Req.shuffleOutputs = false;
wallet.completeTx(d2Req);
Transaction txD2 = d2Req.tx;
wallet.commitTx(txD1);
wallet.commitTx(txD2);
assertInConflict(txA1);
assertInConflict(txA2);
assertInConflict(txA3);
assertInConflict(txB1);
assertInConflict(txB2);
assertInConflict(txC1);
assertInConflict(txC2);
assertInConflict(txD1);
assertInConflict(txD2);
// Add a block to the block store. The rest of the blocks in this test will be on top of this one.
FakeTxBuilder.BlockPair blockPair0 = createFakeBlock(blockStore, 1);
// A block was mined including txA1
FakeTxBuilder.BlockPair blockPair1 = createFakeBlock(blockStore, 2, txA1);
wallet.receiveFromBlock(txA1, blockPair1.storedBlock, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
wallet.notifyNewBestBlock(blockPair1.storedBlock);
assertSpent(txA1);
assertDead(txA2);
assertDead(txA3);
assertInConflict(txB1);
assertInConflict(txB2);
assertInConflict(txC1);
assertDead(txC2);
assertInConflict(txD1);
assertDead(txD2);
// A reorg: previous block "replaced" by new block containing txA1 and txB1
FakeTxBuilder.BlockPair blockPair2 = createFakeBlock(blockStore, blockPair0.storedBlock, 2, txA1, txB1);
wallet.receiveFromBlock(txA1, blockPair2.storedBlock, AbstractBlockChain.NewBlockType.SIDE_CHAIN, 0);
wallet.receiveFromBlock(txB1, blockPair2.storedBlock, AbstractBlockChain.NewBlockType.SIDE_CHAIN, 1);
wallet.reorganize(blockPair0.storedBlock, Lists.newArrayList(blockPair1.storedBlock),
Lists.newArrayList(blockPair2.storedBlock));
assertSpent(txA1);
assertDead(txA2);
assertDead(txA3);
assertSpent(txB1);
assertDead(txB2);
assertPending(txC1);
assertDead(txC2);
assertPending(txD1);
assertDead(txD2);
// A reorg: previous block "replaced" by new block containing txA1, txB1 and txC1
FakeTxBuilder.BlockPair blockPair3 = createFakeBlock(blockStore, blockPair0.storedBlock, 2, txA1, txB1, txC1);
wallet.receiveFromBlock(txA1, blockPair3.storedBlock, AbstractBlockChain.NewBlockType.SIDE_CHAIN, 0);
wallet.receiveFromBlock(txB1, blockPair3.storedBlock, AbstractBlockChain.NewBlockType.SIDE_CHAIN, 1);
wallet.receiveFromBlock(txC1, blockPair3.storedBlock, AbstractBlockChain.NewBlockType.SIDE_CHAIN, 2);
wallet.reorganize(blockPair0.storedBlock, Lists.newArrayList(blockPair2.storedBlock),
Lists.newArrayList(blockPair3.storedBlock));
assertSpent(txA1);
assertDead(txA2);
assertDead(txA3);
assertSpent(txB1);
assertDead(txB2);
assertSpent(txC1);
assertDead(txC2);
assertPending(txD1);
assertDead(txD2);
// A reorg: previous block "replaced" by new block containing txB1
FakeTxBuilder.BlockPair blockPair4 = createFakeBlock(blockStore, blockPair0.storedBlock, 2, txB1);
wallet.receiveFromBlock(txB1, blockPair4.storedBlock, AbstractBlockChain.NewBlockType.SIDE_CHAIN, 0);
wallet.reorganize(blockPair0.storedBlock, Lists.newArrayList(blockPair3.storedBlock),
Lists.newArrayList(blockPair4.storedBlock));
assertPending(txA1);
assertDead(txA2);
assertDead(txA3);
assertSpent(txB1);
assertDead(txB2);
assertPending(txC1);
assertDead(txC2);
assertPending(txD1);
assertDead(txD2);
// A reorg: previous block "replaced" by new block containing txA2
FakeTxBuilder.BlockPair blockPair5 = createFakeBlock(blockStore, blockPair0.storedBlock, 2, txA2);
wallet.receiveFromBlock(txA2, blockPair5.storedBlock, AbstractBlockChain.NewBlockType.SIDE_CHAIN, 0);
wallet.reorganize(blockPair0.storedBlock, Lists.newArrayList(blockPair4.storedBlock),
Lists.newArrayList(blockPair5.storedBlock));
assertDead(txA1);
assertUnspent(txA2);
assertDead(txA3);
assertPending(txB1);
assertDead(txB2);
assertDead(txC1);
assertDead(txC2);
assertDead(txD1);
assertDead(txD2);
// A reorg: previous block "replaced" by new empty block
FakeTxBuilder.BlockPair blockPair6 = createFakeBlock(blockStore, blockPair0.storedBlock, 2);
wallet.reorganize(blockPair0.storedBlock, Lists.newArrayList(blockPair5.storedBlock),
Lists.newArrayList(blockPair6.storedBlock));
assertDead(txA1);
assertPending(txA2);
assertDead(txA3);
assertPending(txB1);
assertDead(txB2);
assertDead(txC1);
assertDead(txC2);
assertDead(txD1);
assertDead(txD2);
}
@Test
public void doubleSpendWeReceive() {
FakeTxBuilder.DoubleSpends doubleSpends = FakeTxBuilder.createFakeDoubleSpendTxns(myAddress);
// doubleSpends.t1 spends to our wallet. doubleSpends.t2 double spends somewhere else.
Transaction t1b = new Transaction();
TransactionOutput t1bo = new TransactionOutput(t1b, valueOf(0, 50), OTHER_ADDRESS);
t1b.addOutput(t1bo);
t1b.addInput(doubleSpends.t1.getOutput(0));
wallet.receivePending(doubleSpends.t1, null);
wallet.receivePending(doubleSpends.t2, null);
wallet.receivePending(t1b, null);
assertInConflict(doubleSpends.t1);
assertInConflict(doubleSpends.t1);
assertInConflict(t1b);
// Add a block to the block store. The rest of the blocks in this test will be on top of this one.
FakeTxBuilder.BlockPair blockPair0 = createFakeBlock(blockStore, 1);
// A block was mined including doubleSpends.t1
FakeTxBuilder.BlockPair blockPair1 = createFakeBlock(blockStore, 2, doubleSpends.t1);
wallet.receiveFromBlock(doubleSpends.t1, blockPair1.storedBlock, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
wallet.notifyNewBestBlock(blockPair1.storedBlock);
assertSpent(doubleSpends.t1);
assertDead(doubleSpends.t2);
assertPending(t1b);
// A reorg: previous block "replaced" by new block containing doubleSpends.t2
FakeTxBuilder.BlockPair blockPair2 = createFakeBlock(blockStore, blockPair0.storedBlock, 2, doubleSpends.t2);
wallet.receiveFromBlock(doubleSpends.t2, blockPair2.storedBlock, AbstractBlockChain.NewBlockType.SIDE_CHAIN, 0);
wallet.reorganize(blockPair0.storedBlock, Lists.newArrayList(blockPair1.storedBlock),
Lists.newArrayList(blockPair2.storedBlock));
assertDead(doubleSpends.t1);
assertSpent(doubleSpends.t2);
assertDead(t1b);
}
@Test
public void doubleSpendForBuildingTx() throws Exception {
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
Transaction send1 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
Transaction send2 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send1);
assertUnspent(send1);
wallet.receivePending(send2, null);
assertUnspent(send1);
assertDead(send2);
}
@Test
public void txSpendingDeadTx() throws Exception {
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
Transaction send1 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
Transaction send2 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
wallet.commitTx(send1);
assertPending(send1);
Transaction send1b = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 50), true));
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, send2);
assertDead(send1);
assertUnspent(send2);
wallet.receivePending(send1b, null);
assertDead(send1);
assertUnspent(send2);
assertDead(send1b);
}
private void assertInConflict(Transaction tx) {
assertEquals(ConfidenceType.IN_CONFLICT, tx.getConfidence().getConfidenceType());
assertTrue(wallet.poolContainsTxHash(WalletTransaction.Pool.PENDING, tx.getTxId()));
}
private void assertPending(Transaction tx) {
assertEquals(ConfidenceType.PENDING, tx.getConfidence().getConfidenceType());
assertTrue(wallet.poolContainsTxHash(WalletTransaction.Pool.PENDING, tx.getTxId()));
}
private void assertSpent(Transaction tx) {
assertEquals(ConfidenceType.BUILDING, tx.getConfidence().getConfidenceType());
assertTrue(wallet.poolContainsTxHash(WalletTransaction.Pool.SPENT, tx.getTxId()));
}
private void assertUnspent(Transaction tx) {
assertEquals(ConfidenceType.BUILDING, tx.getConfidence().getConfidenceType());
assertTrue(wallet.poolContainsTxHash(WalletTransaction.Pool.UNSPENT, tx.getTxId()));
}
private void assertDead(Transaction tx) {
assertEquals(ConfidenceType.DEAD, tx.getConfidence().getConfidenceType());
assertTrue(wallet.poolContainsTxHash(WalletTransaction.Pool.DEAD, tx.getTxId()));
}
@Test
public void testAddTransactionsDependingOn() throws Exception {
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
Transaction send1 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
Transaction send2 = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 20), true));
wallet.commitTx(send1);
Transaction send1b = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 50), true));
wallet.commitTx(send1b);
Transaction send1c = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 25), true));
wallet.commitTx(send1c);
wallet.commitTx(send2);
Set<Transaction> txns = new HashSet<>();
txns.add(send1);
wallet.addTransactionsDependingOn(txns, wallet.getTransactions(true));
assertEquals(3, txns.size());
assertTrue(txns.contains(send1));
assertTrue(txns.contains(send1b));
assertTrue(txns.contains(send1c));
}
@Test
public void sortTxnsByDependency() throws Exception {
Transaction send1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(2, 0));
Transaction send1a = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(1, 0), true));
wallet.commitTx(send1a);
Transaction send1b = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 50), true));
wallet.commitTx(send1b);
Transaction send1c = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 25), true));
wallet.commitTx(send1c);
Transaction send1d = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 12), true));
wallet.commitTx(send1d);
Transaction send1e = Objects.requireNonNull(wallet.createSend(OTHER_ADDRESS, valueOf(0, 06), true));
wallet.commitTx(send1e);
Transaction send2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(200, 0));
SendRequest req2a = SendRequest.to(OTHER_ADDRESS, valueOf(100, 0));
req2a.tx.addInput(send2.getOutput(0));
req2a.shuffleOutputs = false;
wallet.completeTx(req2a);
Transaction send2a = req2a.tx;
SendRequest req2b = SendRequest.to(OTHER_ADDRESS, valueOf(50, 0));
req2b.tx.addInput(send2a.getOutput(1));
req2b.shuffleOutputs = false;
wallet.completeTx(req2b);
Transaction send2b = req2b.tx;
SendRequest req2c = SendRequest.to(OTHER_ADDRESS, valueOf(25, 0));
req2c.tx.addInput(send2b.getOutput(1));
req2c.shuffleOutputs = false;
wallet.completeTx(req2c);
Transaction send2c = req2c.tx;
Set<Transaction> unsortedTxns = new HashSet<>();
unsortedTxns.add(send1a);
unsortedTxns.add(send1b);
unsortedTxns.add(send1c);
unsortedTxns.add(send1d);
unsortedTxns.add(send1e);
unsortedTxns.add(send2a);
unsortedTxns.add(send2b);
unsortedTxns.add(send2c);
List<Transaction> sortedTxns = wallet.sortTxnsByDependency(unsortedTxns);
assertEquals(8, sortedTxns.size());
assertTrue(sortedTxns.indexOf(send1a) < sortedTxns.indexOf(send1b));
assertTrue(sortedTxns.indexOf(send1b) < sortedTxns.indexOf(send1c));
assertTrue(sortedTxns.indexOf(send1c) < sortedTxns.indexOf(send1d));
assertTrue(sortedTxns.indexOf(send1d) < sortedTxns.indexOf(send1e));
assertTrue(sortedTxns.indexOf(send2a) < sortedTxns.indexOf(send2b));
assertTrue(sortedTxns.indexOf(send2b) < sortedTxns.indexOf(send2c));
}
@Test
public void pending1() {
// Check that if we receive a pending transaction that is then confirmed, we are notified as appropriate.
final Coin nanos = COIN;
final Transaction t1 = createFakeTx(TESTNET.network(), nanos, myAddress);
// First one is "called" second is "pending".
final boolean[] flags = new boolean[2];
final Transaction[] notifiedTx = new Transaction[1];
final int[] walletChanged = new int[1];
wallet.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> {
// Check we got the expected transaction.
assertEquals(tx, t1);
// Check that it's considered to be pending inclusion in the block chain.
assertEquals(prevBalance, ZERO);
assertEquals(newBalance, nanos);
flags[0] = true;
flags[1] = tx.isPending();
notifiedTx[0] = tx;
});
wallet.addChangeEventListener(wallet -> walletChanged[0]++);
if (wallet.isPendingTransactionRelevant(t1))
wallet.receivePending(t1, null);
Threading.waitForUserCode();
assertTrue(flags[0]);
assertTrue(flags[1]); // is pending
flags[0] = false;
// Check we don't get notified if we receive it again.
assertFalse(wallet.isPendingTransactionRelevant(t1));
assertFalse(flags[0]);
// Now check again, that we should NOT be notified when we receive it via a block (we were already notified).
// However the confidence should be updated.
// Make a fresh copy of the tx to ensure we're testing realistically.
flags[0] = flags[1] = false;
final TransactionConfidence.Listener.ChangeReason[] reasons = new TransactionConfidence.Listener.ChangeReason[1];
notifiedTx[0].getConfidence().addEventListener((confidence, reason) -> {
flags[1] = true;
reasons[0] = reason;
});
assertEquals(TransactionConfidence.ConfidenceType.PENDING,
notifiedTx[0].getConfidence().getConfidenceType());
// Send a block with nothing interesting. Verify we don't get a callback.
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN);
Threading.waitForUserCode();
assertNull(reasons[0]);
final Transaction t1Copy = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(t1.serialize()));
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, t1Copy);
Threading.waitForUserCode();
assertFalse(flags[0]);
assertTrue(flags[1]);
assertEquals(TransactionConfidence.ConfidenceType.BUILDING, notifiedTx[0].getConfidence().getConfidenceType());
// Check we don't get notified about an irrelevant transaction.
flags[0] = false;
flags[1] = false;
Transaction irrelevant = createFakeTx(TESTNET.network(), nanos, OTHER_ADDRESS);
if (wallet.isPendingTransactionRelevant(irrelevant))
wallet.receivePending(irrelevant, null);
Threading.waitForUserCode();
assertFalse(flags[0]);
assertEquals(3, walletChanged[0]);
}
@Test
public void pending2() throws Exception {
// Check that if we receive a pending tx we did not send, it updates our spent flags correctly.
final Transaction[] txn = new Transaction[1];
final Coin[] bigints = new Coin[2];
wallet.addCoinsSentEventListener((wallet, tx, prevBalance, newBalance) -> {
txn[0] = tx;
bigints[0] = prevBalance;
bigints[1] = newBalance;
});
// Receive some coins.
Coin nanos = COIN;
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, nanos);
// Create a spend with them, but don't commit it (ie it's from somewhere else but using our keys). This TX
// will have change as we don't spend our entire balance.
Coin halfNanos = valueOf(0, 50);
Transaction t2 = wallet.createSend(OTHER_ADDRESS, halfNanos);
// Now receive it as pending.
if (wallet.isPendingTransactionRelevant(t2))
wallet.receivePending(t2, null);
// We received an onCoinsSent() callback.
Threading.waitForUserCode();
assertEquals(t2, txn[0]);
assertEquals(nanos, bigints[0]);
assertEquals(halfNanos, bigints[1]);
// Our balance is now 0.50 BTC
assertEquals(halfNanos, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
}
@Test
public void pending3() {
// Check that if we receive a pending tx, and it's overridden by a double spend from the best chain, we
// are notified that it's dead. This should work even if the pending tx inputs are NOT ours, ie, they don't
// connect to anything.
Coin nanos = COIN;
// Create two transactions that share the same input tx.
Address badGuy = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
Transaction doubleSpentTx = new Transaction();
TransactionOutput doubleSpentOut = new TransactionOutput(doubleSpentTx, nanos, badGuy);
doubleSpentTx.addOutput(doubleSpentOut);
Transaction t1 = new Transaction();
TransactionOutput o1 = new TransactionOutput(t1, nanos, myAddress);
t1.addOutput(o1);
t1.addInput(doubleSpentOut);
Transaction t2 = new Transaction();
TransactionOutput o2 = new TransactionOutput(t2, nanos, badGuy);
t2.addOutput(o2);
t2.addInput(doubleSpentOut);
final Transaction[] called = new Transaction[2];
wallet.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> called[0] = tx);
wallet.addTransactionConfidenceEventListener((wallet, tx) -> {
if (tx.getConfidence().getConfidenceType() ==
ConfidenceType.DEAD) {
called[0] = tx;
called[1] = tx.getConfidence().getOverridingTransaction();
}
});
assertEquals(ZERO, wallet.getBalance());
if (wallet.isPendingTransactionRelevant(t1))
wallet.receivePending(t1, null);
Threading.waitForUserCode();
assertEquals(t1, called[0]);
assertEquals(nanos, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
// Now receive a double spend on the best chain.
called[0] = called[1] = null;
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, t2);
Threading.waitForUserCode();
assertEquals(ZERO, wallet.getBalance());
assertEquals(t1, called[0]); // dead
assertEquals(t2, called[1]); // replacement
}
@Test
public void transactionsList() throws Exception {
// Check the wallet can give us an ordered list of all received transactions.
TimeUtils.setMockClock();
Transaction tx1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
TimeUtils.rollMockClock(Duration.ofMinutes(10));
Transaction tx2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(0, 5));
// Check we got them back in order.
List<Transaction> transactions = wallet.getTransactionsByTime();
assertEquals(tx2, transactions.get(0));
assertEquals(tx1, transactions.get(1));
assertEquals(2, transactions.size());
// Check we get only the last transaction if we request a subrange.
transactions = wallet.getRecentTransactions(1, false);
assertEquals(1, transactions.size());
assertEquals(tx2, transactions.get(0));
// Create a spend five minutes later.
TimeUtils.rollMockClock(Duration.ofMinutes(5));
Transaction tx3 = wallet.createSend(OTHER_ADDRESS, valueOf(0, 5));
// Does not appear in list yet.
assertEquals(2, wallet.getTransactionsByTime().size());
wallet.commitTx(tx3);
// Now it does.
transactions = wallet.getTransactionsByTime();
assertEquals(3, transactions.size());
assertEquals(tx3, transactions.get(0));
// Verify we can handle the case of older wallets in which the timestamp is null (guessed from the
// block appearances list).
tx1.clearUpdateTime();
tx3.clearUpdateTime();
// Check we got them back in order.
transactions = wallet.getTransactionsByTime();
assertEquals(tx2, transactions.get(0));
assertEquals(3, transactions.size());
}
@Test
public void keyCreationTime() {
Instant now = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS);
TimeUtils.setMockClock(now);
wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
assertEquals(now, wallet.earliestKeyCreationTime());
TimeUtils.rollMockClock(Duration.ofMinutes(1));
wallet.freshReceiveKey();
assertEquals(now, wallet.earliestKeyCreationTime());
}
@Test
public void scriptCreationTime() {
Instant now = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS);
TimeUtils.setMockClock(now);
wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
assertEquals(now, wallet.earliestKeyCreationTime());
TimeUtils.rollMockClock(Duration.ofMinutes(-2));
wallet.addWatchedAddress(OTHER_ADDRESS);
wallet.freshReceiveKey();
assertEquals(now.minusSeconds(120), wallet.earliestKeyCreationTime());
}
@Test
public void spendToSameWallet() throws Exception {
// Test that a spend to the same wallet is dealt with correctly.
// It should appear in the wallet and confirm.
// This is a bit of a silly thing to do in the real world as all it does is burn a fee but it is perfectly valid.
Coin coin1 = COIN;
Coin coinHalf = valueOf(0, 50);
// Start by giving us 1 coin.
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, coin1);
// Send half to ourselves. We should then have a balance available to spend of zero.
assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals(1, wallet.getTransactions(true).size());
Transaction outbound1 = wallet.createSend(myAddress, coinHalf);
wallet.commitTx(outbound1);
// We should have a zero available balance before the next block.
assertEquals(ZERO, wallet.getBalance());
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, outbound1);
// We should have a balance of 1 BTC after the block is received.
assertEquals(coin1, wallet.getBalance());
}
@Test
public void lastBlockSeen() throws Exception {
Coin v1 = valueOf(5, 0);
Coin v2 = valueOf(0, 50);
Coin v3 = valueOf(0, 25);
Transaction t1 = createFakeTx(TESTNET.network(), v1, myAddress);
Transaction t2 = createFakeTx(TESTNET.network(), v2, myAddress);
Transaction t3 = createFakeTx(TESTNET.network(), v3, myAddress);
Block genesis = blockStore.getChainHead().getHeader();
Block b10 = makeSolvedTestBlock(genesis, t1);
Block b11 = makeSolvedTestBlock(genesis, t2);
Block b2 = makeSolvedTestBlock(b10, t3);
Block b3 = makeSolvedTestBlock(b2);
// Receive a block on the best chain - this should set the last block seen hash.
chain.add(b10);
assertEquals(b10.getHash(), wallet.getLastBlockSeenHash());
assertEquals(b10.time(), wallet.lastBlockSeenTime().get());
assertEquals(1, wallet.getLastBlockSeenHeight());
// Receive a block on the side chain - this should not change the last block seen hash.
chain.add(b11);
assertEquals(b10.getHash(), wallet.getLastBlockSeenHash());
// Receive block 2 on the best chain - this should change the last block seen hash.
chain.add(b2);
assertEquals(b2.getHash(), wallet.getLastBlockSeenHash());
// Receive block 3 on the best chain - this should change the last block seen hash despite having no txns.
chain.add(b3);
assertEquals(b3.getHash(), wallet.getLastBlockSeenHash());
}
@Test
public void pubkeyOnlyScripts() throws Exception {
// Verify that we support outputs like OP_PUBKEY and the corresponding inputs.
ECKey key1 = wallet.freshReceiveKey();
Coin value = valueOf(5, 0);
Transaction t1 = createFakeTx(value, key1);
if (wallet.isPendingTransactionRelevant(t1))
wallet.receivePending(t1, null);
// TX should have been seen as relevant.
assertEquals(value, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
assertEquals(ZERO, wallet.getBalance(Wallet.BalanceType.AVAILABLE));
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, t1);
// TX should have been seen as relevant, extracted and processed.
assertEquals(value, wallet.getBalance(Wallet.BalanceType.AVAILABLE));
// Spend it and ensure we can spend the <key> OP_CHECKSIG output correctly.
Transaction t2 = wallet.createSend(OTHER_ADDRESS, value);
assertNotNull(t2);
// TODO: This code is messy, improve the Script class and fixinate!
assertEquals(t2.toString(), 1, t2.getInput(0).getScriptSig().chunks().size());
assertTrue(t2.getInput(0).getScriptSig().chunks().get(0).data.length > 50);
}
@Test
public void isWatching() {
assertFalse(wallet.isWatching());
Wallet watchingWallet = Wallet.fromWatchingKey(TESTNET.network(),
wallet.getWatchingKey().dropPrivateBytes().dropParent(), ScriptType.P2PKH);
assertTrue(watchingWallet.isWatching());
wallet.encrypt(PASSWORD1);
assertFalse(wallet.isWatching());
}
@Test
public void watchingWallet() throws Exception {
DeterministicKey watchKey = wallet.getWatchingKey();
String serialized = watchKey.serializePubB58(TESTNET.network());
// Construct watching wallet.
Wallet watchingWallet = Wallet.fromWatchingKey(TESTNET.network(),
DeterministicKey.deserializeB58(null, serialized, TESTNET.network()), ScriptType.P2PKH);
DeterministicKey key2 = watchingWallet.freshReceiveKey();
assertEquals(myKey, key2);
ECKey key = wallet.freshKey(KeyChain.KeyPurpose.CHANGE);
key2 = watchingWallet.freshKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(key, key2);
key.sign(Sha256Hash.ZERO_HASH);
try {
key2.sign(Sha256Hash.ZERO_HASH);
fail();
} catch (ECKey.MissingPrivateKeyException e) {
// Expected
}
receiveATransaction(watchingWallet, myKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
assertEquals(COIN, watchingWallet.getBalance());
assertEquals(COIN, watchingWallet.getBalance(Wallet.BalanceType.AVAILABLE));
assertEquals(ZERO, watchingWallet.getBalance(Wallet.BalanceType.AVAILABLE_SPENDABLE));
}
@Test(expected = ECKey.MissingPrivateKeyException.class)
public void watchingWalletWithCreationTime() {
DeterministicKey watchKey = wallet.getWatchingKey();
String serialized = watchKey.serializePubB58(TESTNET.network());
Wallet watchingWallet = Wallet.fromWatchingKeyB58(TESTNET.network(), serialized, Instant.ofEpochSecond(1415282801));
DeterministicKey key2 = watchingWallet.freshReceiveKey();
assertEquals(myKey, key2);
ECKey key = wallet.freshKey(KeyChain.KeyPurpose.CHANGE);
key2 = watchingWallet.freshKey(KeyChain.KeyPurpose.CHANGE);
assertEquals(key, key2);
key.sign(Sha256Hash.ZERO_HASH);
key2.sign(Sha256Hash.ZERO_HASH);
}
@Test
public void watchingScripts() {
// Verify that pending transactions to watched addresses are relevant
Address watchedAddress = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
wallet.addWatchedAddress(watchedAddress);
Coin value = valueOf(5, 0);
Transaction t1 = createFakeTx(TESTNET.network(), value, watchedAddress);
assertTrue(t1.getWalletOutputs(wallet).size() >= 1);
assertTrue(wallet.isPendingTransactionRelevant(t1));
}
@Test(expected = InsufficientMoneyException.class)
public void watchingScriptsConfirmed() throws Exception {
Address watchedAddress = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
wallet.addWatchedAddress(watchedAddress);
sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, CENT, watchedAddress);
assertEquals(CENT, wallet.getBalance());
// We can't spend watched balances
wallet.createSend(OTHER_ADDRESS, CENT);
}
@Test
public void watchingScriptsSentFrom() {
int baseElements = wallet.getBloomFilterElementCount();
Address watchedAddress = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
wallet.addWatchedAddress(watchedAddress);
assertEquals(baseElements + 1, wallet.getBloomFilterElementCount());
Transaction t1 = createFakeTx(TESTNET.network(), CENT, watchedAddress);
Transaction t2 = createFakeTx(TESTNET.network(), COIN, OTHER_ADDRESS);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, t1);
assertEquals(baseElements + 2, wallet.getBloomFilterElementCount());
Transaction st2 = new Transaction();
st2.addOutput(CENT, OTHER_ADDRESS);
st2.addOutput(COIN, OTHER_ADDRESS);
st2.addInput(t1.getOutput(0));
st2.addInput(t2.getOutput(0));
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, st2);
assertEquals(baseElements + 2, wallet.getBloomFilterElementCount());
assertEquals(CENT, st2.getValueSentFromMe(wallet));
}
@Test
public void watchingScriptsBloomFilter() {
Address watchedAddress = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
Transaction t1 = createFakeTx(TESTNET.network(), CENT, watchedAddress);
TransactionOutPoint outPoint = new TransactionOutPoint(0, t1);
wallet.addWatchedAddress(watchedAddress);
// Note that this has a 1e-12 chance of failing this unit test due to a false positive
assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.serialize()));
sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
assertTrue(wallet.getBloomFilter(1e-12).contains(outPoint.serialize()));
}
@Test
public void getWatchedAddresses() {
Address watchedAddress = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
wallet.addWatchedAddress(watchedAddress);
List<Address> watchedAddresses = wallet.getWatchedAddresses();
assertEquals(1, watchedAddresses.size());
assertEquals(watchedAddress, watchedAddresses.get(0));
}
@Test
public void removeWatchedAddresses() {
List<Address> addressesForRemoval = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Address watchedAddress = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
addressesForRemoval.add(watchedAddress);
wallet.addWatchedAddress(watchedAddress);
}
wallet.removeWatchedAddresses(addressesForRemoval);
for (Address addr : addressesForRemoval)
assertFalse(wallet.isAddressWatched(addr));
}
@Test
public void removeWatchedAddress() {
Address watchedAddress = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
wallet.addWatchedAddress(watchedAddress);
wallet.removeWatchedAddress(watchedAddress);
assertFalse(wallet.isAddressWatched(watchedAddress));
}
@Test
public void removeScriptsBloomFilter() {
List<Address> addressesForRemoval = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Address watchedAddress = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
addressesForRemoval.add(watchedAddress);
wallet.addWatchedAddress(watchedAddress);
}
wallet.removeWatchedAddresses(addressesForRemoval);
for (Address addr : addressesForRemoval) {
Transaction t1 = createFakeTx(TESTNET.network(), CENT, addr);
TransactionOutPoint outPoint = new TransactionOutPoint(0, t1);
// Note that this has a 1e-12 chance of failing this unit test due to a false positive
assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.serialize()));
sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, t1);
assertFalse(wallet.getBloomFilter(1e-12).contains(outPoint.serialize()));
}
}
@Test
public void autosaveImmediate() throws Exception {
// Test that the wallet will save itself automatically when it changes.
File f = File.createTempFile("bitcoinj-unit-test", null);
Sha256Hash hash1 = Sha256Hash.of(f);
// Start with zero delay and ensure the wallet file changes after adding a key.
wallet.autosaveToFile(f, 0, TimeUnit.SECONDS, null);
ECKey key = wallet.freshReceiveKey();
Sha256Hash hash2 = Sha256Hash.of(f);
assertFalse("Wallet not saved after generating fresh key", hash1.equals(hash2)); // File has changed.
Transaction t1 = createFakeTx(valueOf(5, 0), key);
if (wallet.isPendingTransactionRelevant(t1))
wallet.receivePending(t1, null);
Sha256Hash hash3 = Sha256Hash.of(f);
assertFalse("Wallet not saved after receivePending", hash2.equals(hash3)); // File has changed again.
}
@Test
public void autosaveDelayed() throws Exception {
// Test that the wallet will save itself automatically when it changes, but not immediately and near-by
// updates are coalesced together. This test is a bit racy, it assumes we can complete the unit test within
// an auto-save cycle of 1 second.
final File[] results = new File[2];
final CountDownLatch latch = new CountDownLatch(3);
File f = File.createTempFile("bitcoinj-unit-test", null);
Sha256Hash hash1 = Sha256Hash.of(f);
wallet.autosaveToFile(f, 1, TimeUnit.SECONDS,
new WalletFiles.Listener() {
@Override
public void onBeforeAutoSave(File tempFile) {
results[0] = tempFile;
}
@Override
public void onAfterAutoSave(File newlySavedFile) {
results[1] = newlySavedFile;
latch.countDown();
}
}
);
ECKey key = wallet.freshReceiveKey();
Sha256Hash hash2 = Sha256Hash.of(f);
assertFalse(hash1.equals(hash2)); // File has changed immediately despite the delay, as keys are important.
assertNotNull(results[0]);
assertEquals(f, results[1]);
results[0] = results[1] = null;
sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN);
Sha256Hash hash3 = Sha256Hash.of(f);
assertEquals(hash2, hash3); // File has NOT changed yet. Just new blocks with no txns - delayed.
assertNull(results[0]);
assertNull(results[1]);
sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, valueOf(5, 0), key);
Sha256Hash hash4 = Sha256Hash.of(f);
assertFalse(hash3.equals(hash4)); // File HAS changed.
results[0] = results[1] = null;
// A block that contains some random tx we don't care about.
sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, Coin.COIN, OTHER_ADDRESS);
assertEquals(hash4, Sha256Hash.of(f)); // File has NOT changed.
assertNull(results[0]);
assertNull(results[1]);
// Wait for an auto-save to occur.
latch.await();
Sha256Hash hash5 = Sha256Hash.of(f);
assertFalse(hash4.equals(hash5)); // File has now changed.
assertNotNull(results[0]);
assertEquals(f, results[1]);
// Now we shutdown auto-saving and expect wallet changes to remain unsaved, even "important" changes.
wallet.shutdownAutosaveAndWait();
results[0] = results[1] = null;
ECKey key2 = new ECKey();
wallet.importKey(key2);
assertEquals(hash5, Sha256Hash.of(f)); // File has NOT changed.
sendMoneyToWallet(BlockChain.NewBlockType.BEST_CHAIN, valueOf(5, 0), key2);
Thread.sleep(2000); // Wait longer than autosave delay. TODO Fix the racyness.
assertEquals(hash5, Sha256Hash.of(f)); // File has still NOT changed.
assertNull(results[0]);
assertNull(results[1]);
}
@Test
public void spendOutputFromPendingTransaction() throws Exception {
// We'll set up a wallet that receives a coin, then sends a coin of lesser value and keeps the change.
Coin v1 = COIN;
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, v1);
// First create our current transaction
ECKey k2 = wallet.freshReceiveKey();
Coin v2 = valueOf(0, 50);
Transaction t2 = new Transaction();
TransactionOutput o2 = new TransactionOutput(t2, v2, k2.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
t2.addOutput(o2);
SendRequest req = SendRequest.forTx(t2);
wallet.completeTx(req);
// Commit t2, so it is placed in the pending pool
wallet.commitTx(t2);
assertEquals(0, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals(1, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
assertEquals(2, wallet.getTransactions(true).size());
// Now try to the spend the output.
ECKey k3 = new ECKey();
Coin v3 = valueOf(0, 25);
Transaction t3 = new Transaction();
t3.addOutput(v3, k3.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
t3.addInput(o2);
wallet.signTransaction(SendRequest.forTx(t3));
// Commit t3, so the coins from the pending t2 are spent
wallet.commitTx(t3);
assertEquals(0, wallet.getPoolSize(WalletTransaction.Pool.UNSPENT));
assertEquals(2, wallet.getPoolSize(WalletTransaction.Pool.PENDING));
assertEquals(3, wallet.getTransactions(true).size());
// Now the output of t2 must not be available for spending
assertFalse(o2.isAvailableForSpending());
}
@Test
public void replayWhilstPending() {
// Check that if a pending transaction spends outputs of chain-included transactions, we mark them as spent.
// See bug 345. This can happen if there is a pending transaction floating around and then you replay the
// chain without emptying the memory pool (or refilling it from a peer).
Coin value = COIN;
Transaction tx1 = createFakeTx(TESTNET.network(), value, myAddress);
Transaction tx2 = new Transaction();
tx2.addInput(tx1.getOutput(0));
tx2.addOutput(valueOf(0, 9), OTHER_ADDRESS);
// Add a change address to ensure this tx is relevant.
tx2.addOutput(CENT, wallet.currentChangeAddress());
wallet.receivePending(tx2, null);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx1);
assertEquals(ZERO, wallet.getBalance());
assertEquals(1, wallet.getPoolSize(Pool.SPENT));
assertEquals(1, wallet.getPoolSize(Pool.PENDING));
assertEquals(0, wallet.getPoolSize(Pool.UNSPENT));
}
@Test
public void outOfOrderPendingTxns() {
// Check that if there are two pending transactions which we receive out of order, they are marked as spent
// correctly. For instance, we are watching a wallet, someone pays us (A) and we then pay someone else (B)
// with a change address but the network delivers the transactions to us in order B then A.
Coin value = COIN;
Transaction a = createFakeTx(TESTNET.network(), value, myAddress);
Transaction b = new Transaction();
b.addInput(a.getOutput(0));
b.addOutput(CENT, OTHER_ADDRESS);
Coin v = COIN.subtract(CENT);
b.addOutput(v, wallet.currentChangeAddress());
a = roundTripTransaction(a);
b = roundTripTransaction(b);
wallet.receivePending(b, null);
assertEquals(v, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
wallet.receivePending(a, null);
assertEquals(v, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
}
@Test
public void encryptionDecryptionAESBasic() {
Wallet encryptedWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
encryptedWallet.encrypt(PASSWORD1);
KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter();
AesKey aesKey = keyCrypter.deriveKey(PASSWORD1);
assertEquals(EncryptionType.ENCRYPTED_SCRYPT_AES, encryptedWallet.getEncryptionType());
assertTrue(encryptedWallet.checkPassword(PASSWORD1));
assertTrue(encryptedWallet.checkAESKey(aesKey));
assertFalse(encryptedWallet.checkPassword(WRONG_PASSWORD));
assertNotNull("The keyCrypter is missing but should not be", keyCrypter);
encryptedWallet.decrypt(aesKey);
// Wallet should now be unencrypted.
assertNull("Wallet is not an unencrypted wallet", encryptedWallet.getKeyCrypter());
try {
encryptedWallet.checkPassword(PASSWORD1);
fail();
} catch (IllegalStateException e) {
}
}
@Test
public void encryptionDecryptionPasswordBasic() {
Wallet encryptedWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
encryptedWallet.encrypt(PASSWORD1);
assertTrue(encryptedWallet.isEncrypted());
encryptedWallet.decrypt(PASSWORD1);
assertFalse(encryptedWallet.isEncrypted());
// Wallet should now be unencrypted.
assertNull("Wallet is not an unencrypted wallet", encryptedWallet.getKeyCrypter());
try {
encryptedWallet.checkPassword(PASSWORD1);
fail();
} catch (IllegalStateException e) {
}
}
@Test
public void encryptionDecryptionBadPassword() {
Wallet encryptedWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
encryptedWallet.encrypt(PASSWORD1);
KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter();
AesKey wrongAesKey = keyCrypter.deriveKey(WRONG_PASSWORD);
// Check the wallet is currently encrypted
assertEquals("Wallet is not an encrypted wallet", EncryptionType.ENCRYPTED_SCRYPT_AES, encryptedWallet.getEncryptionType());
assertFalse(encryptedWallet.checkAESKey(wrongAesKey));
// Check that the wrong password does not decrypt the wallet.
try {
encryptedWallet.decrypt(wrongAesKey);
fail("Incorrectly decoded wallet with wrong password");
} catch (Wallet.BadWalletEncryptionKeyException e) {
// Expected.
}
}
@Test
public void changePasswordTest() {
Wallet encryptedWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
encryptedWallet.encrypt(PASSWORD1);
CharSequence newPassword = "My name is Tom";
encryptedWallet.changeEncryptionPassword(PASSWORD1, newPassword);
assertTrue(encryptedWallet.checkPassword(newPassword));
assertFalse(encryptedWallet.checkPassword(WRONG_PASSWORD));
}
@Test
public void changeAesKeyTest() {
Wallet encryptedWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
encryptedWallet.encrypt(PASSWORD1);
KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter();
AesKey aesKey = keyCrypter.deriveKey(PASSWORD1);
CharSequence newPassword = "My name is Tom";
AesKey newAesKey = keyCrypter.deriveKey(newPassword);
encryptedWallet.changeEncryptionKey(keyCrypter, aesKey, newAesKey);
assertTrue(encryptedWallet.checkAESKey(newAesKey));
assertFalse(encryptedWallet.checkAESKey(aesKey));
}
@Test
public void encryptionDecryptionCheckExceptions() {
Wallet encryptedWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
encryptedWallet.encrypt(PASSWORD1);
KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter();
AesKey aesKey = keyCrypter.deriveKey(PASSWORD1);
// Check the wallet is currently encrypted
assertEquals("Wallet is not an encrypted wallet", EncryptionType.ENCRYPTED_SCRYPT_AES, encryptedWallet.getEncryptionType());
// Decrypt wallet.
assertNotNull("The keyCrypter is missing but should not be", keyCrypter);
encryptedWallet.decrypt(aesKey);
// Try decrypting it again
try {
assertNotNull("The keyCrypter is missing but should not be", keyCrypter);
encryptedWallet.decrypt(aesKey);
fail("Should not be able to decrypt a decrypted wallet");
} catch (IllegalStateException e) {
// expected
}
assertNull("Wallet is not an unencrypted wallet", encryptedWallet.getKeyCrypter());
// Encrypt wallet.
encryptedWallet.encrypt(keyCrypter, aesKey);
assertEquals("Wallet is not an encrypted wallet", EncryptionType.ENCRYPTED_SCRYPT_AES, encryptedWallet.getEncryptionType());
// Try encrypting it again
try {
encryptedWallet.encrypt(keyCrypter, aesKey);
fail("Should not be able to encrypt an encrypted wallet");
} catch (IllegalStateException e) {
// expected
}
assertEquals("Wallet is not an encrypted wallet", EncryptionType.ENCRYPTED_SCRYPT_AES, encryptedWallet.getEncryptionType());
}
@Test(expected = KeyCrypterException.class)
public void addUnencryptedKeyToEncryptedWallet() {
Wallet encryptedWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
encryptedWallet.encrypt(PASSWORD1);
ECKey key1 = new ECKey();
encryptedWallet.importKey(key1);
}
@Test(expected = KeyCrypterException.class)
public void addEncryptedKeyToUnencryptedWallet() {
Wallet encryptedWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
encryptedWallet.encrypt(PASSWORD1);
KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter();
ECKey key1 = new ECKey();
key1 = key1.encrypt(keyCrypter, keyCrypter.deriveKey("PASSWORD!"));
wallet.importKey(key1);
}
@Test(expected = KeyCrypterException.class)
public void mismatchedCrypter() {
Wallet encryptedWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
encryptedWallet.encrypt(PASSWORD1);
KeyCrypter keyCrypter = encryptedWallet.getKeyCrypter();
AesKey aesKey = keyCrypter.deriveKey(PASSWORD1);
// Try added an ECKey that was encrypted with a differenct ScryptParameters (i.e. a non-homogenous key).
// This is not allowed as the ScryptParameters is stored at the Wallet level.
KeyCrypter keyCrypterDifferent = new KeyCrypterScrypt();
ECKey ecKeyDifferent = new ECKey();
ecKeyDifferent = ecKeyDifferent.encrypt(keyCrypterDifferent, aesKey);
encryptedWallet.importKey(ecKeyDifferent);
}
@Test
public void importAndEncrypt() throws InsufficientMoneyException {
Wallet encryptedWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
encryptedWallet.encrypt(PASSWORD1);
final ECKey key = new ECKey();
encryptedWallet.importKeysAndEncrypt(Collections.singletonList(key), PASSWORD1);
assertEquals(1, encryptedWallet.getImportedKeys().size());
assertEquals(key.getPubKeyPoint(), encryptedWallet.getImportedKeys().get(0).getPubKeyPoint());
sendMoneyToWallet(encryptedWallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, Coin.COIN, key.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
assertEquals(Coin.COIN, encryptedWallet.getBalance());
SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
req.aesKey = Objects.requireNonNull(encryptedWallet.getKeyCrypter()).deriveKey(PASSWORD1);
encryptedWallet.sendCoinsOffline(req);
}
@Test
public void ageMattersDuringSelection() throws Exception {
// Test that we prefer older coins to newer coins when building spends. This reduces required fees and improves
// time to confirmation as the transaction will appear less spammy.
final int ITERATIONS = 10;
Transaction[] txns = new Transaction[ITERATIONS];
for (int i = 0; i < ITERATIONS; i++) {
txns[i] = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
}
// Check that we spend transactions in order of reception.
for (int i = 0; i < ITERATIONS; i++) {
Transaction spend = wallet.createSend(OTHER_ADDRESS, COIN);
assertEquals(spend.getInputs().size(), 1);
assertEquals("Failed on iteration " + i, spend.getInput(0).getOutpoint().hash(), txns[i].getTxId());
wallet.commitTx(spend);
}
}
@Test(expected = Wallet.ExceededMaxTransactionSize.class)
public void respectMaxStandardSize() throws Exception {
// Check that we won't create txns > 100kb. Average tx size is ~220 bytes so this would have to be enormous.
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, valueOf(100, 0));
Transaction tx = new Transaction();
byte[] bits = new byte[20];
new Random().nextBytes(bits);
Coin v = CENT;
// 3100 outputs to a random address.
for (int i = 0; i < 3100; i++) {
tx.addOutput(v, LegacyAddress.fromPubKeyHash(BitcoinNetwork.TESTNET, bits));
}
SendRequest req = SendRequest.forTx(tx);
wallet.completeTx(req);
}
@Test
public void opReturnOneOutputTest() throws Exception {
// Tests basic send of transaction with one output that doesn't transfer any value but just writes OP_RETURN.
receiveATransaction(wallet, myAddress);
Transaction tx = new Transaction();
Coin messagePrice = Coin.ZERO;
Script script = ScriptBuilder.createOpReturnScript("hello world!".getBytes());
tx.addOutput(messagePrice, script);
SendRequest request = SendRequest.forTx(tx);
request.ensureMinRequiredFee = true;
wallet.completeTx(request);
}
@Test
public void opReturnMaxBytes() throws Exception {
receiveATransaction(wallet, myAddress);
Transaction tx = new Transaction();
Script script = ScriptBuilder.createOpReturnScript(new byte[80]);
tx.addOutput(Coin.ZERO, script);
SendRequest request = SendRequest.forTx(tx);
request.ensureMinRequiredFee = true;
wallet.completeTx(request);
}
@Test
public void opReturnOneOutputWithValueTest() throws Exception {
// Tests basic send of transaction with one output that destroys coins and has an OP_RETURN.
receiveATransaction(wallet, myAddress);
Transaction tx = new Transaction();
Coin messagePrice = CENT;
Script script = ScriptBuilder.createOpReturnScript("hello world!".getBytes());
tx.addOutput(messagePrice, script);
SendRequest request = SendRequest.forTx(tx);
wallet.completeTx(request);
}
@Test
public void opReturnTwoOutputsTest() throws Exception {
// Tests sending transaction where one output transfers BTC, the other one writes OP_RETURN.
receiveATransaction(wallet, myAddress);
Transaction tx = new Transaction();
Coin messagePrice = Coin.ZERO;
Script script = ScriptBuilder.createOpReturnScript("hello world!".getBytes());
tx.addOutput(CENT, OTHER_ADDRESS);
tx.addOutput(messagePrice, script);
SendRequest request = SendRequest.forTx(tx);
wallet.completeTx(request);
}
@Test(expected = Wallet.MultipleOpReturnRequested.class)
@Parameters({"false, false", "false, true", "true, false", "true, true"})
public void twoOpReturnsPerTransactionTest(boolean ensureMinRequiredFee, boolean emptyWallet) throws Exception {
// Tests sending transaction where there are 2 attempts to write OP_RETURN scripts - this should fail and throw MultipleOpReturnRequested.
receiveATransaction(wallet, myAddress);
Transaction tx = new Transaction();
Coin messagePrice = Coin.ZERO;
Script script1 = ScriptBuilder.createOpReturnScript("hello world 1!".getBytes());
Script script2 = ScriptBuilder.createOpReturnScript("hello world 2!".getBytes());
tx.addOutput(messagePrice, script1);
tx.addOutput(messagePrice, script2);
SendRequest request = SendRequest.forTx(tx);
request.ensureMinRequiredFee = ensureMinRequiredFee;
request.emptyWallet = emptyWallet;
wallet.completeTx(request);
}
@Test(expected = Wallet.DustySendRequested.class)
public void sendDustTest() throws InsufficientMoneyException {
// Tests sending dust, should throw DustySendRequested.
Transaction tx = new Transaction();
Coin dustThreshold = new TransactionOutput(null, Coin.COIN, OTHER_ADDRESS).getMinNonDustValue();
tx.addOutput(dustThreshold.subtract(SATOSHI), OTHER_ADDRESS);
SendRequest request = SendRequest.forTx(tx);
request.ensureMinRequiredFee = true;
wallet.completeTx(request);
}
@Test
public void sendMultipleCentsTest() throws Exception {
receiveATransactionAmount(wallet, myAddress, Coin.COIN);
Transaction tx = new Transaction();
Coin c = CENT.subtract(SATOSHI);
tx.addOutput(c, OTHER_ADDRESS);
tx.addOutput(c, OTHER_ADDRESS);
tx.addOutput(c, OTHER_ADDRESS);
tx.addOutput(c, OTHER_ADDRESS);
SendRequest request = SendRequest.forTx(tx);
wallet.completeTx(request);
}
@Test(expected = Wallet.DustySendRequested.class)
public void sendDustAndOpReturnWithoutValueTest() throws Exception {
// Tests sending dust and OP_RETURN without value, should throw DustySendRequested because sending sending dust is not allowed in any case.
receiveATransactionAmount(wallet, myAddress, Coin.COIN);
Transaction tx = new Transaction();
tx.addOutput(Coin.ZERO, ScriptBuilder.createOpReturnScript("hello world!".getBytes()));
tx.addOutput(Coin.SATOSHI, OTHER_ADDRESS);
SendRequest request = SendRequest.forTx(tx);
request.ensureMinRequiredFee = true;
wallet.completeTx(request);
}
@Test(expected = Wallet.DustySendRequested.class)
public void sendDustAndMessageWithValueTest() throws Exception {
// Tests sending dust and OP_RETURN with value, should throw DustySendRequested
receiveATransaction(wallet, myAddress);
Transaction tx = new Transaction();
tx.addOutput(Coin.CENT, ScriptBuilder.createOpReturnScript("hello world!".getBytes()));
Coin dustThreshold = new TransactionOutput(null, Coin.COIN, OTHER_ADDRESS).getMinNonDustValue();
tx.addOutput(dustThreshold.subtract(SATOSHI), OTHER_ADDRESS);
SendRequest request = SendRequest.forTx(tx);
request.ensureMinRequiredFee = true;
wallet.completeTx(request);
}
@Test
public void sendRequestP2PKTest() {
ECKey key = new ECKey();
SendRequest req = SendRequest.to(key, SATOSHI.multiply(12));
assertArrayEquals(key.getPubKey(),
ScriptPattern.extractKeyFromP2PK(req.tx.getOutput(0).getScriptPubKey()));
}
@Test
public void sendRequestP2PKHTest() {
SendRequest req = SendRequest.to(OTHER_ADDRESS, SATOSHI.multiply(12));
assertEquals(OTHER_ADDRESS, req.tx.getOutput(0).getScriptPubKey().getToAddress(BitcoinNetwork.TESTNET));
}
@Test
public void feeSolverAndCoinSelectionTest_dustySendRequested() throws Exception {
// Generate a few outputs to us that are far too small to spend reasonably
Transaction tx1 = createFakeTx(TESTNET.network(), SATOSHI, myAddress);
Transaction tx2 = createFakeTx(TESTNET.network(), SATOSHI, myAddress);
assertNotEquals(tx1.getTxId(), tx2.getTxId());
Transaction tx3 = createFakeTx(TESTNET.network(), SATOSHI.multiply(10), myAddress);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx1, tx2, tx3);
// Not allowed to send dust.
try {
SendRequest request = SendRequest.to(OTHER_ADDRESS, SATOSHI);
request.ensureMinRequiredFee = true;
wallet.completeTx(request);
fail();
} catch (Wallet.DustySendRequested e) {
// Expected.
}
// Spend it all without fee enforcement
SendRequest req = SendRequest.to(OTHER_ADDRESS, SATOSHI.multiply(12));
assertNotNull(wallet.sendCoinsOffline(req));
assertEquals(ZERO, wallet.getBalance());
}
@Test
public void coinSelection_coinTimesDepth() throws Exception {
Transaction txCent = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT);
for (int i = 0; i < 197; i++)
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN);
Transaction txCoin = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
assertEquals(COIN.add(CENT), wallet.getBalance());
assertTrue(txCent.getOutput(0).isMine(wallet));
assertTrue(txCent.getOutput(0).isAvailableForSpending());
assertEquals(199, txCent.getConfidence().getDepthInBlocks());
assertTrue(txCoin.getOutput(0).isMine(wallet));
assertTrue(txCoin.getOutput(0).isAvailableForSpending());
assertEquals(1, txCoin.getConfidence().getDepthInBlocks());
// txCent has higher coin*depth than txCoin...
assertTrue(txCent.getOutput(0).getValue().multiply(txCent.getConfidence().getDepthInBlocks())
.isGreaterThan(txCoin.getOutput(0).getValue().multiply(txCoin.getConfidence().getDepthInBlocks())));
// ...so txCent should be selected
Transaction spend1 = wallet.createSend(OTHER_ADDRESS, CENT);
assertEquals(1, spend1.getInputs().size());
assertEquals(CENT, spend1.getInput(0).getValue());
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN);
assertTrue(txCent.getOutput(0).isMine(wallet));
assertTrue(txCent.getOutput(0).isAvailableForSpending());
assertEquals(200, txCent.getConfidence().getDepthInBlocks());
assertTrue(txCoin.getOutput(0).isMine(wallet));
assertTrue(txCoin.getOutput(0).isAvailableForSpending());
assertEquals(2, txCoin.getConfidence().getDepthInBlocks());
// Now txCent and txCoin have exactly the same coin*depth...
assertEquals(txCent.getOutput(0).getValue().multiply(txCent.getConfidence().getDepthInBlocks()),
txCoin.getOutput(0).getValue().multiply(txCoin.getConfidence().getDepthInBlocks()));
// ...so the larger txCoin should be selected
Transaction spend2 = wallet.createSend(OTHER_ADDRESS, COIN);
assertEquals(1, spend2.getInputs().size());
assertEquals(COIN, spend2.getInput(0).getValue());
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN);
assertTrue(txCent.getOutput(0).isMine(wallet));
assertTrue(txCent.getOutput(0).isAvailableForSpending());
assertEquals(201, txCent.getConfidence().getDepthInBlocks());
assertTrue(txCoin.getOutput(0).isMine(wallet));
assertTrue(txCoin.getOutput(0).isAvailableForSpending());
assertEquals(3, txCoin.getConfidence().getDepthInBlocks());
// Now txCent has lower coin*depth than txCoin...
assertTrue(txCent.getOutput(0).getValue().multiply(txCent.getConfidence().getDepthInBlocks())
.isLessThan(txCoin.getOutput(0).getValue().multiply(txCoin.getConfidence().getDepthInBlocks())));
// ...so txCoin should be selected
Transaction spend3 = wallet.createSend(OTHER_ADDRESS, COIN);
assertEquals(1, spend3.getInputs().size());
assertEquals(COIN, spend3.getInput(0).getValue());
}
@Test
public void feeSolverAndCoinSelectionTests2() throws Exception {
Transaction tx5 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
// Now test feePerKb
SendRequest request15 = SendRequest.to(OTHER_ADDRESS, CENT);
for (int i = 0; i < 29; i++)
request15.tx.addOutput(CENT, OTHER_ADDRESS);
assertTrue(request15.tx.serialize().length > 1000);
request15.feePerKb = Transaction.DEFAULT_TX_FEE;
request15.ensureMinRequiredFee = true;
wallet.completeTx(request15);
assertEquals(Coin.valueOf(121300), request15.tx.getFee());
Transaction spend15 = request15.tx;
assertEquals(31, spend15.getOutputs().size());
// We optimize for priority, so the output selected should be the largest one
assertEquals(1, spend15.getInputs().size());
assertEquals(COIN, spend15.getInput(0).getValue());
// Test ensureMinRequiredFee
SendRequest request16 = SendRequest.to(OTHER_ADDRESS, CENT);
request16.feePerKb = ZERO;
request16.ensureMinRequiredFee = true;
for (int i = 0; i < 29; i++)
request16.tx.addOutput(CENT, OTHER_ADDRESS);
assertTrue(request16.tx.serialize().length > 1000);
wallet.completeTx(request16);
// Just the reference fee should be added if feePerKb == 0
// Hardcoded tx length because actual length may vary depending on actual signature length
assertEquals(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.multiply(1213).divide(1000), request16.tx.getFee());
Transaction spend16 = request16.tx;
assertEquals(31, spend16.getOutputs().size());
// We optimize for priority, so the output selected should be the largest one
assertEquals(1, spend16.getInputs().size());
assertEquals(COIN, spend16.getInput(0).getValue());
// Create a transaction whose max size could be up to 999 (if signatures were maximum size)
SendRequest request17 = SendRequest.to(OTHER_ADDRESS, CENT);
for (int i = 0; i < 22; i++)
request17.tx.addOutput(CENT, OTHER_ADDRESS);
request17.tx.addOutput(new TransactionOutput(request17.tx, CENT, new byte[15]));
request17.feePerKb = Transaction.DEFAULT_TX_FEE;
request17.ensureMinRequiredFee = true;
wallet.completeTx(request17);
assertEquals(Coin.valueOf(99900), request17.tx.getFee());
assertEquals(1, request17.tx.getInputs().size());
// Calculate its max length to make sure it is indeed 999
int theoreticalMaxLength17 = request17.tx.serialize().length + myKey.getPubKey().length + 75;
for (TransactionInput in : request17.tx.getInputs())
theoreticalMaxLength17 -= in.getScriptBytes().length;
assertEquals(999, theoreticalMaxLength17);
Transaction spend17 = request17.tx;
{
// Its actual size must be between 996 and 999 (inclusive) as signatures have a 3-byte size range (almost always)
final int length = spend17.serialize().length;
assertTrue(Integer.toString(length), length >= 996 && length <= 999);
}
// Now check that it got a fee of 1 since its max size is 999 (1kb).
assertEquals(25, spend17.getOutputs().size());
// We optimize for priority, so the output selected should be the largest one
assertEquals(1, spend17.getInputs().size());
assertEquals(COIN, spend17.getInput(0).getValue());
// Create a transaction who's max size could be up to 1001 (if signatures were maximum size)
SendRequest request18 = SendRequest.to(OTHER_ADDRESS, CENT);
for (int i = 0; i < 22; i++)
request18.tx.addOutput(CENT, OTHER_ADDRESS);
request18.tx.addOutput(new TransactionOutput(request18.tx, CENT, new byte[17]));
request18.feePerKb = Transaction.DEFAULT_TX_FEE;
request18.ensureMinRequiredFee = true;
wallet.completeTx(request18);
assertEquals(Coin.valueOf(100100), request18.tx.getFee());
assertEquals(1, request18.tx.getInputs().size());
// Calculate its max length to make sure it is indeed 1001
Transaction spend18 = request18.tx;
int theoreticalMaxLength18 = spend18.serialize().length + myKey.getPubKey().length + 75;
for (TransactionInput in : spend18.getInputs())
theoreticalMaxLength18 -= in.getScriptBytes().length;
assertEquals(1001, theoreticalMaxLength18);
// Its actual size must be between 998 and 1000 (inclusive) as signatures have a 3-byte size range (almost always)
assertTrue(spend18.serialize().length >= 998);
assertTrue(spend18.serialize().length <= 1001);
// Now check that it did get a fee since its max size is 1000
assertEquals(25, spend18.getOutputs().size());
// We optimize for priority, so the output selected should be the largest one
assertEquals(1, spend18.getInputs().size());
assertEquals(COIN, spend18.getInput(0).getValue());
// Now create a transaction that will spend COIN + fee, which makes it require both inputs
assertEquals(wallet.getBalance(), CENT.add(COIN));
SendRequest request19 = SendRequest.to(OTHER_ADDRESS, CENT);
request19.feePerKb = ZERO;
for (int i = 0; i < 99; i++)
request19.tx.addOutput(CENT, OTHER_ADDRESS);
// If we send now, we should only have to spend our COIN
wallet.completeTx(request19);
assertEquals(Coin.ZERO, request19.tx.getFee());
assertEquals(1, request19.tx.getInputs().size());
assertEquals(100, request19.tx.getOutputs().size());
// Now reset request19 and give it a fee per kb
request19.tx.clearInputs();
request19 = SendRequest.forTx(request19.tx);
request19.feePerKb = Transaction.DEFAULT_TX_FEE;
request19.shuffleOutputs = false;
wallet.completeTx(request19);
assertEquals(Coin.valueOf(374200), request19.tx.getFee());
assertEquals(2, request19.tx.getInputs().size());
assertEquals(COIN, request19.tx.getInput(0).getValue());
assertEquals(CENT, request19.tx.getInput(1).getValue());
// Create another transaction that will spend COIN + fee, which makes it require both inputs
SendRequest request20 = SendRequest.to(OTHER_ADDRESS, CENT);
request20.feePerKb = ZERO;
for (int i = 0; i < 99; i++)
request20.tx.addOutput(CENT, OTHER_ADDRESS);
// If we send now, we shouldn't have a fee and should only have to spend our COIN
wallet.completeTx(request20);
assertEquals(ZERO, request20.tx.getFee());
assertEquals(1, request20.tx.getInputs().size());
assertEquals(100, request20.tx.getOutputs().size());
// Now reset request19 and give it a fee per kb
request20.tx.clearInputs();
request20 = SendRequest.forTx(request20.tx);
request20.feePerKb = Transaction.DEFAULT_TX_FEE;
wallet.completeTx(request20);
// 4kb tx.
assertEquals(Coin.valueOf(374200), request20.tx.getFee());
assertEquals(2, request20.tx.getInputs().size());
assertEquals(COIN, request20.tx.getInput(0).getValue());
assertEquals(CENT, request20.tx.getInput(1).getValue());
// Same as request 19, but make the change 0 (so it doesn't force fee) and make us require min fee
SendRequest request21 = SendRequest.to(OTHER_ADDRESS, CENT);
request21.feePerKb = ZERO;
request21.ensureMinRequiredFee = true;
for (int i = 0; i < 99; i++)
request21.tx.addOutput(CENT, OTHER_ADDRESS);
//request21.tx.addOutput(CENT.subtract(Coin.valueOf(18880-10)), OTHER_ADDRESS); //fails because tx size is calculated with a change output
request21.tx.addOutput(CENT.subtract(Coin.valueOf(18880)), OTHER_ADDRESS); //3739 bytes, fee 5048 sat/kb
//request21.tx.addOutput(CENT.subtract(Coin.valueOf(500000)), OTHER_ADDRESS); //3774 bytes, fee 5003 sat/kb
// If we send without a feePerKb, we should still require REFERENCE_DEFAULT_MIN_TX_FEE because we have an output < 0.01
wallet.completeTx(request21);
// Hardcoded tx length because actual length may vary depending on actual signature length
assertEquals(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.multiply(3776).divide(1000), request21.tx.getFee());
assertEquals(2, request21.tx.getInputs().size());
assertEquals(COIN, request21.tx.getInput(0).getValue());
assertEquals(CENT, request21.tx.getInput(1).getValue());
// Test feePerKb when we aren't using ensureMinRequiredFee
SendRequest request25 = SendRequest.to(OTHER_ADDRESS, CENT);
request25.feePerKb = ZERO;
for (int i = 0; i < 70; i++)
request25.tx.addOutput(CENT, OTHER_ADDRESS);
// If we send now, we shouldn't need a fee and should only have to spend our COIN
wallet.completeTx(request25);
assertEquals(ZERO, request25.tx.getFee());
assertEquals(1, request25.tx.getInputs().size());
assertEquals(72, request25.tx.getOutputs().size());
// Now reset request25 and give it a fee per kb
request25.tx.clearInputs();
request25 = SendRequest.forTx(request25.tx);
request25.feePerKb = Transaction.DEFAULT_TX_FEE;
request25.shuffleOutputs = false;
wallet.completeTx(request25);
assertEquals(Coin.valueOf(279000), request25.tx.getFee());
assertEquals(2, request25.tx.getInputs().size());
assertEquals(COIN, request25.tx.getInput(0).getValue());
assertEquals(CENT, request25.tx.getInput(1).getValue());
// Spend our CENT output.
Transaction spendTx5 = new Transaction();
spendTx5.addOutput(CENT, OTHER_ADDRESS);
spendTx5.addInput(tx5.getOutput(0));
wallet.signTransaction(SendRequest.forTx(spendTx5));
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, spendTx5);
assertEquals(COIN, wallet.getBalance());
// Ensure change is discarded if it is dust
SendRequest request26 = SendRequest.to(OTHER_ADDRESS, CENT);
for (int i = 0; i < 98; i++)
request26.tx.addOutput(CENT, OTHER_ADDRESS);
// Hardcoded tx length because actual length may vary depending on actual signature length
Coin fee = Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.multiply(3560).divide(1000);
Coin dustThresholdMinusOne = new TransactionOutput(null, Coin.COIN, OTHER_ADDRESS).getMinNonDustValue().subtract(SATOSHI);
request26.tx.addOutput(CENT.subtract(fee.add(dustThresholdMinusOne)),
OTHER_ADDRESS);
assertTrue(request26.tx.serialize().length > 1000);
request26.feePerKb = SATOSHI;
request26.ensureMinRequiredFee = true;
wallet.completeTx(request26);
assertEquals(fee.add(dustThresholdMinusOne), request26.tx.getFee());
Transaction spend26 = request26.tx;
assertEquals(100, spend26.getOutputs().size());
// We optimize for priority, so the output selected should be the largest one
assertEquals(1, spend26.getInputs().size());
assertEquals(COIN, spend26.getInput(0).getValue());
}
@Test
public void recipientPaysFees() throws Exception {
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
// Simplest recipientPaysFees use case
Coin valueToSend = CENT.divide(2);
SendRequest request = SendRequest.to(OTHER_ADDRESS, valueToSend);
request.feePerKb = Transaction.DEFAULT_TX_FEE;
request.ensureMinRequiredFee = true;
request.recipientsPayFees = true;
request.shuffleOutputs = false;
wallet.completeTx(request);
// Hardcoded tx length because actual length may vary depending on actual signature length
Coin fee = request.feePerKb.multiply(227).divide(1000);
assertEquals(fee, request.tx.getFee());
Transaction spend = request.tx;
assertEquals(2, spend.getOutputs().size());
assertEquals(valueToSend.subtract(fee), spend.getOutput(0).getValue());
assertEquals(COIN.subtract(valueToSend), spend.getOutput(1).getValue());
assertEquals(1, spend.getInputs().size());
assertEquals(COIN, spend.getInput(0).getValue());
// Fee is split between the 2 outputs
SendRequest request2 = SendRequest.to(OTHER_ADDRESS, valueToSend);
request2.tx.addOutput(valueToSend, OTHER_ADDRESS);
request2.feePerKb = Transaction.DEFAULT_TX_FEE;
request2.ensureMinRequiredFee = true;
request2.recipientsPayFees = true;
request2.shuffleOutputs = false;
wallet.completeTx(request2);
// Hardcoded tx length because actual length may vary depending on actual signature length
Coin fee2 = request2.feePerKb.multiply(261).divide(1000);
assertEquals(fee2, request2.tx.getFee());
Transaction spend2 = request2.tx;
assertEquals(3, spend2.getOutputs().size());
assertEquals(valueToSend.subtract(fee2.divide(2)), spend2.getOutput(0).getValue());
assertEquals(valueToSend.subtract(fee2.divide(2)), spend2.getOutput(1).getValue());
assertEquals(COIN.subtract(valueToSend.multiply(2)), spend2.getOutput(2).getValue());
assertEquals(1, spend2.getInputs().size());
assertEquals(COIN, spend2.getInput(0).getValue());
// Fee is split between the 3 outputs. Division has a remainder which is taken from the first output
SendRequest request3 = SendRequest.to(OTHER_ADDRESS, valueToSend);
request3.tx.addOutput(valueToSend, OTHER_ADDRESS);
request3.tx.addOutput(valueToSend, OTHER_ADDRESS);
request3.feePerKb = Transaction.DEFAULT_TX_FEE;
request3.ensureMinRequiredFee = true;
request3.recipientsPayFees = true;
request3.shuffleOutputs = false;
wallet.completeTx(request3);
// Hardcoded tx length because actual length may vary depending on actual signature length
Coin fee3 = request3.feePerKb.multiply(295).divide(1000);
assertEquals(fee3, request3.tx.getFee());
Transaction spend3 = request3.tx;
assertEquals(4, spend3.getOutputs().size());
// 1st output pays the fee division remainder
assertEquals(valueToSend.subtract(fee3.divideAndRemainder(3)[0]).subtract(fee3.divideAndRemainder(3)[1]),
spend3.getOutput(0).getValue());
assertEquals(valueToSend.subtract(fee3.divide(3)), spend3.getOutput(1).getValue());
assertEquals(valueToSend.subtract(fee3.divide(3)), spend3.getOutput(2).getValue());
assertEquals(COIN.subtract(valueToSend.multiply(3)), spend3.getOutput(3).getValue());
assertEquals(1, spend3.getInputs().size());
assertEquals(COIN, spend3.getInput(0).getValue());
// Output when subtracted fee is dust
// Hardcoded tx length because actual length may vary depending on actual signature length
Coin fee4 = Transaction.DEFAULT_TX_FEE.multiply(227).divide(1000);
Coin dustThreshold = new TransactionOutput(null, Coin.COIN, OTHER_ADDRESS).getMinNonDustValue();
valueToSend = fee4.add(dustThreshold).subtract(SATOSHI);
SendRequest request4 = SendRequest.to(OTHER_ADDRESS, valueToSend);
request4.feePerKb = Transaction.DEFAULT_TX_FEE;
request4.ensureMinRequiredFee = true;
request4.recipientsPayFees = true;
request4.shuffleOutputs = false;
try {
wallet.completeTx(request4);
fail("Expected CouldNotAdjustDownwards exception");
} catch (Wallet.CouldNotAdjustDownwards e) {
}
// Change is dust, so it is incremented to min non dust value. First output value is reduced to compensate.
// Hardcoded tx length because actual length may vary depending on actual signature length
Coin fee5 = Transaction.DEFAULT_TX_FEE.multiply(261).divide(1000);
valueToSend = COIN.divide(2).subtract(Coin.MICROCOIN);
SendRequest request5 = SendRequest.to(OTHER_ADDRESS, valueToSend);
request5.tx.addOutput(valueToSend, OTHER_ADDRESS);
request5.feePerKb = Transaction.DEFAULT_TX_FEE;
request5.ensureMinRequiredFee = true;
request5.recipientsPayFees = true;
request5.shuffleOutputs = false;
wallet.completeTx(request5);
assertEquals(fee5, request5.tx.getFee());
Transaction spend5 = request5.tx;
assertEquals(3, spend5.getOutputs().size());
Coin valueSubtractedFromFirstOutput = dustThreshold
.subtract(COIN.subtract(valueToSend.multiply(2)));
assertEquals(valueToSend.subtract(fee5.divide(2)).subtract(valueSubtractedFromFirstOutput),
spend5.getOutput(0).getValue());
assertEquals(valueToSend.subtract(fee5.divide(2)), spend5.getOutput(1).getValue());
assertEquals(dustThreshold, spend5.getOutput(2).getValue());
assertEquals(1, spend5.getInputs().size());
assertEquals(COIN, spend5.getInput(0).getValue());
// Change is dust, so it is incremented to min non dust value. First output value is about to be reduced to
// compensate, but after subtracting some satoshis, first output is dust.
// Hardcoded tx length because actual length may vary depending on actual signature length
Coin fee6 = Transaction.DEFAULT_TX_FEE.multiply(261).divide(1000);
Coin valueToSend1 = fee6.divide(2).add(dustThreshold).add(Coin.MICROCOIN);
Coin valueToSend2 = COIN.subtract(valueToSend1).subtract(Coin.MICROCOIN.multiply(2));
SendRequest request6 = SendRequest.to(OTHER_ADDRESS, valueToSend1);
request6.tx.addOutput(valueToSend2, OTHER_ADDRESS);
request6.feePerKb = Transaction.DEFAULT_TX_FEE;
request6.ensureMinRequiredFee = true;
request6.recipientsPayFees = true;
request6.shuffleOutputs = false;
try {
wallet.completeTx(request6);
fail("Expected CouldNotAdjustDownwards exception");
} catch (Wallet.CouldNotAdjustDownwards e) {
}
}
@Test
public void transactionGetFeeTest() throws Exception {
// Prepare wallet to spend
StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1);
Transaction tx = createFakeTx(TESTNET.network(), COIN, myAddress);
wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
// Create a transaction
SendRequest request = SendRequest.to(OTHER_ADDRESS, CENT);
request.feePerKb = Transaction.DEFAULT_TX_FEE;
wallet.completeTx(request);
assertEquals(Coin.valueOf(22700), request.tx.getFee());
}
@Test
public void witnessTransactionGetFeeTest() throws Exception {
Wallet mySegwitWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2WPKH);
Address mySegwitAddress = mySegwitWallet.freshReceiveAddress(ScriptType.P2WPKH);
// Prepare wallet to spend
StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_SEGWIT_ADDRESS), BigInteger.ONE, 1);
Transaction tx = createFakeTx(TESTNET.network(), COIN, mySegwitAddress);
mySegwitWallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
// Create a transaction
SendRequest request = SendRequest.to(OTHER_SEGWIT_ADDRESS, CENT);
request.feePerKb = Transaction.DEFAULT_TX_FEE;
mySegwitWallet.completeTx(request);
// Fee test, absolute and per virtual kilobyte
Coin fee = request.tx.getFee();
int vsize = request.tx.getVsize();
Coin feePerVkb = fee.multiply(1000).divide(vsize);
assertEquals(Coin.valueOf(14100), fee);
// due to shorter than expected signature encoding, in rare cases we overpay a little
Coin overpaidFee = Transaction.DEFAULT_TX_FEE.add(valueOf(714));
assertTrue(feePerVkb.toString(),feePerVkb.equals(Transaction.DEFAULT_TX_FEE) || feePerVkb.equals(overpaidFee));
}
@Test
public void lowerThanDefaultFee() throws InsufficientMoneyException {
int feeFactor = 200;
Coin fee = Transaction.DEFAULT_TX_FEE.divide(feeFactor);
receiveATransactionAmount(wallet, myAddress, Coin.COIN);
SendRequest req = SendRequest.to(myAddress, Coin.CENT);
req.feePerKb = fee;
wallet.completeTx(req);
assertEquals(Coin.valueOf(22700).divide(feeFactor), req.tx.getFee());
wallet.commitTx(req.tx);
SendRequest emptyReq = SendRequest.emptyWallet(myAddress);
emptyReq.feePerKb = fee;
emptyReq.ensureMinRequiredFee = true;
emptyReq.emptyWallet = true;
emptyReq.allowUnconfirmed();
wallet.completeTx(emptyReq);
final Coin feePerKb = emptyReq.tx.getFee().multiply(1000).divide(emptyReq.tx.getVsize());
assertThat((double) feePerKb.toSat(), closeTo(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.toSat(),20));
wallet.commitTx(emptyReq.tx);
}
@Test
public void higherThanDefaultFee() throws InsufficientMoneyException {
int feeFactor = 10;
Coin fee = Transaction.DEFAULT_TX_FEE.multiply(feeFactor);
receiveATransactionAmount(wallet, myAddress, Coin.COIN);
SendRequest req = SendRequest.to(myAddress, Coin.CENT);
req.feePerKb = fee;
wallet.completeTx(req);
assertEquals(Coin.valueOf(22700).multiply(feeFactor), req.tx.getFee());
wallet.commitTx(req.tx);
SendRequest emptyReq = SendRequest.emptyWallet(myAddress);
emptyReq.feePerKb = fee;
emptyReq.emptyWallet = true;
emptyReq.allowUnconfirmed();
wallet.completeTx(emptyReq);
assertEquals(Coin.valueOf(342000), emptyReq.tx.getFee());
wallet.commitTx(emptyReq.tx);
}
@Test
public void testCompleteTxWithExistingInputs() throws Exception {
// Tests calling completeTx with a SendRequest that already has a few inputs in it
// Generate a few outputs to us
StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1);
Transaction tx1 = createFakeTx(TESTNET.network(), COIN, myAddress);
wallet.receiveFromBlock(tx1, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
Transaction tx2 = createFakeTx(TESTNET.network(), COIN, myAddress);
assertNotEquals(tx1.getTxId(), tx2.getTxId());
wallet.receiveFromBlock(tx2, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 1);
Transaction tx3 = createFakeTx(TESTNET.network(), CENT, myAddress);
wallet.receiveFromBlock(tx3, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 2);
SendRequest request1 = SendRequest.to(OTHER_ADDRESS, CENT);
// If we just complete as-is, we will use one of the COIN outputs to get higher priority,
// resulting in a change output
request1.shuffleOutputs = false;
wallet.completeTx(request1);
assertEquals(1, request1.tx.getInputs().size());
assertEquals(2, request1.tx.getOutputs().size());
assertEquals(CENT, request1.tx.getOutput(0).getValue());
assertEquals(COIN.subtract(CENT), request1.tx.getOutput(1).getValue());
// Now create an identical request2 and add an unsigned spend of the CENT output
SendRequest request2 = SendRequest.to(OTHER_ADDRESS, CENT);
request2.tx.addInput(tx3.getOutput(0));
// Now completeTx will result in one input, one output
wallet.completeTx(request2);
assertEquals(1, request2.tx.getInputs().size());
assertEquals(1, request2.tx.getOutputs().size());
assertEquals(CENT, request2.tx.getOutput(0).getValue());
// Make sure it was properly signed
request2.tx.getInput(0).getScriptSig().correctlySpends(
request2.tx, 0, null, null, tx3.getOutput(0).getScriptPubKey(), Script.ALL_VERIFY_FLAGS);
// However, if there is no connected output, we connect it
SendRequest request3 = SendRequest.to(OTHER_ADDRESS, CENT);
request3.tx.addInput(new TransactionInput(request3.tx, new byte[] {}, new TransactionOutPoint(0, tx3.getTxId())));
// Now completeTx will find the matching UTXO from the wallet and add its value to the unconnected input
request3.shuffleOutputs = false;
wallet.completeTx(request3);
assertEquals(1, request3.tx.getInputs().size());
assertEquals(1, request3.tx.getOutputs().size());
assertEquals(CENT, request3.tx.getOutput(0).getValue());
SendRequest request4 = SendRequest.to(OTHER_ADDRESS, CENT);
request4.tx.addInput(tx3.getOutput(0));
// Now if we manually sign it, completeTx will not replace our signature
wallet.signTransaction(request4);
byte[] scriptSig = request4.tx.getInput(0).getScriptBytes();
wallet.completeTx(request4);
assertEquals(1, request4.tx.getInputs().size());
assertEquals(1, request4.tx.getOutputs().size());
assertEquals(CENT, request4.tx.getOutput(0).getValue());
assertArrayEquals(scriptSig, request4.tx.getInput(0).getScriptBytes());
}
@Test
public void testCompleteTxWithUnconnectedExistingInput() throws Exception {
// Test calling completeTx with a SendRequest that has an unconnected input (i.e. an input with an unconnected outpoint)
// Generate an output to us
StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1);
Transaction tx = createFakeTx(TESTNET.network(), COIN, myAddress);
wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
// SendRequest using that output as an unconnected input
SendRequest request = SendRequest.to(OTHER_ADDRESS, COIN);
request.tx.addInput(new TransactionInput(request.tx, new byte[] {}, new TransactionOutPoint(0, tx.getTxId())));
// Complete the transaction
wallet.completeTx(request);
// Make sure it has no duplicate inputs
assertEquals(uniqueOutPoints(request.tx.getInputs()), request.tx.getInputs().size());
}
// Count unique TransactionOutPoints in a list of TransactionInputs
private long uniqueOutPoints(List<TransactionInput> inputs) {
return inputs.stream()
.map(TransactionInput::getOutpoint)
.distinct()
.count();
}
// There is a test for spending a coinbase transaction as it matures in BlockChainTest#coinbaseTransactionAvailability
// Support for offline spending is tested in PeerGroupTest
@Test
public void exceptionsDoNotBlockAllListeners() {
// Check that if a wallet listener throws an exception, the others still run.
wallet.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> {
log.info("onCoinsReceived 1");
throw new RuntimeException("barf");
});
final AtomicInteger flag = new AtomicInteger();
wallet.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> {
log.info("onCoinsReceived 2");
flag.incrementAndGet();
});
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN);
log.info("Wait for user thread");
Threading.waitForUserCode();
log.info("... and test flag.");
assertEquals(1, flag.get());
}
@Test
public void testEmptyRandomWallet() throws Exception {
// Add a random set of outputs
StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1);
Random rng = new Random();
for (int i = 0; i < rng.nextInt(100) + 1; i++) {
Transaction tx = createFakeTx(TESTNET.network(), Coin.valueOf(rng.nextInt((int) COIN.value)), myAddress);
wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, i);
}
SendRequest request = SendRequest.emptyWallet(OTHER_ADDRESS);
wallet.completeTx(request);
wallet.commitTx(request.tx);
assertEquals(ZERO, wallet.getBalance());
}
@Test
public void testEmptyWallet() throws Exception {
// Add exactly 0.01
StoredBlock block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 1);
Transaction tx = createFakeTx(TESTNET.network(), CENT, myAddress);
wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
SendRequest request = SendRequest.emptyWallet(OTHER_ADDRESS);
wallet.completeTx(request);
assertEquals(ZERO, request.tx.getFee());
wallet.commitTx(request.tx);
assertEquals(ZERO, wallet.getBalance());
assertEquals(CENT, request.tx.getOutput(0).getValue());
// Add 1 confirmed cent and 1 unconfirmed cent. Verify only one cent is emptied because of the coin selection
// policies that are in use by default.
block = new StoredBlock(makeSolvedTestBlock(blockStore, OTHER_ADDRESS), BigInteger.ONE, 2);
tx = createFakeTx(TESTNET.network(), CENT, myAddress);
wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
tx = createFakeTx(TESTNET.network(), CENT, myAddress);
wallet.receivePending(tx, null);
request = SendRequest.emptyWallet(OTHER_ADDRESS);
wallet.completeTx(request);
assertEquals(ZERO, request.tx.getFee());
wallet.commitTx(request.tx);
assertEquals(ZERO, wallet.getBalance());
assertEquals(CENT, request.tx.getOutput(0).getValue());
// Add an unsendable value
block = new StoredBlock(block.getHeader().createNextBlock(OTHER_ADDRESS), BigInteger.ONE, 3);
Coin dustThresholdMinusOne = new TransactionOutput(null, Coin.COIN, OTHER_ADDRESS).getMinNonDustValue().subtract(SATOSHI);
tx = createFakeTx(TESTNET.network(), dustThresholdMinusOne, myAddress);
wallet.receiveFromBlock(tx, block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 0);
try {
request = SendRequest.emptyWallet(OTHER_ADDRESS);
wallet.completeTx(request);
assertEquals(ZERO, request.tx.getFee());
fail();
} catch (Wallet.CouldNotAdjustDownwards e) {}
}
@Test
public void childPaysForParent() {
// Receive confirmed balance to play with.
Transaction toMe = createFakeTxWithoutChangeAddress(COIN, myAddress);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, toMe);
assertEquals(Coin.COIN, wallet.getBalance(BalanceType.ESTIMATED_SPENDABLE));
assertEquals(Coin.COIN, wallet.getBalance(BalanceType.AVAILABLE_SPENDABLE));
// Receive unconfirmed coin without fee.
Transaction toMeWithoutFee = createFakeTxWithoutChangeAddress(COIN, myAddress);
wallet.receivePending(toMeWithoutFee, null);
assertEquals(Coin.COIN.multiply(2), wallet.getBalance(BalanceType.ESTIMATED_SPENDABLE));
assertEquals(Coin.COIN, wallet.getBalance(BalanceType.AVAILABLE_SPENDABLE));
// Craft a child-pays-for-parent transaction.
final Coin feeRaise = MILLICOIN;
final SendRequest sendRequest = SendRequest.childPaysForParent(wallet, toMeWithoutFee, feeRaise);
wallet.signTransaction(sendRequest);
wallet.commitTx(sendRequest.tx);
assertEquals(Transaction.Purpose.RAISE_FEE, sendRequest.tx.getPurpose());
assertEquals(Coin.COIN.multiply(2).subtract(feeRaise), wallet.getBalance(BalanceType.ESTIMATED_SPENDABLE));
assertEquals(Coin.COIN, wallet.getBalance(BalanceType.AVAILABLE_SPENDABLE));
}
@Test
public void keyRotationRandom() throws Exception {
TimeUtils.setMockClock();
// Start with an empty wallet (no HD chain).
wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
// Watch out for wallet-initiated broadcasts.
MockTransactionBroadcaster broadcaster = new MockTransactionBroadcaster(wallet);
// Send three cents to two different random keys, then add a key and mark the initial keys as compromised.
ECKey key1 = new ECKey();
key1.setCreationTime(TimeUtils.currentTime().minusSeconds(86400 * 2));
ECKey key2 = new ECKey();
key2.setCreationTime(TimeUtils.currentTime().minusSeconds(86400));
wallet.importKey(key1);
wallet.importKey(key2);
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, key1.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, key2.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, key2.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
Instant compromiseTime = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS);
assertEquals(0, broadcaster.size());
assertFalse(wallet.isKeyRotating(key1));
// We got compromised!
TimeUtils.rollMockClock(Duration.ofSeconds(1));
wallet.setKeyRotationTime(compromiseTime);
assertTrue(wallet.isKeyRotating(key1));
wallet.doMaintenance(null, true);
Transaction tx = broadcaster.waitForTransactionAndSucceed();
final Coin THREE_CENTS = CENT.add(CENT).add(CENT);
assertEquals(Coin.valueOf(49100), tx.getFee());
assertEquals(THREE_CENTS, tx.getValueSentFromMe(wallet));
assertEquals(THREE_CENTS.subtract(tx.getFee()), tx.getValueSentToMe(wallet));
// TX sends to one of our addresses (for now we ignore married wallets).
final Address toAddress = tx.getOutput(0).getScriptPubKey().getToAddress(BitcoinNetwork.TESTNET);
final ECKey rotatingToKey = wallet.findKeyFromPubKeyHash(toAddress.getHash(), toAddress.getOutputScriptType());
assertNotNull(rotatingToKey);
assertFalse(wallet.isKeyRotating(rotatingToKey));
assertEquals(3, tx.getInputs().size());
// It confirms.
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx);
// Now receive some more money to the newly derived address via a new block and check that nothing happens.
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, toAddress);
assertTrue(wallet.doMaintenance(null, true).get().isEmpty());
assertEquals(0, broadcaster.size());
// Receive money via a new block on key1 and ensure it shows up as a maintenance task.
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, key1.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
wallet.doMaintenance(null, true);
tx = broadcaster.waitForTransactionAndSucceed();
assertNotNull(wallet.findKeyFromPubKeyHash(tx.getOutput(0).getScriptPubKey().getPubKeyHash(),
toAddress.getOutputScriptType()));
log.info("Unexpected thing: {}", tx);
assertEquals(Coin.valueOf(19300), tx.getFee());
assertEquals(1, tx.getInputs().size());
assertEquals(1, tx.getOutputs().size());
assertEquals(CENT, tx.getValueSentFromMe(wallet));
assertEquals(CENT.subtract(tx.getFee()), tx.getValueSentToMe(wallet));
assertEquals(Transaction.Purpose.KEY_ROTATION, tx.getPurpose());
// We don't attempt to race an attacker against unconfirmed transactions.
// Now round-trip the wallet and check the protobufs are storing the data correctly.
wallet = roundTrip(wallet);
tx = wallet.getTransaction(tx.getTxId());
Objects.requireNonNull(tx);
assertEquals(Transaction.Purpose.KEY_ROTATION, tx.getPurpose());
// Have to divide here to avoid mismatch due to second-level precision in serialisation.
assertEquals(compromiseTime, wallet.keyRotationTime().get());
// Make a normal spend and check it's all ok.
wallet.sendCoins(broadcaster, OTHER_ADDRESS, wallet.getBalance());
tx = broadcaster.waitForTransaction();
assertArrayEquals(OTHER_ADDRESS.getHash(), tx.getOutput(0).getScriptPubKey().getPubKeyHash());
}
private Wallet roundTrip(Wallet wallet) throws UnreadableWalletException {
int numActiveKeyChains = wallet.getActiveKeyChains().size();
DeterministicKeyChain activeKeyChain = wallet.getActiveKeyChain();
int numKeys = activeKeyChain.getKeys(false, true).size();
int numIssuedInternal = activeKeyChain.getIssuedInternalKeys();
int numIssuedExternal = activeKeyChain.getIssuedExternalKeys();
DeterministicKey rootKey = wallet.getActiveKeyChain().getRootKey();
DeterministicKey watchingKey = activeKeyChain.getWatchingKey();
HDPath accountPath = activeKeyChain.getAccountPath();
ScriptType outputScriptType = activeKeyChain.getOutputScriptType();
Protos.Wallet protos = new WalletProtobufSerializer().walletToProto(wallet);
Wallet roundTrippedWallet = new WalletProtobufSerializer().readWallet(BitcoinNetwork.TESTNET, null, protos);
assertEquals(numActiveKeyChains, roundTrippedWallet.getActiveKeyChains().size());
DeterministicKeyChain roundTrippedActiveKeyChain = roundTrippedWallet.getActiveKeyChain();
assertEquals(numKeys, roundTrippedActiveKeyChain.getKeys(false, true).size());
assertEquals(numIssuedInternal, roundTrippedActiveKeyChain.getIssuedInternalKeys());
assertEquals(numIssuedExternal, roundTrippedActiveKeyChain.getIssuedExternalKeys());
assertEquals(rootKey, roundTrippedWallet.getActiveKeyChain().getRootKey());
assertEquals(watchingKey, roundTrippedActiveKeyChain.getWatchingKey());
assertEquals(accountPath, roundTrippedActiveKeyChain.getAccountPath());
assertEquals(outputScriptType, roundTrippedActiveKeyChain.getOutputScriptType());
return roundTrippedWallet;
}
@Test
public void keyRotationHD() throws Exception {
// Test that if we rotate an HD chain, a new one is created and all arrivals on the old keys are moved.
TimeUtils.setMockClock();
wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
ECKey key1 = wallet.freshReceiveKey();
ECKey key2 = wallet.freshReceiveKey();
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, key1.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
sendMoneyToWallet(wallet, AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, key2.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
DeterministicKey watchKey1 = wallet.getWatchingKey();
// A day later, we get compromised.
TimeUtils.rollMockClock(Duration.ofDays(1));
wallet.setKeyRotationTime(TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS));
List<Transaction> txns = wallet.doMaintenance(null, false).get();
assertEquals(1, txns.size());
DeterministicKey watchKey2 = wallet.getWatchingKey();
assertNotEquals(watchKey1, watchKey2);
}
@Test(expected = IllegalArgumentException.class)
public void importOfHDKeyForbidden() {
wallet.importKey(wallet.freshReceiveKey());
}
//@Test //- this test is slow, disable for now.
public void fragmentedReKeying() {
// Send lots of small coins and check the fee is correct.
ECKey key = wallet.freshReceiveKey();
Address address = key.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
TimeUtils.setMockClock();
TimeUtils.rollMockClock(Duration.ofDays(1));
for (int i = 0; i < 800; i++) {
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, address);
}
MockTransactionBroadcaster broadcaster = new MockTransactionBroadcaster(wallet);
Instant compromise = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS);
TimeUtils.rollMockClock(Duration.ofDays(1));
wallet.freshReceiveKey();
wallet.setKeyRotationTime(compromise);
wallet.doMaintenance(null, true);
Transaction tx = broadcaster.waitForTransactionAndSucceed();
final Coin valueSentToMe = tx.getValueSentToMe(wallet);
Coin fee = tx.getValueSentFromMe(wallet).subtract(valueSentToMe);
assertEquals(Coin.valueOf(900000), fee);
assertEquals(KeyTimeCoinSelector.MAX_SIMULTANEOUS_INPUTS, tx.getInputs().size());
assertEquals(Coin.valueOf(599100000), valueSentToMe);
tx = broadcaster.waitForTransaction();
assertNotNull(tx);
assertEquals(200, tx.getInputs().size());
}
private static final byte[] EMPTY_SIG = {};
@Test
public void completeTxPartiallySignedWithDummySigs() throws Exception {
byte[] dummySig = TransactionSignature.dummy().encodeToBitcoin();
completeTxPartiallySigned(Wallet.MissingSigsMode.USE_DUMMY_SIG, dummySig);
}
@Test
public void completeTxPartiallySignedWithEmptySig() throws Exception {
completeTxPartiallySigned(Wallet.MissingSigsMode.USE_OP_ZERO, EMPTY_SIG);
}
@Test (expected = ECKey.MissingPrivateKeyException.class)
public void completeTxPartiallySignedThrows() throws Exception {
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, myKey);
SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
wallet.completeTx(req);
// Delete the sigs
for (TransactionInput input : req.tx.getInputs())
input.clearScriptBytes();
Wallet watching = Wallet.fromWatchingKey(TESTNET.network(), wallet.getWatchingKey().dropParent().dropPrivateBytes(),
ScriptType.P2PKH);
watching.freshReceiveKey();
watching.completeTx(SendRequest.forTx(req.tx));
}
@SuppressWarnings("ConstantConditions")
public void completeTxPartiallySigned(Wallet.MissingSigsMode missSigMode, byte[] expectedSig) throws Exception {
// Check the wallet will write dummy scriptSigs for inputs that we have only pubkeys for without the privkey.
ECKey priv = new ECKey();
ECKey pub = ECKey.fromPublicOnly(priv);
wallet.importKey(pub);
ECKey priv2 = wallet.freshReceiveKey();
// Send three transactions, with one being an address type and the other being a raw CHECKSIG type pubkey only,
// and the final one being a key we do have. We expect the first two inputs to be dummy values and the last
// to be signed correctly.
Transaction t1 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, pub.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET));
Transaction t2 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, pub);
Transaction t3 = sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT, priv2);
SendRequest req = SendRequest.emptyWallet(OTHER_ADDRESS);
req.missingSigsMode = missSigMode;
wallet.completeTx(req);
byte[] dummySig = TransactionSignature.dummy().encodeToBitcoin();
// Selected inputs can be in any order.
for (int i = 0; i < req.tx.getInputs().size(); i++) {
TransactionInput input = req.tx.getInput(i);
if (input.getConnectedOutput().getParentTransaction().equals(t1)) {
assertArrayEquals(expectedSig, input.getScriptSig().chunks().get(0).data);
} else if (input.getConnectedOutput().getParentTransaction().equals(t2)) {
assertArrayEquals(expectedSig, input.getScriptSig().chunks().get(0).data);
} else if (input.getConnectedOutput().getParentTransaction().equals(t3)) {
input.getScriptSig().correctlySpends(
req.tx, i, null, null, t3.getOutput(0).getScriptPubKey(), Script.ALL_VERIFY_FLAGS);
}
}
assertTrue(TransactionSignature.isEncodingCanonical(dummySig));
}
@Test
public void riskAnalysis() {
// Send a tx that is considered risky to the wallet, verify it doesn't show up in the balances.
final Transaction tx = createFakeTx(TESTNET.network(), COIN, myAddress);
final AtomicBoolean bool = new AtomicBoolean();
wallet.setRiskAnalyzer((wallet, wtx, dependencies) -> {
RiskAnalysis.Result result = RiskAnalysis.Result.OK;
if (wtx.getTxId().equals(tx.getTxId()))
result = RiskAnalysis.Result.NON_STANDARD;
final RiskAnalysis.Result finalResult = result;
return () -> {
bool.set(true);
return finalResult;
};
});
assertTrue(wallet.isPendingTransactionRelevant(tx));
assertEquals(Coin.ZERO, wallet.getBalance());
assertEquals(Coin.ZERO, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
wallet.receivePending(tx, null);
assertEquals(Coin.ZERO, wallet.getBalance());
assertEquals(Coin.ZERO, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
assertTrue(bool.get());
// Confirm it in the same manner as how Bloom filtered blocks do. Verify it shows up.
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx);
assertEquals(COIN, wallet.getBalance());
}
@Test
public void transactionInBlockNotification() {
final Transaction tx = createFakeTx(TESTNET.network(), COIN, myAddress);
StoredBlock block = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS, tx).storedBlock;
wallet.receivePending(tx, null);
boolean notification = wallet.notifyTransactionIsInBlock(tx.getTxId(), block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 1);
assertTrue(notification);
final Transaction tx2 = createFakeTx(TESTNET.network(), COIN, OTHER_ADDRESS);
wallet.receivePending(tx2, null);
StoredBlock block2 = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS + 1, tx2).storedBlock;
boolean notification2 = wallet.notifyTransactionIsInBlock(tx2.getTxId(), block2, AbstractBlockChain.NewBlockType.BEST_CHAIN, 1);
assertFalse(notification2);
}
@Test
public void duplicatedBlock() {
final Transaction tx = createFakeTx(TESTNET.network(), COIN, myAddress);
StoredBlock block = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS, tx).storedBlock;
wallet.notifyNewBestBlock(block);
wallet.notifyNewBestBlock(block);
}
@Test
public void keyEvents() {
// Check that we can register an event listener, generate some keys and the callbacks are invoked properly.
wallet = new Wallet(BitcoinNetwork.TESTNET, KeyChainGroup.builder(BitcoinNetwork.TESTNET).fromRandom(ScriptType.P2PKH).build());
final List<ECKey> keys = new LinkedList<>();
wallet.addKeyChainEventListener(Threading.SAME_THREAD, keys::addAll);
wallet.freshReceiveKey();
assertEquals(1, keys.size());
}
@Test
public void upgradeToDeterministic_P2PKH_to_P2WPKH_unencrypted() {
wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
assertFalse(wallet.isEncrypted());
assertFalse(wallet.isDeterministicUpgradeRequired(ScriptType.P2PKH));
assertTrue(wallet.isDeterministicUpgradeRequired(ScriptType.P2WPKH));
assertEquals(ScriptType.P2PKH, wallet.currentReceiveAddress().getOutputScriptType());
assertEquals(ScriptType.P2PKH, wallet.freshReceiveAddress().getOutputScriptType());
wallet.upgradeToDeterministic(ScriptType.P2WPKH, null);
assertFalse(wallet.isEncrypted());
assertFalse(wallet.isDeterministicUpgradeRequired(ScriptType.P2PKH));
assertFalse(wallet.isDeterministicUpgradeRequired(ScriptType.P2WPKH));
assertEquals(ScriptType.P2WPKH, wallet.currentReceiveAddress().getOutputScriptType());
assertEquals(ScriptType.P2WPKH, wallet.freshReceiveAddress().getOutputScriptType());
}
@Test
public void upgradeToDeterministic_P2PKH_to_P2WPKH_encrypted() {
wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
assertFalse(wallet.isEncrypted());
assertFalse(wallet.isDeterministicUpgradeRequired(ScriptType.P2PKH));
assertTrue(wallet.isDeterministicUpgradeRequired(ScriptType.P2WPKH));
AesKey aesKey = new KeyCrypterScrypt(SCRYPT_ITERATIONS).deriveKey("abc");
wallet.encrypt(new KeyCrypterScrypt(), aesKey);
assertTrue(wallet.isEncrypted());
assertEquals(ScriptType.P2PKH, wallet.currentReceiveAddress().getOutputScriptType());
assertEquals(ScriptType.P2PKH, wallet.freshReceiveAddress().getOutputScriptType());
try {
wallet.upgradeToDeterministic(ScriptType.P2WPKH, null);
fail();
} catch (DeterministicUpgradeRequiresPassword e) {
// Expected.
}
wallet.upgradeToDeterministic(ScriptType.P2WPKH, aesKey);
assertTrue(wallet.isEncrypted());
assertFalse(wallet.isDeterministicUpgradeRequired(ScriptType.P2PKH));
assertFalse(wallet.isDeterministicUpgradeRequired(ScriptType.P2WPKH));
assertEquals(ScriptType.P2WPKH, wallet.currentReceiveAddress().getOutputScriptType());
assertEquals(ScriptType.P2WPKH, wallet.freshReceiveAddress().getOutputScriptType());
}
@Test
public void upgradeToDeterministic_noDowngrade_unencrypted() {
wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2WPKH);
assertFalse(wallet.isEncrypted());
assertFalse(wallet.isDeterministicUpgradeRequired(ScriptType.P2PKH));
assertFalse(wallet.isDeterministicUpgradeRequired(ScriptType.P2WPKH));
assertEquals(ScriptType.P2WPKH, wallet.currentReceiveAddress().getOutputScriptType());
assertEquals(ScriptType.P2WPKH, wallet.freshReceiveAddress().getOutputScriptType());
wallet.upgradeToDeterministic(ScriptType.P2PKH, null);
assertFalse(wallet.isEncrypted());
assertFalse(wallet.isDeterministicUpgradeRequired(ScriptType.P2PKH));
assertFalse(wallet.isDeterministicUpgradeRequired(ScriptType.P2WPKH));
assertEquals(ScriptType.P2WPKH, wallet.currentReceiveAddress().getOutputScriptType());
assertEquals(ScriptType.P2WPKH, wallet.freshReceiveAddress().getOutputScriptType());
}
@Test(expected = IllegalStateException.class)
public void shouldNotAddTransactionSignerThatIsNotReady() {
wallet.addTransactionSigner(new NopTransactionSigner(false));
}
@Test
public void sendRequestExchangeRate() throws Exception {
receiveATransaction(wallet, myAddress);
SendRequest sendRequest = SendRequest.to(myAddress, Coin.COIN);
sendRequest.exchangeRate = new ExchangeRate(Fiat.parseFiat("EUR", "500"));
wallet.completeTx(sendRequest);
assertEquals(sendRequest.exchangeRate, sendRequest.tx.getExchangeRate());
}
@Test
public void sendRequestMemo() throws Exception {
receiveATransaction(wallet, myAddress);
SendRequest sendRequest = SendRequest.to(myAddress, Coin.COIN);
sendRequest.memo = "memo";
wallet.completeTx(sendRequest);
assertEquals(sendRequest.memo, sendRequest.tx.getMemo());
}
@Test(expected = java.lang.IllegalStateException.class)
public void sendCoinsNoBroadcasterTest() throws InsufficientMoneyException {
ECKey key = ECKey.fromPrivate(BigInteger.TEN);
SendRequest req = SendRequest.to(key, SATOSHI.multiply(12));
wallet.sendCoins(req);
}
@Test
public void sendCoinsWithBroadcasterTest() throws InsufficientMoneyException {
ECKey key = ECKey.fromPrivate(BigInteger.TEN);
receiveATransactionAmount(wallet, myAddress, Coin.COIN);
MockTransactionBroadcaster broadcaster = new MockTransactionBroadcaster(wallet);
wallet.setTransactionBroadcaster(broadcaster);
SendRequest req = SendRequest.to(key, Coin.CENT);
wallet.sendCoins(req);
}
@Test
public void createBasicWithKeys() {
ECKey key = ECKey.fromPrivate(ByteUtils.parseHex("00905b93f990267f4104f316261fc10f9f983551f9ef160854f40102eb71cffdcc"));
Wallet wallet = Wallet.createBasic(BitcoinNetwork.TESTNET);
wallet.importKey(key);
assertEquals(1, wallet.getImportedKeys().size());
assertEquals(key, wallet.getImportedKeys().get(0));
}
@Test
public void reset() {
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN, myAddress);
assertNotEquals(Coin.ZERO, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
assertNotEquals(0, wallet.getTransactions(false).size());
assertNotEquals(0, wallet.getUnspents().size());
wallet.reset();
assertEquals(Coin.ZERO, wallet.getBalance(Wallet.BalanceType.ESTIMATED));
assertEquals(0, wallet.getTransactions(false).size());
assertEquals(0, wallet.getUnspents().size());
}
@Test
public void totalReceivedSent() throws Exception {
// Receive 4 BTC in 2 separate transactions
Transaction toMe1 = createFakeTxWithoutChangeAddress(COIN.multiply(2), myAddress);
Transaction toMe2 = createFakeTxWithoutChangeAddress(COIN.multiply(2), myAddress);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, toMe1, toMe2);
// Check we calculate the total received correctly
assertEquals(Coin.COIN.multiply(4), wallet.getTotalReceived());
// Send 3 BTC in a single transaction
SendRequest req = SendRequest.to(OTHER_ADDRESS, Coin.COIN.multiply(3));
wallet.completeTx(req);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, req.tx);
// Check that we still have the same totalReceived, since the above tx will have sent us change back
assertEquals(Coin.COIN.multiply(4),wallet.getTotalReceived());
assertEquals(Coin.COIN.multiply(3),wallet.getTotalSent());
// TODO: test shared wallet calculation here
}
@Test
public void testIrrelevantDoubleSpend() throws Exception {
Transaction tx0 = createFakeTx(TESTNET.network());
Transaction tx1 = createFakeTx(TESTNET.network());
Transaction tx2 = new Transaction();
tx2.addInput(tx0.getOutput(0));
tx2.addOutput(COIN, myAddress);
tx2.addOutput(COIN, OTHER_ADDRESS);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx2, tx1, tx0);
// tx3 and tx4 double spend each other
Transaction tx3 = new Transaction();
tx3.addInput(tx1.getOutput(0));
tx3.addOutput(COIN, myAddress);
tx3.addOutput(COIN, OTHER_ADDRESS);
wallet.receivePending(tx3, null);
// tx4 also spends irrelevant output from tx2
Transaction tx4 = new Transaction();
tx4.addInput(tx1.getOutput(0)); // spends same output
tx4.addInput(tx2.getOutput(1));
tx4.addOutput(COIN, OTHER_ADDRESS);
// tx4 does not actually get added to wallet here since it by itself is irrelevant
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx4);
// since tx4 is not saved, tx2 output 1 will have bad spentBy
wallet = roundTrip(wallet);
assertTrue(wallet.isConsistent());
}
@Test
public void overridingDeadTxTest() throws Exception {
Transaction tx0 = createFakeTx(TESTNET.network());
Transaction tx1 = new Transaction();
tx1.addInput(tx0.getOutput(0));
tx1.addOutput(COIN, OTHER_ADDRESS);
tx1.addOutput(COIN, OTHER_ADDRESS);
tx1.addOutput(COIN, myAddress); // to save this in wallet
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx0, tx1);
// tx2, tx3 and tx4 double spend each other
Transaction tx2 = new Transaction();
tx2.addInput(tx1.getOutput(0));
tx2.addInput(tx1.getOutput(1));
tx2.addOutput(COIN, myAddress);
tx2.addOutput(COIN, OTHER_ADDRESS);
wallet.receivePending(tx2, null);
// irrelevant to the wallet
Transaction tx3 = new Transaction();
tx3.addInput(tx1.getOutput(0)); // spends same output as tx2
tx3.addOutput(COIN, OTHER_ADDRESS);
// irrelevant to the wallet
Transaction tx4 = new Transaction();
tx4.addInput(tx1.getOutput(1)); // spends different output, but also in tx2
tx4.addOutput(COIN, OTHER_ADDRESS);
assertUnspent(tx1);
assertPending(tx2);
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx3);
assertUnspent(tx1);
assertDead(tx2);
assertEquals(2, wallet.transactions.size()); // tx3 not saved
sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, tx4);
assertUnspent(tx1);
assertDead(tx2);
assertEquals(2, wallet.transactions.size()); // tx4 not saved
// this will fail if tx4 does not get disconnected from tx1
wallet = roundTrip(wallet);
assertTrue(wallet.isConsistent());
}
@Test
public void scriptTypeKeyChainRestrictions() {
// Set up chains: basic chain, P2PKH deterministric chain, P2WPKH deterministic chain.
DeterministicKeyChain p2pkhChain = DeterministicKeyChain.builder().random(new SecureRandom())
.outputScriptType(ScriptType.P2PKH).build();
DeterministicKeyChain p2wpkhChain = DeterministicKeyChain.builder().random(new SecureRandom())
.outputScriptType(ScriptType.P2WPKH).build();
KeyChainGroup kcg = KeyChainGroup.builder(BitcoinNetwork.TESTNET).addChain(p2pkhChain).addChain(p2wpkhChain).build();
Wallet wallet = new Wallet(BitcoinNetwork.TESTNET, kcg);
// Set up one key from each chain.
ECKey importedKey = new ECKey();
wallet.importKey(importedKey);
ECKey p2pkhKey = p2pkhChain.getKey(KeyPurpose.RECEIVE_FUNDS);
ECKey p2wpkhKey = p2wpkhChain.getKey(KeyPurpose.RECEIVE_FUNDS);
// Test imported key: it's not limited to script type.
assertTrue(wallet.isAddressMine(importedKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)));
assertTrue(wallet.isAddressMine(importedKey.toAddress(ScriptType.P2WPKH, BitcoinNetwork.TESTNET)));
assertEquals(importedKey, wallet.findKeyFromAddress(importedKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)));
assertEquals(importedKey, wallet.findKeyFromAddress(importedKey.toAddress(ScriptType.P2WPKH, BitcoinNetwork.TESTNET)));
// Test key from P2PKH chain: it's limited to P2PKH addresses
assertTrue(wallet.isAddressMine(p2pkhKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)));
assertFalse(wallet.isAddressMine(p2pkhKey.toAddress(ScriptType.P2WPKH, BitcoinNetwork.TESTNET)));
assertEquals(p2pkhKey, wallet.findKeyFromAddress(p2pkhKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)));
assertNull(wallet.findKeyFromAddress(p2pkhKey.toAddress(ScriptType.P2WPKH, BitcoinNetwork.TESTNET)));
// Test key from P2WPKH chain: it's limited to P2WPKH addresses
assertFalse(wallet.isAddressMine(p2wpkhKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)));
assertTrue(wallet.isAddressMine(p2wpkhKey.toAddress(ScriptType.P2WPKH, BitcoinNetwork.TESTNET)));
assertNull(wallet.findKeyFromAddress(p2wpkhKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)));
assertEquals(p2wpkhKey, wallet.findKeyFromAddress(p2wpkhKey.toAddress(ScriptType.P2WPKH, BitcoinNetwork.TESTNET)));
}
@Test
public void roundtripViaMnemonicCode() {
Wallet wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2WPKH);
List<String> mnemonicCode = wallet.getKeyChainSeed().getMnemonicCode();
final DeterministicSeed clonedSeed = DeterministicSeed.ofMnemonic(mnemonicCode, "",
wallet.earliestKeyCreationTime());
Wallet clone = Wallet.fromSeed(BitcoinNetwork.TESTNET, clonedSeed, ScriptType.P2WPKH);
assertEquals(wallet.currentReceiveKey(), clone.currentReceiveKey());
assertEquals(wallet.freshReceiveAddress(ScriptType.P2PKH),
clone.freshReceiveAddress(ScriptType.P2PKH));
}
@Test
public void oneTxTwoWallets() {
Wallet wallet1 = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2WPKH);
Wallet wallet2 = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2WPKH);
Address address1 = wallet1.freshReceiveAddress(ScriptType.P2PKH);
Address address2 = wallet2.freshReceiveAddress(ScriptType.P2PKH);
// Both wallet1 and wallet2 receive coins in the same tx
Transaction tx0 = createFakeTx(TESTNET.network());
Transaction tx1 = new Transaction();
tx1.addInput(tx0.getOutput(0));
tx1.addOutput(COIN, address1); // to wallet1
tx1.addOutput(COIN, address2); // to wallet2
tx1.addOutput(COIN, OTHER_ADDRESS);
wallet1.receivePending(tx1, null);
wallet2.receivePending(tx1, null);
// Confirm transactions in both wallets
StoredBlock block = createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS, tx1).storedBlock;
wallet1.notifyTransactionIsInBlock(tx1.getTxId(), block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 1);
wallet2.notifyTransactionIsInBlock(tx1.getTxId(), block, AbstractBlockChain.NewBlockType.BEST_CHAIN, 1);
assertEquals(COIN, wallet1.getTotalReceived());
assertEquals(COIN, wallet2.getTotalReceived());
// Spend two outputs from the same tx from two different wallets
SendRequest sendReq = SendRequest.to(OTHER_ADDRESS, valueOf(2, 0));
sendReq.tx.addInput(tx1.getOutput(0));
sendReq.tx.addInput(tx1.getOutput(1));
// Wallet1 sign input 0
TransactionInput inputW1 = sendReq.tx.getInput(0);
ECKey sigKey1 = inputW1.getOutpoint().getConnectedKey(wallet1);
Script scriptCode1 = ScriptBuilder.createP2PKHOutputScript(sigKey1);
TransactionSignature txSig1 = sendReq.tx.calculateWitnessSignature(0, sigKey1, scriptCode1,
inputW1.getValue(), Transaction.SigHash.ALL, false);
inputW1.setScriptSig(ScriptBuilder.createEmpty());
inputW1.setWitness(TransactionWitness.redeemP2WPKH(txSig1, sigKey1));
// Wallet2 sign input 1
TransactionInput inputW2 = sendReq.tx.getInput(1);
ECKey sigKey2 = inputW2.getOutpoint().getConnectedKey(wallet2);
Script scriptCode2 = ScriptBuilder.createP2PKHOutputScript(sigKey2);
TransactionSignature txSig2 = sendReq.tx.calculateWitnessSignature(0, sigKey2, scriptCode2,
inputW2.getValue(), Transaction.SigHash.ALL, false);
inputW2.setScriptSig(ScriptBuilder.createEmpty());
inputW2.setWitness(TransactionWitness.redeemP2WPKH(txSig2, sigKey2));
wallet1.commitTx(sendReq.tx);
wallet2.commitTx(sendReq.tx);
assertEquals(ZERO, wallet1.getBalance());
assertEquals(ZERO, wallet2.getBalance());
assertTrue(wallet1.isConsistent());
assertTrue(wallet2.isConsistent());
Transaction txW1 = wallet1.getTransaction(tx1.getTxId());
Transaction txW2 = wallet2.getTransaction(tx1.getTxId());
assertEquals(txW1, tx1);
assertNotSame(txW1, tx1);
assertEquals(txW2, tx1);
assertNotSame(txW2, tx1);
assertEquals(txW1, txW2);
assertNotSame(txW1, txW2);
}
@Test
public void deprecatedMembers() {
Wallet wallet1 = Wallet.createBasic(TESTNET);
assertEquals(BitcoinNetwork.TESTNET, wallet1.network());
Wallet wallet2 = Wallet.createDeterministic(TESTNET, ScriptType.P2WPKH, KeyChainGroupStructure.BIP43);
assertEquals(BitcoinNetwork.TESTNET, wallet2.network());
Wallet wallet3 = Wallet.createDeterministic(TESTNET, ScriptType.P2WPKH);
assertEquals(BitcoinNetwork.TESTNET, wallet3.network());
Wallet wallet4 = Wallet.fromSeed(TESTNET, DeterministicSeed.ofEntropy(new byte[20], ""), ScriptType.P2WPKH);
assertEquals(BitcoinNetwork.TESTNET, wallet4.network());
Wallet wallet5 = Wallet.fromSeed(TESTNET, DeterministicSeed.ofEntropy(new byte[20], ""), ScriptType.P2WPKH, KeyChainGroupStructure.BIP43);
assertEquals(BitcoinNetwork.TESTNET, wallet5.network());
Wallet wallet6 = Wallet.fromSeed(TESTNET, DeterministicSeed.ofEntropy(new byte[20], ""), ScriptType.P2WPKH, HDPath.BIP44_PARENT);
assertEquals(BitcoinNetwork.TESTNET, wallet6.network());
HDPath accountPath = KeyChainGroupStructure.BIP43.accountPathFor(ScriptType.P2WPKH, BitcoinNetwork.TESTNET);
DeterministicKeyChain keyChain = DeterministicKeyChain.builder()
.random(new SecureRandom())
.accountPath(accountPath)
.build();
DeterministicKey watchingKey = keyChain.getWatchingKey().dropPrivateBytes().dropParent();
Wallet wallet7 = Wallet.fromWatchingKey(TESTNET, watchingKey, ScriptType.P2WPKH);
assertEquals(BitcoinNetwork.TESTNET, wallet7.network());
String watchingKeyb58 = watchingKey.serializePubB58(TESTNET.network());
Wallet wallet8 = Wallet.fromWatchingKeyB58(TESTNET, watchingKeyb58, Instant.ofEpochSecond(1415282801));
assertEquals(BitcoinNetwork.TESTNET, wallet8.network());
Wallet wallet9 = Wallet.fromWatchingKeyB58(TESTNET, watchingKeyb58);
assertEquals(BitcoinNetwork.TESTNET, wallet9.network());
Wallet wallet10 = Wallet.fromWatchingKeyB58(TESTNET, watchingKeyb58, 1415282801);
assertEquals(BitcoinNetwork.TESTNET, wallet10.network());
}
}
| 175,263
| 48.607699
| 155
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/wallet/DefaultRiskAnalysisTest.java
|
/*
* Copyright 2013 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.wallet;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.Coin;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.internal.ByteUtils;
import org.bitcoinj.core.Context;
import org.bitcoinj.core.TransactionOutPoint;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.crypto.TransactionSignature;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.ScriptBuilder;
import org.bitcoinj.script.ScriptChunk;
import org.bitcoinj.testing.FakeTxBuilder;
import org.bitcoinj.wallet.DefaultRiskAnalysis.RuleViolation;
import org.junit.Before;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.bitcoinj.base.Coin.COIN;
import static org.bitcoinj.base.internal.Preconditions.checkState;
import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA1;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
public class DefaultRiskAnalysisTest {
// Uses mainnet because isStandard checks are disabled on testnet.
private static final NetworkParameters MAINNET = MainNetParams.get();
private Wallet wallet;
private final int TIMESTAMP = 1384190189;
private static final ECKey key1 = new ECKey();
private final List<Transaction> NO_DEPS = Collections.emptyList();
@Before
public void setup() {
Context.propagate(new Context());
wallet = Wallet.createDeterministic(BitcoinNetwork.MAINNET, ScriptType.P2PKH);
wallet.setLastBlockSeenHeight(1000);
wallet.setLastBlockSeenTime(Instant.ofEpochSecond(TIMESTAMP));
}
@Test(expected = IllegalStateException.class)
public void analysisCantBeUsedTwice() {
Transaction tx = new Transaction();
DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
assertEquals(RiskAnalysis.Result.OK, analysis.analyze());
assertNull(analysis.getNonFinal());
// Verify we can't re-use a used up risk analysis.
analysis.analyze();
}
@Test
public void nonFinal() {
// Verify that just having a lock time in the future is not enough to be considered risky (it's still final).
Transaction tx = new Transaction();
TransactionInput input = tx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0));
tx.addOutput(COIN, key1);
tx.setLockTime(TIMESTAMP + 86400);
DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
assertEquals(RiskAnalysis.Result.OK, analysis.analyze());
assertNull(analysis.getNonFinal());
// Set a sequence number on the input to make it genuinely non-final. Verify it's risky.
input.setSequenceNumber(TransactionInput.NO_SEQUENCE - 1);
analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
assertEquals(RiskAnalysis.Result.NON_FINAL, analysis.analyze());
assertEquals(tx, analysis.getNonFinal());
// If the lock time is the current block, it's about to become final and we consider it non-risky.
tx.setLockTime(1000);
analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
assertEquals(RiskAnalysis.Result.OK, analysis.analyze());
}
@Test
public void selfCreatedAreNotRisky() {
Transaction tx = new Transaction();
tx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0)).setSequenceNumber(1);
tx.addOutput(COIN, key1);
tx.setLockTime(TIMESTAMP + 86400);
{
// Is risky ...
DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
assertEquals(RiskAnalysis.Result.NON_FINAL, analysis.analyze());
}
tx.getConfidence().setSource(TransactionConfidence.Source.SELF);
{
// Is no longer risky.
DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
assertEquals(RiskAnalysis.Result.OK, analysis.analyze());
}
}
@Test
public void nonFinalDependency() {
// Final tx has a dependency that is non-final.
Transaction tx1 = new Transaction();
tx1.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0)).setSequenceNumber(1);
TransactionOutput output = tx1.addOutput(COIN, key1);
tx1.setLockTime(TIMESTAMP + 86400);
Transaction tx2 = new Transaction();
tx2.addInput(output);
tx2.addOutput(COIN, new ECKey());
DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx2, Collections.singletonList(tx1));
assertEquals(RiskAnalysis.Result.NON_FINAL, analysis.analyze());
assertEquals(tx1, analysis.getNonFinal());
}
@Test
public void nonStandardDust() {
Transaction standardTx = new Transaction();
standardTx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0));
standardTx.addOutput(COIN, key1);
assertEquals(RiskAnalysis.Result.OK, DefaultRiskAnalysis.FACTORY.create(wallet, standardTx, NO_DEPS).analyze());
Transaction dustTx = new Transaction();
dustTx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0));
dustTx.addOutput(Coin.SATOSHI, key1); // 1 Satoshi
assertEquals(RiskAnalysis.Result.NON_STANDARD, DefaultRiskAnalysis.FACTORY.create(wallet, dustTx, NO_DEPS).analyze());
Transaction edgeCaseTx = new Transaction();
edgeCaseTx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0));
Coin dustThreshold = new TransactionOutput(null, Coin.COIN, key1).getMinNonDustValue();
edgeCaseTx.addOutput(dustThreshold, key1);
assertEquals(RiskAnalysis.Result.OK, DefaultRiskAnalysis.FACTORY.create(wallet, edgeCaseTx, NO_DEPS).analyze());
}
@Test
public void nonShortestPossiblePushData() {
ScriptChunk nonStandardChunk = new ScriptChunk(OP_PUSHDATA1, new byte[75]);
byte[] nonStandardScript = new ScriptBuilder().addChunk(nonStandardChunk).build().program();
// Test non-standard script as an input.
Transaction tx = new Transaction();
assertEquals(DefaultRiskAnalysis.RuleViolation.NONE, DefaultRiskAnalysis.isStandard(tx));
tx.addInput(new TransactionInput(null, nonStandardScript, TransactionOutPoint.UNCONNECTED));
assertEquals(DefaultRiskAnalysis.RuleViolation.SHORTEST_POSSIBLE_PUSHDATA, DefaultRiskAnalysis.isStandard(tx));
// Test non-standard script as an output.
tx.clearInputs();
assertEquals(DefaultRiskAnalysis.RuleViolation.NONE, DefaultRiskAnalysis.isStandard(tx));
tx.addOutput(new TransactionOutput(null, COIN, nonStandardScript));
assertEquals(DefaultRiskAnalysis.RuleViolation.SHORTEST_POSSIBLE_PUSHDATA, DefaultRiskAnalysis.isStandard(tx));
}
@Test
public void canonicalSignature() {
TransactionSignature sig = TransactionSignature.dummy();
Script scriptOk = ScriptBuilder.createInputScript(sig);
assertEquals(RuleViolation.NONE,
DefaultRiskAnalysis.isInputStandard(new TransactionInput(null, scriptOk.program(), TransactionOutPoint.UNCONNECTED)));
byte[] sigBytes = sig.encodeToBitcoin();
// Appending a zero byte makes the signature uncanonical without violating DER encoding.
Script scriptUncanonicalEncoding = new ScriptBuilder().data(Arrays.copyOf(sigBytes, sigBytes.length + 1))
.build();
assertEquals(RuleViolation.SIGNATURE_CANONICAL_ENCODING, DefaultRiskAnalysis.isInputStandard(
new TransactionInput(null, scriptUncanonicalEncoding.program(), TransactionOutPoint.UNCONNECTED)));
}
@Test
public void canonicalSignatureLowS() throws Exception {
// First, a synthetic test.
TransactionSignature sig = TransactionSignature.dummy();
Script scriptHighS = ScriptBuilder
.createInputScript(new TransactionSignature(sig.r, ECKey.CURVE.getN().subtract(sig.s)));
assertEquals(RuleViolation.SIGNATURE_CANONICAL_ENCODING, DefaultRiskAnalysis.isInputStandard(
new TransactionInput(null, scriptHighS.program(), TransactionOutPoint.UNCONNECTED)));
// This is a real transaction. Its signatures S component is "low".
Transaction tx1 = Transaction.read(ByteBuffer.wrap(ByteUtils.parseHex(
"010000000200a2be4376b7f47250ad9ad3a83b6aa5eb6a6d139a1f50771704d77aeb8ce76c010000006a4730440220055723d363cd2d4fe4e887270ebdf5c4b99eaf233a5c09f9404f888ec8b839350220763c3794d310b384ce86decfb05787e5bfa5d31983db612a2dde5ffec7f396ae012102ef47e27e0c4bdd6dc83915f185d972d5eb8515c34d17bad584a9312e59f4e0bcffffffff52239451d37757eeacb86d32864ec1ee6b6e131d1e3fee6f1cff512703b71014030000006b483045022100ea266ac4f893d98a623a6fc0e6a961cd5a3f32696721e87e7570a68851917e75022056d75c3b767419f6f6cb8189a0ad78d45971523908dc4892f7594b75fd43a8d00121038bb455ca101ebbb0ecf7f5c01fa1dcb7d14fbf6b7d7ea52ee56f0148e72a736cffffffff0630b15a00000000001976a9146ae477b690cf85f21c2c01e2c8639a5c18dc884e88ac4f260d00000000001976a91498d08c02ab92a671590adb726dddb719695ee12e88ac65753b00000000001976a9140b2eb4ba6d364c82092f25775f56bc10cd92c8f188ac65753b00000000001976a914d1cb414e22081c6ba3a935635c0f1d837d3c5d9188ac65753b00000000001976a914df9d137a0d279471a2796291874c29759071340b88ac3d753b00000000001976a91459f5aa4815e3aa8e1720e8b82f4ac8e6e904e47d88ac00000000")));
assertEquals("2a1c8569b2b01ebac647fb94444d1118d4d00e327456a3c518e40d47d72cd5fe", tx1.getTxId().toString());
assertEquals(RuleViolation.NONE, DefaultRiskAnalysis.isStandard(tx1));
// This tx is the same as the above, except for a "high" S component on the signature of input 1.
// It was part of the Oct 2015 malleability attack.
Transaction tx2 = Transaction.read(ByteBuffer.wrap(ByteUtils.parseHex(
"010000000200a2be4376b7f47250ad9ad3a83b6aa5eb6a6d139a1f50771704d77aeb8ce76c010000006a4730440220055723d363cd2d4fe4e887270ebdf5c4b99eaf233a5c09f9404f888ec8b839350220763c3794d310b384ce86decfb05787e5bfa5d31983db612a2dde5ffec7f396ae012102ef47e27e0c4bdd6dc83915f185d972d5eb8515c34d17bad584a9312e59f4e0bcffffffff52239451d37757eeacb86d32864ec1ee6b6e131d1e3fee6f1cff512703b71014030000006c493046022100ea266ac4f893d98a623a6fc0e6a961cd5a3f32696721e87e7570a68851917e75022100a928a3c4898be60909347e765f52872a613d8aada66c57a8c8791316d2f298710121038bb455ca101ebbb0ecf7f5c01fa1dcb7d14fbf6b7d7ea52ee56f0148e72a736cffffffff0630b15a00000000001976a9146ae477b690cf85f21c2c01e2c8639a5c18dc884e88ac4f260d00000000001976a91498d08c02ab92a671590adb726dddb719695ee12e88ac65753b00000000001976a9140b2eb4ba6d364c82092f25775f56bc10cd92c8f188ac65753b00000000001976a914d1cb414e22081c6ba3a935635c0f1d837d3c5d9188ac65753b00000000001976a914df9d137a0d279471a2796291874c29759071340b88ac3d753b00000000001976a91459f5aa4815e3aa8e1720e8b82f4ac8e6e904e47d88ac00000000")));
assertEquals("dbe4147cf89b89fd9fa6c8ce6a3e2adecb234db094ec88301ae09073ca17d61d", tx2.getTxId().toString());
assertFalse(ECKey.ECDSASignature
.decodeFromDER(Script.parse(tx2.getInput(1).getScriptBytes()).chunks().get(0).data)
.isCanonical());
assertEquals(RuleViolation.SIGNATURE_CANONICAL_ENCODING, DefaultRiskAnalysis.isStandard(tx2));
}
@Test
public void standardOutputs() {
Transaction tx = new Transaction();
tx.addInput(MAINNET.getGenesisBlock().getTransactions().get(0).getOutput(0));
// A pay to address output
tx.addOutput(Coin.CENT, ScriptBuilder.createP2PKHOutputScript(key1));
// A P2PK output
tx.addOutput(Coin.CENT, ScriptBuilder.createP2PKOutputScript(key1));
tx.addOutput(Coin.CENT, ScriptBuilder.createP2PKOutputScript(key1));
// 1-of-2 multisig output.
List<ECKey> keys = Arrays.asList(key1, new ECKey());
tx.addOutput(Coin.CENT, ScriptBuilder.createMultiSigOutputScript(1, keys));
// 2-of-2 multisig output.
tx.addOutput(Coin.CENT, ScriptBuilder.createMultiSigOutputScript(2, keys));
// P2SH
tx.addOutput(Coin.CENT, ScriptBuilder.createP2SHOutputScript(1, keys));
// OP_RETURN
tx.addOutput(Coin.CENT, ScriptBuilder.createOpReturnScript("hi there".getBytes()));
assertEquals(RiskAnalysis.Result.OK, DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS).analyze());
}
@Test
public void optInFullRBF() {
Transaction tx = FakeTxBuilder.createFakeTx(MAINNET.network());
tx.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE - 2);
DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
assertEquals(RiskAnalysis.Result.NON_FINAL, analysis.analyze());
assertEquals(tx, analysis.getNonFinal());
}
@Test
public void relativeLockTime() {
Transaction tx = FakeTxBuilder.createFakeTx(MAINNET.network());
tx.setVersion(2);
checkState(!tx.hasRelativeLockTime());
tx.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE);
DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
assertEquals(RiskAnalysis.Result.OK, analysis.analyze());
tx.getInput(0).setSequenceNumber(0);
analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
assertEquals(RiskAnalysis.Result.NON_FINAL, analysis.analyze());
assertEquals(tx, analysis.getNonFinal());
}
@Test
public void transactionVersions() {
Transaction tx = FakeTxBuilder.createFakeTx(MAINNET.network());
tx.setVersion(1);
DefaultRiskAnalysis analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
assertEquals(RiskAnalysis.Result.OK, analysis.analyze());
tx.setVersion(2);
analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
assertEquals(RiskAnalysis.Result.OK, analysis.analyze());
tx.setVersion(3);
analysis = DefaultRiskAnalysis.FACTORY.create(wallet, tx, NO_DEPS);
assertEquals(RiskAnalysis.Result.NON_STANDARD, analysis.analyze());
assertEquals(tx, analysis.getNonStandard());
}
}
| 15,363
| 53.676157
| 1,042
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/wallet/DefaultCoinSelectorTest.java
|
/*
* Copyright 2013 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.
*/
package org.bitcoinj.wallet;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.core.AbstractBlockChain;
import org.bitcoinj.core.Block;
import org.bitcoinj.base.Coin;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.PeerAddress;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionConfidence;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.params.RegTestParams;
import org.bitcoinj.testing.FakeTxBuilder;
import org.bitcoinj.testing.TestWithWallet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static org.bitcoinj.base.Coin.CENT;
import static org.bitcoinj.base.Coin.COIN;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class DefaultCoinSelectorTest extends TestWithWallet {
private static final NetworkParameters REGTEST = RegTestParams.get();
@Before
@Override
public void setUp() throws Exception {
super.setUp();
TimeUtils.setMockClock(); // Use mock clock
}
@After
@Override
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void selectable() throws Exception {
Transaction t;
t = new Transaction();
t.getConfidence().setConfidenceType(TransactionConfidence.ConfidenceType.PENDING);
assertFalse(DefaultCoinSelector.isSelectable(t, BitcoinNetwork.TESTNET));
t.getConfidence().setSource(TransactionConfidence.Source.SELF);
assertFalse(DefaultCoinSelector.isSelectable(t, BitcoinNetwork.TESTNET));
t.getConfidence().markBroadcastBy(PeerAddress.simple(InetAddress.getByName("1.2.3.4"), TESTNET.getPort()));
assertTrue(DefaultCoinSelector.isSelectable(t, BitcoinNetwork.TESTNET));
t.getConfidence().markBroadcastBy(PeerAddress.simple(InetAddress.getByName("5.6.7.8"), TESTNET.getPort()));
assertTrue(DefaultCoinSelector.isSelectable(t, BitcoinNetwork.TESTNET));
t = new Transaction();
t.getConfidence().setConfidenceType(TransactionConfidence.ConfidenceType.BUILDING);
assertTrue(DefaultCoinSelector.isSelectable(t, BitcoinNetwork.TESTNET));
t = new Transaction();
t.getConfidence().setConfidenceType(TransactionConfidence.ConfidenceType.PENDING);
t.getConfidence().setSource(TransactionConfidence.Source.SELF);
assertTrue(DefaultCoinSelector.isSelectable(t, BitcoinNetwork.REGTEST));
}
@Test
public void depthOrdering() {
// Send two transactions in two blocks on top of each other.
Transaction t1 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
Transaction t2 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
// Check we selected just the oldest one.
CoinSelector selector = wallet.getCoinSelector();
CoinSelection selection = selector.select(COIN, wallet.calculateAllSpendCandidates());
assertTrue(selection.outputs().contains(t1.getOutput(0)));
assertEquals(COIN, selection.totalValue());
// Check we ordered them correctly (by depth).
ArrayList<TransactionOutput> candidates = new ArrayList<>();
candidates.add(t2.getOutput(0));
candidates.add(t1.getOutput(0));
DefaultCoinSelector.sortOutputs(candidates);
assertEquals(t1.getOutput(0), candidates.get(0));
assertEquals(t2.getOutput(0), candidates.get(1));
}
@Test
public void coinAgeOrdering() {
// Send three transactions in four blocks on top of each other. Coin age of t1 is 1*4=4, coin age of t2 = 2*2=4
// and t3=0.01.
Transaction t1 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, COIN));
// Padding block.
wallet.notifyNewBestBlock(FakeTxBuilder.createFakeBlock(blockStore, Block.BLOCK_HEIGHT_GENESIS).storedBlock);
final Coin TWO_COINS = COIN.multiply(2);
Transaction t2 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, TWO_COINS));
Transaction t3 = Objects.requireNonNull(sendMoneyToWallet(AbstractBlockChain.NewBlockType.BEST_CHAIN, CENT));
// Should be ordered t2, t1, t3.
ArrayList<TransactionOutput> candidates = new ArrayList<>();
candidates.add(t3.getOutput(0));
candidates.add(t2.getOutput(0));
candidates.add(t1.getOutput(0));
DefaultCoinSelector.sortOutputs(candidates);
assertEquals(t2.getOutput(0), candidates.get(0));
assertEquals(t1.getOutput(0), candidates.get(1));
assertEquals(t3.getOutput(0), candidates.get(2));
}
@Test
public void identicalInputs() {
// Add four outputs to a transaction with same value and destination. Select them all.
Transaction t = new Transaction();
List<TransactionOutput> outputs = Arrays.asList(
new TransactionOutput(t, Coin.valueOf(30302787), myAddress),
new TransactionOutput(t, Coin.valueOf(30302787), myAddress),
new TransactionOutput(t, Coin.valueOf(30302787), myAddress),
new TransactionOutput(t, Coin.valueOf(30302787), myAddress)
);
t.getConfidence().setConfidenceType(TransactionConfidence.ConfidenceType.BUILDING);
CoinSelector selector = DefaultCoinSelector.get(BitcoinNetwork.TESTNET);
CoinSelection selection = selector.select(COIN.multiply(2), outputs);
assertTrue(selection.outputs().size() == 4);
}
}
| 6,417
| 42.958904
| 122
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/wallet/WalletExtensionsTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.wallet;
import org.bitcoinj.testing.FooWalletExtension;
import org.bitcoinj.testing.TestWithWallet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class WalletExtensionsTest extends TestWithWallet {
@Before
@Override
public void setUp() throws Exception {
super.setUp();
}
@After
@Override
public void tearDown() throws Exception {
super.tearDown();
}
@Test(expected = java.lang.IllegalStateException.class)
public void duplicateWalletExtensionTest() {
wallet.addExtension(new FooWalletExtension("com.whatever.required", true));
wallet.addExtension(new FooWalletExtension("com.whatever.required", true));
}
}
| 1,357
| 29.177778
| 83
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/params/BitcoinNetworkParamsTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.params;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.core.Block;
import org.bitcoinj.base.Coin;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class BitcoinNetworkParamsTest {
private final BitcoinNetworkParams BITCOIN_PARAMS = new BitcoinNetworkParams(BitcoinNetwork.TESTNET) {
@Override
public Block getGenesisBlock() {
return null;
}
};
@Test
public void isDifficultyTransitionPoint() {
assertFalse(BITCOIN_PARAMS.isDifficultyTransitionPoint(2014));
assertTrue(BITCOIN_PARAMS.isDifficultyTransitionPoint(2015));
assertFalse(BITCOIN_PARAMS.isDifficultyTransitionPoint(2016));
}
@Test
public void isRewardHalvingPoint() {
assertTrue(BITCOIN_PARAMS.isRewardHalvingPoint(209999));
assertTrue(BITCOIN_PARAMS.isRewardHalvingPoint(419999));
assertFalse(BITCOIN_PARAMS.isRewardHalvingPoint(629998));
assertTrue(BITCOIN_PARAMS.isRewardHalvingPoint(629999));
assertFalse(BITCOIN_PARAMS.isRewardHalvingPoint(630000));
assertTrue(BITCOIN_PARAMS.isRewardHalvingPoint(839999));
}
@Test
public void getBlockInflation() {
assertEquals(Coin.FIFTY_COINS, BITCOIN_PARAMS.getBlockInflation(209998));
assertEquals(Coin.FIFTY_COINS, BITCOIN_PARAMS.getBlockInflation(209999));
assertEquals(Coin.FIFTY_COINS.div(2), BITCOIN_PARAMS.getBlockInflation(210000));
assertEquals(Coin.FIFTY_COINS.div(2), BITCOIN_PARAMS.getBlockInflation(210001));
}
}
| 2,281
| 34.65625
| 106
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/uri/BitcoinURITest.java
|
/*
* Copyright 2012, 2014 the original author or authors.
*
* 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.
*/
package org.bitcoinj.uri;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.Address;
import org.bitcoinj.base.DefaultAddressParser;
import org.bitcoinj.base.LegacyAddress;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.params.Networks;
import org.bitcoinj.testing.MockAltNetworkParams;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import static org.bitcoinj.base.Coin.CENT;
import static org.bitcoinj.base.Coin.parseCoin;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class BitcoinURITest {
private BitcoinURI testObject = null;
private static final BitcoinNetwork MAINNET = BitcoinNetwork.MAINNET;
private static final BitcoinNetwork TESTNET = BitcoinNetwork.TESTNET;
private static final String MAINNET_GOOD_ADDRESS = "1KzTSfqjF2iKCduwz59nv2uqh1W2JsTxZH";
private static final String MAINNET_GOOD_SEGWIT_ADDRESS = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4";
private static final String BITCOIN_SCHEME = BitcoinNetwork.BITCOIN_SCHEME;
@Test
public void of_anyNetwork() throws Exception {
BitcoinURI uri1 = BitcoinURI.of("bitcoin:" + MAINNET_GOOD_ADDRESS);
assertEquals(BitcoinNetwork.MAINNET, uri1.getAddress().network());
BitcoinURI uri2 = BitcoinURI.of("bitcoin:" + MAINNET_GOOD_SEGWIT_ADDRESS);
assertEquals(BitcoinNetwork.MAINNET, uri2.getAddress().network());
BitcoinURI uri3 = BitcoinURI.of("bitcoin:mutDLVyes4YNWkL4j8g9oUsSUSTtnt13hP");
assertEquals(BitcoinNetwork.TESTNET, uri3.getAddress().network());
BitcoinURI uri4 = BitcoinURI.of("bitcoin:tb1qn96rzewt04q0vtnh8lh0kelekkj2lpjh29lg6x");
assertEquals(BitcoinNetwork.TESTNET, uri4.getAddress().network());
BitcoinURI uri5 = BitcoinURI.of("BITCOIN:TB1QN96RZEWT04Q0VTNH8LH0KELEKKJ2LPJH29LG6X");
assertEquals(BitcoinNetwork.TESTNET, uri5.getAddress().network());
}
@Test
public void testConvertToBitcoinURI() {
Address goodAddress = new DefaultAddressParser().parseAddress(MAINNET_GOOD_ADDRESS, MAINNET);
// simple example
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?amount=12.34&label=Hello&message=AMessage", BitcoinURI.convertToBitcoinURI(goodAddress, parseCoin("12.34"), "Hello", "AMessage"));
// example with spaces, ampersand and plus
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?amount=12.34&label=Hello%20World&message=Mess%20%26%20age%20%2B%20hope", BitcoinURI.convertToBitcoinURI(goodAddress, parseCoin("12.34"), "Hello World", "Mess & age + hope"));
// no amount, label present, message present
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?label=Hello&message=glory", BitcoinURI.convertToBitcoinURI(goodAddress, null, "Hello", "glory"));
// amount present, no label, message present
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?amount=0.1&message=glory", BitcoinURI.convertToBitcoinURI(goodAddress, parseCoin("0.1"), null, "glory"));
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?amount=0.1&message=glory", BitcoinURI.convertToBitcoinURI(goodAddress, parseCoin("0.1"), "", "glory"));
// amount present, label present, no message
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?amount=12.34&label=Hello", BitcoinURI.convertToBitcoinURI(goodAddress, parseCoin("12.34"), "Hello", null));
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?amount=12.34&label=Hello", BitcoinURI.convertToBitcoinURI(goodAddress, parseCoin("12.34"), "Hello", ""));
// amount present, no label, no message
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?amount=1000", BitcoinURI.convertToBitcoinURI(goodAddress, parseCoin("1000"), null, null));
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?amount=1000", BitcoinURI.convertToBitcoinURI(goodAddress, parseCoin("1000"), "", ""));
// no amount, label present, no message
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?label=Hello", BitcoinURI.convertToBitcoinURI(goodAddress, null, "Hello", null));
// no amount, no label, message present
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?message=Agatha", BitcoinURI.convertToBitcoinURI(goodAddress, null, null, "Agatha"));
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS + "?message=Agatha", BitcoinURI.convertToBitcoinURI(goodAddress, null, "", "Agatha"));
// no amount, no label, no message
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS, BitcoinURI.convertToBitcoinURI(goodAddress, null, null, null));
assertEquals("bitcoin:" + MAINNET_GOOD_ADDRESS, BitcoinURI.convertToBitcoinURI(goodAddress, null, "", ""));
// different scheme
NetworkParameters alternativeParameters = new MockAltNetworkParams();
String mockNetGoodAddress = MockAltNetworkParams.MOCKNET_GOOD_ADDRESS;
Networks.register(alternativeParameters);
try {
assertEquals("mockcoin:" + mockNetGoodAddress + "?amount=12.34&label=Hello&message=AMessage",
BitcoinURI.convertToBitcoinURI(LegacyAddress.fromBase58(mockNetGoodAddress, alternativeParameters.network()), parseCoin("12.34"), "Hello", "AMessage"));
} finally {
Networks.unregister(alternativeParameters);
}
}
@Test
public void testConvertToBitcoinURI_segwit() {
Address segwitAddress = new DefaultAddressParser().parseAddress(MAINNET_GOOD_SEGWIT_ADDRESS, MAINNET);
assertEquals("bitcoin:" + MAINNET_GOOD_SEGWIT_ADDRESS + "?message=segwit%20rules", BitcoinURI.convertToBitcoinURI(
segwitAddress, null, null, "segwit rules"));
}
@Test
public void testGood_legacy() throws BitcoinURIParseException {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS, MAINNET);
assertEquals(MAINNET_GOOD_ADDRESS, testObject.getAddress().toString());
assertNull("Unexpected amount", testObject.getAmount());
assertNull("Unexpected label", testObject.getLabel());
assertEquals("Unexpected label", 20, testObject.getAddress().getHash().length);
}
@Test
public void testGood_uppercaseScheme() throws BitcoinURIParseException {
testObject = BitcoinURI.of(BITCOIN_SCHEME.toUpperCase(Locale.US) + ":" + MAINNET_GOOD_ADDRESS, MAINNET);
assertEquals(MAINNET_GOOD_ADDRESS, testObject.getAddress().toString());
assertNull("Unexpected amount", testObject.getAmount());
assertNull("Unexpected label", testObject.getLabel());
assertEquals("Unexpected label", 20, testObject.getAddress().getHash().length);
}
@Test
public void testGood_segwit() throws BitcoinURIParseException {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_SEGWIT_ADDRESS, MAINNET);
assertEquals(MAINNET_GOOD_SEGWIT_ADDRESS, testObject.getAddress().toString());
assertNull("Unexpected amount", testObject.getAmount());
assertNull("Unexpected label", testObject.getLabel());
}
/**
* Test a broken URI (bad scheme)
*/
@Test
public void testBad_Scheme() {
try {
testObject = BitcoinURI.of("blimpcoin:" + MAINNET_GOOD_ADDRESS, MAINNET);
fail("Expecting BitcoinURIParseException");
} catch (BitcoinURIParseException e) {
}
}
/**
* Test a broken URI (bad syntax)
*/
@Test
public void testBad_BadSyntax() {
// Various illegal characters
try {
testObject = BitcoinURI.of(BITCOIN_SCHEME + "|" + MAINNET_GOOD_ADDRESS, MAINNET);
fail("Expecting BitcoinURIParseException");
} catch (BitcoinURIParseException e) {
assertTrue(e.getMessage().contains("Bad URI syntax"));
}
try {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS + "\\", MAINNET);
fail("Expecting BitcoinURIParseException");
} catch (BitcoinURIParseException e) {
assertTrue(e.getMessage().contains("Bad URI syntax"));
}
// Separator without field
try {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":", MAINNET);
fail("Expecting BitcoinURIParseException");
} catch (BitcoinURIParseException e) {
assertTrue(e.getMessage().contains("Bad URI syntax"));
}
}
/**
* Test a broken URI (missing address)
*/
@Test
public void testBad_Address() {
try {
testObject = BitcoinURI.of(BITCOIN_SCHEME, MAINNET);
fail("Expecting BitcoinURIParseException");
} catch (BitcoinURIParseException e) {
}
}
/**
* Test a broken URI (bad address type)
*/
@Test
public void testBad_IncorrectAddressType() {
try {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS, TESTNET);
fail("Expecting BitcoinURIParseException");
} catch (BitcoinURIParseException e) {
assertTrue(e.getMessage().contains("Bad address"));
}
}
/**
* Handles a simple amount
*
* @throws BitcoinURIParseException
* If something goes wrong
*/
@Test
public void testGood_Amount() throws BitcoinURIParseException {
// Test the decimal parsing
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?amount=6543210.12345678", MAINNET);
assertEquals("654321012345678", testObject.getAmount().toString());
// Test the decimal parsing
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?amount=.12345678", MAINNET);
assertEquals("12345678", testObject.getAmount().toString());
// Test the integer parsing
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?amount=6543210", MAINNET);
assertEquals("654321000000000", testObject.getAmount().toString());
// the maximum amount
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?amount=" + new BigDecimal(Long.MAX_VALUE).movePointLeft(8), MAINNET);
assertEquals(Long.MAX_VALUE, testObject.getAmount().longValue());
}
/**
* Handles a simple label
*
* @throws BitcoinURIParseException
* If something goes wrong
*/
@Test
public void testGood_Label() throws BitcoinURIParseException {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?label=Hello%20World", MAINNET);
assertEquals("Hello World", testObject.getLabel());
}
/**
* Handles a simple label with an embedded ampersand and plus
*
* @throws BitcoinURIParseException
* If something goes wrong
*/
@Test
public void testGood_LabelWithAmpersandAndPlus() throws BitcoinURIParseException {
String testString = "Hello Earth & Mars + Venus";
String encodedLabel = BitcoinURI.encodeURLString(testString);
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS + "?label="
+ encodedLabel, MAINNET);
assertEquals(testString, testObject.getLabel());
}
/**
* Handles a Russian label (Unicode test)
*
* @throws BitcoinURIParseException
* If something goes wrong
*/
@Test
public void testGood_LabelWithRussian() throws BitcoinURIParseException {
// Moscow in Russian in Cyrillic
String moscowString = "\u041c\u043e\u0441\u043a\u0432\u0430";
String encodedLabel = BitcoinURI.encodeURLString(moscowString);
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS + "?label="
+ encodedLabel, MAINNET);
assertEquals(moscowString, testObject.getLabel());
}
/**
* Handles a simple message
*
* @throws BitcoinURIParseException
* If something goes wrong
*/
@Test
public void testGood_Message() throws BitcoinURIParseException {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?message=Hello%20World", MAINNET);
assertEquals("Hello World", testObject.getMessage());
}
/**
* Handles various well-formed combinations
*
* @throws BitcoinURIParseException
* If something goes wrong
*/
@Test
public void testGood_Combinations() throws BitcoinURIParseException {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?amount=6543210&label=Hello%20World&message=Be%20well", MAINNET);
assertEquals(
"BitcoinURI['amount'='654321000000000','label'='Hello World','message'='Be well','address'='1KzTSfqjF2iKCduwz59nv2uqh1W2JsTxZH']",
testObject.toString());
}
/**
* Handles a badly formatted amount field
*/
@Test
public void testBad_Amount() {
// Missing
try {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?amount=", MAINNET);
fail("Expecting BitcoinURIParseException");
} catch (BitcoinURIParseException e) {
assertTrue(e.getMessage().contains("amount"));
}
// Non-decimal (BIP 21)
try {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?amount=12X4", MAINNET);
fail("Expecting BitcoinURIParseException");
} catch (BitcoinURIParseException e) {
assertTrue(e.getMessage().contains("amount"));
}
}
@Test
public void testEmpty_Label() throws BitcoinURIParseException {
assertNull(BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?label=", MAINNET).getLabel());
}
@Test
public void testEmpty_Message() throws BitcoinURIParseException {
assertNull(BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?message=", MAINNET).getMessage());
}
/**
* Handles duplicated fields (sneaky address overwrite attack)
*/
@Test
public void testBad_Duplicated() {
try {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?address=aardvark", MAINNET);
fail("Expecting BitcoinURIParseException");
} catch (BitcoinURIParseException e) {
assertTrue(e.getMessage().contains("address"));
}
}
@Test
public void testGood_ManyEquals() throws BitcoinURIParseException {
assertEquals("aardvark=zebra", BitcoinURI.of(BITCOIN_SCHEME + ":"
+ MAINNET_GOOD_ADDRESS + "?label=aardvark=zebra", MAINNET).getLabel());
}
/**
* Handles unknown fields (required and not required)
*
* @throws BitcoinURIParseException
* If something goes wrong
*/
@Test
public void testUnknown() throws BitcoinURIParseException {
// Unknown not required field
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?aardvark=true", MAINNET);
assertEquals("BitcoinURI['aardvark'='true','address'='1KzTSfqjF2iKCduwz59nv2uqh1W2JsTxZH']", testObject.toString());
assertEquals("true", testObject.getParameterByName("aardvark"));
// Unknown not required field (isolated)
try {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?aardvark", MAINNET);
fail("Expecting BitcoinURIParseException");
} catch (BitcoinURIParseException e) {
assertTrue(e.getMessage().contains("no separator"));
}
// Unknown and required field
try {
testObject = BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?req-aardvark=true", MAINNET);
fail("Expecting BitcoinURIParseException");
} catch (BitcoinURIParseException e) {
assertTrue(e.getMessage().contains("req-aardvark"));
}
}
@Test
public void brokenURIs() throws BitcoinURIParseException {
// Check we can parse the incorrectly formatted URIs produced by blockchain.info and its iPhone app.
String str = "bitcoin://1KzTSfqjF2iKCduwz59nv2uqh1W2JsTxZH?amount=0.01000000";
BitcoinURI uri = BitcoinURI.of(str);
assertEquals("1KzTSfqjF2iKCduwz59nv2uqh1W2JsTxZH", uri.getAddress().toString());
assertEquals(CENT, uri.getAmount());
}
@Test(expected = BitcoinURIParseException.class)
public void testBad_AmountTooPrecise() throws BitcoinURIParseException {
BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?amount=0.123456789", MAINNET);
}
@Test(expected = BitcoinURIParseException.class)
public void testBad_NegativeAmount() throws BitcoinURIParseException {
BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?amount=-1", MAINNET);
}
@Test(expected = BitcoinURIParseException.class)
public void testBad_TooLargeAmount() throws BitcoinURIParseException {
BigDecimal tooLargeByOne = new BigDecimal(Long.MAX_VALUE).add(BigDecimal.ONE);
BitcoinURI.of(BITCOIN_SCHEME + ":" + MAINNET_GOOD_ADDRESS
+ "?amount=" + tooLargeByOne.movePointLeft(8), MAINNET);
}
@Test
public void testPaymentProtocolReq() throws Exception {
// Non-backwards compatible form ...
BitcoinURI uri = BitcoinURI.of("bitcoin:?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin%2Ff.php%3Fh%3Db0f02e7cea67f168e25ec9b9f9d584f9", TESTNET);
assertEquals("https://bitcoincore.org/~gavin/f.php?h=b0f02e7cea67f168e25ec9b9f9d584f9", uri.getPaymentRequestUrl());
assertEquals(Collections.singletonList("https://bitcoincore.org/~gavin/f.php?h=b0f02e7cea67f168e25ec9b9f9d584f9"),
uri.getPaymentRequestUrls());
assertNull(uri.getAddress());
}
@Test
public void testMultiplePaymentProtocolReq() throws Exception {
BitcoinURI uri = BitcoinURI.of("bitcoin:?r=https%3A%2F%2Fbitcoincore.org%2F%7Egavin&r1=bt:112233445566", MAINNET);
assertEquals(Arrays.asList("bt:112233445566", "https://bitcoincore.org/~gavin"), uri.getPaymentRequestUrls());
assertEquals("https://bitcoincore.org/~gavin", uri.getPaymentRequestUrl());
}
@Test
public void testNoPaymentProtocolReq() throws Exception {
BitcoinURI uri = BitcoinURI.of("bitcoin:" + MAINNET_GOOD_ADDRESS, MAINNET);
assertNull(uri.getPaymentRequestUrl());
assertEquals(Collections.emptyList(), uri.getPaymentRequestUrls());
assertNotNull(uri.getAddress());
}
@Test
public void testUnescapedPaymentProtocolReq() throws Exception {
BitcoinURI uri = BitcoinURI.of("bitcoin:?r=https://merchant.com/pay.php?h%3D2a8628fc2fbe", TESTNET);
assertEquals("https://merchant.com/pay.php?h=2a8628fc2fbe", uri.getPaymentRequestUrl());
assertEquals(Collections.singletonList("https://merchant.com/pay.php?h=2a8628fc2fbe"), uri.getPaymentRequestUrls());
assertNull(uri.getAddress());
}
}
| 20,325
| 42.806034
| 233
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/protocols/payments/PaymentSessionTest.java
|
/*
* Copyright 2013 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.protocols.payments;
import com.google.protobuf.ByteString;
import org.bitcoin.protocols.payments.Protos;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.Address;
import org.bitcoinj.base.Coin;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.core.Context;
import org.bitcoinj.core.TransactionOutPoint;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.crypto.TrustStoreLoader;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.utils.ListenableCompletableFuture;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.io.InputStream;
import java.net.URL;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import static org.bitcoinj.base.Coin.COIN;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class PaymentSessionTest {
private static final NetworkParameters TESTNET = TestNet3Params.get();
private static final NetworkParameters MAINNET = MainNetParams.get();
private static final String simplePaymentUrl = "http://a.simple.url.com/";
private static final String paymentRequestMemo = "send coinz noa plz kthx";
private static final String paymentMemo = "take ze coinz";
private static final ByteString merchantData = ByteString.copyFromUtf8("merchant data");
private static final Instant time = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS);
private ECKey serverKey;
private Transaction tx;
private TransactionOutput outputToMe;
private final Coin amount = COIN;
@Before
public void setUp() {
Context.propagate(new Context());
serverKey = new ECKey();
tx = new Transaction();
outputToMe = new TransactionOutput(tx, amount, serverKey);
tx.addOutput(outputToMe);
}
@Test
public void testSimplePayment() throws Exception {
// Create a PaymentRequest and make sure the correct values are parsed by the PaymentSession.
MockPaymentSession paymentSession = new MockPaymentSession(newSimplePaymentRequest("test"));
assertEquals(paymentRequestMemo, paymentSession.getMemo());
assertEquals(amount, paymentSession.getValue());
assertEquals(simplePaymentUrl, paymentSession.getPaymentUrl());
assertEquals(time, paymentSession.time());
assertTrue(paymentSession.getSendRequest().tx.equals(tx));
assertFalse(paymentSession.isExpired());
// Send the payment and verify that the correct information is sent.
// Add a dummy input to tx so it is considered valid.
tx.addInput(new TransactionInput(tx, outputToMe.getScriptBytes(), TransactionOutPoint.UNCONNECTED));
ArrayList<Transaction> txns = new ArrayList<>();
txns.add(tx);
Address refundAddr = serverKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
paymentSession.sendPayment(txns, refundAddr, paymentMemo);
assertEquals(1, paymentSession.getPaymentLog().size());
assertEquals(simplePaymentUrl, paymentSession.getPaymentLog().get(0).getUrl().toString());
Protos.Payment payment = paymentSession.getPaymentLog().get(0).getPayment();
assertEquals(paymentMemo, payment.getMemo());
assertEquals(merchantData, payment.getMerchantData());
assertEquals(1, payment.getRefundToCount());
assertEquals(amount.value, payment.getRefundTo(0).getAmount());
TransactionOutput refundOutput = new TransactionOutput(null, amount, refundAddr);
ByteString refundScript = ByteString.copyFrom(refundOutput.getScriptBytes());
assertTrue(refundScript.equals(payment.getRefundTo(0).getScript()));
}
@Test
public void testDefaults() throws Exception {
Protos.Output.Builder outputBuilder = Protos.Output.newBuilder()
.setScript(ByteString.copyFrom(outputToMe.getScriptBytes()));
Protos.PaymentDetails paymentDetails = Protos.PaymentDetails.newBuilder()
.setTime(time.getEpochSecond())
.addOutputs(outputBuilder)
.build();
Protos.PaymentRequest paymentRequest = Protos.PaymentRequest.newBuilder()
.setSerializedPaymentDetails(paymentDetails.toByteString())
.build();
MockPaymentSession paymentSession = new MockPaymentSession(paymentRequest);
assertEquals(Coin.ZERO, paymentSession.getValue());
assertNull(paymentSession.getPaymentUrl());
assertNull(paymentSession.getMemo());
}
@Test
public void testExpiredPaymentRequest() throws PaymentProtocolException {
MockPaymentSession paymentSession = new MockPaymentSession(newExpiredPaymentRequest());
assertTrue(paymentSession.isExpired());
// Send the payment and verify that an exception is thrown.
// Add a dummy input to tx so it is considered valid.
tx.addInput(new TransactionInput(tx, outputToMe.getScriptBytes(), TransactionOutPoint.UNCONNECTED));
ArrayList<Transaction> txns = new ArrayList<>();
txns.add(tx);
CompletableFuture<PaymentProtocol.Ack> ack = paymentSession.sendPayment(txns, null, null);
try {
ack.get();
} catch (ExecutionException e) {
if (e.getCause() instanceof PaymentProtocolException.Expired) {
PaymentProtocolException.Expired cause = (PaymentProtocolException.Expired) e.getCause();
assertEquals(0, paymentSession.getPaymentLog().size());
assertEquals(cause.getMessage(), "PaymentRequest is expired");
return;
}
} catch (InterruptedException e) {
// Ignore
}
fail("Expected exception due to expired PaymentRequest");
}
@Test
@Ignore("certificate expired")
public void testPkiVerification() throws Exception {
InputStream in = getClass().getResourceAsStream("pki_test.bitcoinpaymentrequest");
Protos.PaymentRequest paymentRequest = Protos.PaymentRequest.newBuilder().mergeFrom(in).build();
PaymentProtocol.PkiVerificationData pkiData = PaymentProtocol.verifyPaymentRequestPki(paymentRequest,
new TrustStoreLoader.DefaultTrustStoreLoader().getKeyStore());
assertEquals("www.bitcoincore.org", pkiData.displayName);
assertEquals("The USERTRUST Network, Salt Lake City, US", pkiData.rootAuthorityName);
}
private Protos.PaymentRequest newSimplePaymentRequest(String netID) {
Protos.Output.Builder outputBuilder = Protos.Output.newBuilder()
.setAmount(amount.value)
.setScript(ByteString.copyFrom(outputToMe.getScriptBytes()));
Protos.PaymentDetails paymentDetails = Protos.PaymentDetails.newBuilder()
.setNetwork(netID)
.setTime(time.getEpochSecond())
.setPaymentUrl(simplePaymentUrl)
.addOutputs(outputBuilder)
.setMemo(paymentRequestMemo)
.setMerchantData(merchantData)
.build();
return Protos.PaymentRequest.newBuilder()
.setPaymentDetailsVersion(1)
.setPkiType("none")
.setSerializedPaymentDetails(paymentDetails.toByteString())
.build();
}
private Protos.PaymentRequest newExpiredPaymentRequest() {
Protos.Output.Builder outputBuilder = Protos.Output.newBuilder()
.setAmount(amount.value)
.setScript(ByteString.copyFrom(outputToMe.getScriptBytes()));
Protos.PaymentDetails paymentDetails = Protos.PaymentDetails.newBuilder()
.setNetwork("test")
.setTime(time.minusSeconds(10).getEpochSecond())
.setExpires(time.minusSeconds(1).getEpochSecond())
.setPaymentUrl(simplePaymentUrl)
.addOutputs(outputBuilder)
.setMemo(paymentRequestMemo)
.setMerchantData(merchantData)
.build();
return Protos.PaymentRequest.newBuilder()
.setPaymentDetailsVersion(1)
.setPkiType("none")
.setSerializedPaymentDetails(paymentDetails.toByteString())
.build();
}
private static class MockPaymentSession extends PaymentSession {
private final ArrayList<PaymentLogItem> paymentLog = new ArrayList<>();
public MockPaymentSession(Protos.PaymentRequest request) throws PaymentProtocolException {
super(request);
}
public ArrayList<PaymentLogItem> getPaymentLog() {
return paymentLog;
}
@Override
protected ListenableCompletableFuture<PaymentProtocol.Ack> sendPayment(final URL url, final Protos.Payment payment) {
paymentLog.add(new PaymentLogItem(url, payment));
// Return a completed future that has a `null` value. This will satisfy the current tests.
return ListenableCompletableFuture.completedFuture(null);
}
public static class PaymentLogItem {
private final URL url;
private final Protos.Payment payment;
PaymentLogItem(final URL url, final Protos.Payment payment) {
this.url = url;
this.payment = payment;
}
public URL getUrl() {
return url;
}
public Protos.Payment getPayment() {
return payment;
}
}
}
}
| 10,702
| 43.410788
| 125
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/protocols/payments/PaymentProtocolTest.java
|
/*
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.protocols.payments;
import org.bitcoin.protocols.payments.Protos;
import org.bitcoin.protocols.payments.Protos.Payment;
import org.bitcoin.protocols.payments.Protos.PaymentACK;
import org.bitcoin.protocols.payments.Protos.PaymentRequest;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.Address;
import org.bitcoinj.base.Coin;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.crypto.X509Utils;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.protocols.payments.PaymentProtocol.Output;
import org.bitcoinj.protocols.payments.PaymentProtocol.PkiVerificationData;
import org.bitcoinj.protocols.payments.PaymentProtocolException.PkiVerificationException;
import org.bitcoinj.script.ScriptBuilder;
import org.bitcoinj.testing.FakeTxBuilder;
import org.junit.Before;
import org.junit.Test;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class PaymentProtocolTest {
private static final NetworkParameters TESTNET = TestNet3Params.get();
// static test data
private static final Coin AMOUNT = Coin.SATOSHI;
private static final Address TO_ADDRESS = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
private static final String MEMO = "memo";
private static final String PAYMENT_URL = "https://example.com";
private static final byte[] MERCHANT_DATA = { 0, 1, 2 };
private KeyStore caStore;
private X509Certificate caCert;
@Before
public void setUp() throws Exception {
caStore = X509Utils.loadKeyStore("JKS", "password", getClass().getResourceAsStream("test-cacerts"));
caCert = (X509Certificate) caStore.getCertificate("test-cacert");
}
@Test
public void testSignAndVerifyValid() throws Exception {
Protos.PaymentRequest.Builder paymentRequest = minimalPaymentRequest().toBuilder();
// Sign
KeyStore keyStore = X509Utils
.loadKeyStore("JKS", "password", getClass().getResourceAsStream("test-valid-cert"));
PrivateKey privateKey = (PrivateKey) keyStore.getKey("test-valid", "password".toCharArray());
X509Certificate clientCert = (X509Certificate) keyStore.getCertificate("test-valid");
PaymentProtocol.signPaymentRequest(paymentRequest, new X509Certificate[]{clientCert}, privateKey);
// Verify
PkiVerificationData verificationData = PaymentProtocol.verifyPaymentRequestPki(paymentRequest.build(), caStore);
assertNotNull(verificationData);
assertEquals(caCert, verificationData.rootAuthority.getTrustedCert());
}
@Test(expected = PkiVerificationException.class)
public void testSignAndVerifyExpired() throws Exception {
Protos.PaymentRequest.Builder paymentRequest = minimalPaymentRequest().toBuilder();
// Sign
KeyStore keyStore = X509Utils.loadKeyStore("JKS", "password",
getClass().getResourceAsStream("test-expired-cert"));
PrivateKey privateKey = (PrivateKey) keyStore.getKey("test-expired", "password".toCharArray());
X509Certificate clientCert = (X509Certificate) keyStore.getCertificate("test-expired");
PaymentProtocol.signPaymentRequest(paymentRequest, new X509Certificate[]{clientCert}, privateKey);
// Verify
PaymentProtocol.verifyPaymentRequestPki(paymentRequest.build(), caStore);
}
private Protos.PaymentRequest minimalPaymentRequest() {
Protos.PaymentDetails.Builder paymentDetails = Protos.PaymentDetails.newBuilder();
paymentDetails.setTime(TimeUtils.currentTime().getEpochSecond());
Protos.PaymentRequest.Builder paymentRequest = Protos.PaymentRequest.newBuilder();
paymentRequest.setSerializedPaymentDetails(paymentDetails.build().toByteString());
return paymentRequest.build();
}
@Test
public void testPaymentRequest() throws Exception {
// Create
PaymentRequest paymentRequest = PaymentProtocol.createPaymentRequest(TESTNET, AMOUNT, TO_ADDRESS, MEMO,
PAYMENT_URL, MERCHANT_DATA).build();
byte[] paymentRequestBytes = paymentRequest.toByteArray();
// Parse
PaymentSession parsedPaymentRequest = PaymentProtocol.parsePaymentRequest(PaymentRequest
.parseFrom(paymentRequestBytes));
final List<Output> parsedOutputs = parsedPaymentRequest.getOutputs();
assertEquals(1, parsedOutputs.size());
assertEquals(AMOUNT, parsedOutputs.get(0).amount);
assertArrayEquals(ScriptBuilder.createOutputScript(TO_ADDRESS).program(), parsedOutputs.get(0).scriptData);
assertEquals(MEMO, parsedPaymentRequest.getMemo());
assertEquals(PAYMENT_URL, parsedPaymentRequest.getPaymentUrl());
assertArrayEquals(MERCHANT_DATA, parsedPaymentRequest.getMerchantData());
}
@Test
public void testPaymentMessage() throws Exception {
// Create
List<Transaction> transactions = new LinkedList<>();
transactions.add(FakeTxBuilder.createFakeTx(TESTNET.network(), AMOUNT, TO_ADDRESS));
Coin refundAmount = Coin.SATOSHI;
Address refundAddress = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
Payment payment = PaymentProtocol.createPaymentMessage(transactions, refundAmount, refundAddress, MEMO,
MERCHANT_DATA);
byte[] paymentBytes = payment.toByteArray();
// Parse
Payment parsedPayment = Payment.parseFrom(paymentBytes);
List<Transaction> parsedTransactions = PaymentProtocol.parseTransactionsFromPaymentMessage(TESTNET,
parsedPayment);
assertEquals(transactions, parsedTransactions);
assertEquals(1, parsedPayment.getRefundToCount());
assertEquals(MEMO, parsedPayment.getMemo());
assertArrayEquals(MERCHANT_DATA, parsedPayment.getMerchantData().toByteArray());
}
@Test
public void testPaymentAck() throws Exception {
// Create
Payment paymentMessage = Protos.Payment.newBuilder().build();
PaymentACK paymentAck = PaymentProtocol.createPaymentAck(paymentMessage, MEMO);
byte[] paymentAckBytes = paymentAck.toByteArray();
// Parse
PaymentACK parsedPaymentAck = PaymentACK.parseFrom(paymentAckBytes);
assertEquals(paymentMessage, parsedPaymentAck.getPayment());
assertEquals(MEMO, parsedPaymentAck.getMemo());
}
}
| 7,410
| 44.466258
| 120
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/store/SPVBlockStoreTest.java
|
/*
* Copyright 2013 Google Inc.
* Copyright 2018 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.store;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.Address;
import org.bitcoinj.base.internal.PlatformUtils;
import org.bitcoinj.base.internal.Stopwatch;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.core.Block;
import org.bitcoinj.core.Context;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.core.StoredBlock;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.params.TestNet3Params;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class SPVBlockStoreTest {
private static final NetworkParameters TESTNET = TestNet3Params.get();
private File blockStoreFile;
@BeforeClass
public static void setUpClass() {
TimeUtils.clearMockClock();
}
@Before
public void setup() throws Exception {
Context.propagate(new Context());
blockStoreFile = File.createTempFile("spvblockstore", null);
blockStoreFile.delete();
blockStoreFile.deleteOnExit();
}
@Test
public void basics() throws Exception {
Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true));
SPVBlockStore store = new SPVBlockStore(TESTNET, blockStoreFile);
Address to = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
// Check the first block in a new store is the genesis block.
StoredBlock genesis = store.getChainHead();
assertEquals(TESTNET.getGenesisBlock(), genesis.getHeader());
assertEquals(0, genesis.getHeight());
// Build a new block.
StoredBlock b1 = genesis.build(genesis.getHeader().createNextBlock(to).cloneAsHeader());
store.put(b1);
store.setChainHead(b1);
store.close();
// Check we can get it back out again if we rebuild the store object.
store = new SPVBlockStore(TESTNET, blockStoreFile);
StoredBlock b2 = store.get(b1.getHeader().getHash());
assertEquals(b1, b2);
// Check the chain head was stored correctly also.
StoredBlock chainHead = store.getChainHead();
assertEquals(b1, chainHead);
store.close();
}
@Test(expected = BlockStoreException.class)
public void twoStores_onSameFile() throws Exception {
new SPVBlockStore(TESTNET, blockStoreFile);
new SPVBlockStore(TESTNET, blockStoreFile);
}
@Test
public void twoStores_butSequentially() throws Exception {
SPVBlockStore store = new SPVBlockStore(TESTNET, blockStoreFile);
store.close();
store = new SPVBlockStore(TESTNET, blockStoreFile);
}
@Test(expected = BlockStoreException.class)
public void twoStores_sequentially_butMismatchingCapacity() throws Exception {
SPVBlockStore store = new SPVBlockStore(TESTNET, blockStoreFile, 10, false);
store.close();
store = new SPVBlockStore(TESTNET, blockStoreFile, 20, false);
}
@Test
public void twoStores_sequentially_grow() throws Exception {
Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true));
Address to = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
SPVBlockStore store = new SPVBlockStore(TESTNET, blockStoreFile, 10, true);
final StoredBlock block0 = store.getChainHead();
final StoredBlock block1 = block0.build(block0.getHeader().createNextBlock(to).cloneAsHeader());
store.put(block1);
final StoredBlock block2 = block1.build(block1.getHeader().createNextBlock(to).cloneAsHeader());
store.put(block2);
store.setChainHead(block2);
store.close();
store = new SPVBlockStore(TESTNET, blockStoreFile, 20, true);
final StoredBlock read2 = store.getChainHead();
assertEquals(block2, read2);
final StoredBlock read1 = read2.getPrev(store);
assertEquals(block1, read1);
final StoredBlock read0 = read1.getPrev(store);
assertEquals(block0, read0);
store.close();
assertEquals(SPVBlockStore.getFileSize(20), blockStoreFile.length());
}
@Test(expected = BlockStoreException.class)
public void twoStores_sequentially_shrink() throws Exception {
SPVBlockStore store = new SPVBlockStore(TESTNET, blockStoreFile, 20, true);
store.close();
store = new SPVBlockStore(TESTNET, blockStoreFile, 10, true);
}
@Test
public void performanceTest() throws BlockStoreException {
// On slow machines, this test could fail. Then either add @Ignore or adapt the threshold and please report to
// us.
final int ITERATIONS = 100000;
final Duration THRESHOLD = Duration.ofSeconds(5);
SPVBlockStore store = new SPVBlockStore(TESTNET, blockStoreFile);
Stopwatch watch = Stopwatch.start();
for (int i = 0; i < ITERATIONS; i++) {
// Using i as the nonce so that the block hashes are different.
Block block = new Block(0, Sha256Hash.ZERO_HASH, Sha256Hash.ZERO_HASH, 0, 0, i,
Collections.emptyList());
StoredBlock b = new StoredBlock(block, BigInteger.ZERO, i);
store.put(b);
store.setChainHead(b);
}
watch.stop();
assertTrue("took " + watch + " for " + ITERATIONS + " iterations",
watch.elapsed().compareTo(THRESHOLD) < 0);
store.close();
}
@Test
public void clear() throws Exception {
Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true));
SPVBlockStore store = new SPVBlockStore(TESTNET, blockStoreFile);
// Build a new block.
Address to = new ECKey().toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
StoredBlock genesis = store.getChainHead();
StoredBlock b1 = genesis.build(genesis.getHeader().createNextBlock(to).cloneAsHeader());
store.put(b1);
store.setChainHead(b1);
assertEquals(b1.getHeader().getHash(), store.getChainHead().getHeader().getHash());
store.clear();
assertNull(store.get(b1.getHeader().getHash()));
assertEquals(TESTNET.getGenesisBlock().getHash(), store.getChainHead().getHeader().getHash());
store.close();
}
@Test
public void oneStoreDelete() throws Exception {
SPVBlockStore store = new SPVBlockStore(TESTNET, blockStoreFile);
store.close();
boolean deleted = blockStoreFile.delete();
if (!PlatformUtils.isWindows()) {
// TODO: Deletion is failing on Windows
assertTrue(deleted);
}
}
}
| 7,644
| 38.407216
| 118
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/store/WalletProtobufSerializerTest.java
|
/*
* Copyright 2012 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.store;
import com.google.common.io.ByteStreams;
import com.google.protobuf.ByteString;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.internal.ByteUtils;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.base.Address;
import org.bitcoinj.core.Block;
import org.bitcoinj.core.BlockChain;
import org.bitcoinj.core.BlockTest;
import org.bitcoinj.base.Coin;
import org.bitcoinj.core.Context;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.PeerAddress;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.Transaction.Purpose;
import org.bitcoinj.core.TransactionConfidence;
import org.bitcoinj.core.TransactionConfidence.ConfidenceType;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.script.ScriptBuilder;
import org.bitcoinj.testing.FakeTxBuilder;
import org.bitcoinj.testing.FooWalletExtension;
import org.bitcoinj.utils.BriefLogFormatter;
import org.bitcoinj.utils.Threading;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.KeyChain;
import org.bitcoinj.wallet.KeyChainGroup;
import org.bitcoinj.wallet.Protos;
import org.bitcoinj.wallet.UnreadableWalletException;
import org.bitcoinj.wallet.Wallet;
import org.bitcoinj.wallet.WalletExtension;
import org.bitcoinj.wallet.WalletProtobufSerializer;
import org.bitcoinj.wallet.WalletTransaction;
import org.bitcoinj.wallet.WalletTransaction.Pool;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import static org.bitcoinj.base.Coin.COIN;
import static org.bitcoinj.base.Coin.FIFTY_COINS;
import static org.bitcoinj.testing.FakeTxBuilder.createFakeTx;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class WalletProtobufSerializerTest {
private static final NetworkParameters TESTNET = TestNet3Params.get();
private static final NetworkParameters MAINNET = MainNetParams.get();
private ECKey myKey;
private ECKey myWatchedKey;
private Address myAddress;
private Wallet myWallet;
public static String WALLET_DESCRIPTION = "The quick brown fox lives in \u4f26\u6566"; // Beijing in Chinese
private Instant mScriptCreationTime;
@BeforeClass
public static void setUpClass() {
TimeUtils.clearMockClock();
Context.propagate(new Context());
}
@Before
public void setUp() {
BriefLogFormatter.initVerbose();
myWatchedKey = new ECKey();
myKey = new ECKey();
myKey.setCreationTime(Instant.ofEpochSecond(123456789L));
myAddress = myKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
myWallet = new Wallet(BitcoinNetwork.TESTNET, KeyChainGroup.builder(BitcoinNetwork.TESTNET).fromRandom(ScriptType.P2PKH).build());
myWallet.importKey(myKey);
mScriptCreationTime = TimeUtils.currentTime().minusSeconds(1234);
myWallet.addWatchedAddress(myWatchedKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET), mScriptCreationTime);
myWallet.setDescription(WALLET_DESCRIPTION);
}
@Test
public void empty() throws Exception {
// Check the base case of a wallet with one key and no transactions.
Wallet wallet1 = roundTrip(myWallet);
assertEquals(0, wallet1.getTransactions(true).size());
assertEquals(Coin.ZERO, wallet1.getBalance());
ECKey foundKey = wallet1.findKeyFromPubKeyHash(myKey.getPubKeyHash(), null);
assertArrayEquals(myKey.getPubKey(), foundKey.getPubKey());
assertArrayEquals(myKey.getPrivKeyBytes(), foundKey.getPrivKeyBytes());
assertEquals(myKey.creationTime(), foundKey.creationTime());
assertEquals(mScriptCreationTime.truncatedTo(ChronoUnit.MILLIS),
wallet1.getWatchedScripts().get(0).creationTime().get());
assertEquals(1, wallet1.getWatchedScripts().size());
assertEquals(ScriptBuilder.createOutputScript(myWatchedKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET)),
wallet1.getWatchedScripts().get(0));
assertEquals(WALLET_DESCRIPTION, wallet1.getDescription());
}
@Test
public void oneTx() throws Exception {
// Check basic tx serialization.
Coin v1 = COIN;
Transaction t1 = createFakeTx(TESTNET.network(), v1, myAddress);
t1.getConfidence().markBroadcastBy(PeerAddress.simple(InetAddress.getByName("1.2.3.4"), TESTNET.getPort()));
t1.getConfidence().markBroadcastBy(PeerAddress.simple(InetAddress.getByName("5.6.7.8"), TESTNET.getPort()));
t1.getConfidence().setSource(TransactionConfidence.Source.NETWORK);
myWallet.receivePending(t1, null);
Wallet wallet1 = roundTrip(myWallet);
assertEquals(1, wallet1.getTransactions(true).size());
assertEquals(v1, wallet1.getBalance(Wallet.BalanceType.ESTIMATED));
Transaction t1copy = wallet1.getTransaction(t1.getTxId());
assertArrayEquals(t1.serialize(), t1copy.serialize());
assertEquals(2, t1copy.getConfidence().numBroadcastPeers());
assertNotNull(t1copy.getConfidence().lastBroadcastTime());
assertEquals(TransactionConfidence.Source.NETWORK, t1copy.getConfidence().getSource());
Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(myWallet);
assertEquals(Protos.Key.Type.ORIGINAL, walletProto.getKey(0).getType());
assertEquals(0, walletProto.getExtensionCount());
assertEquals(1, walletProto.getTransactionCount());
assertEquals(6, walletProto.getKeyCount());
Protos.Transaction t1p = walletProto.getTransaction(0);
assertEquals(0, t1p.getBlockHashCount());
assertArrayEquals(t1.getTxId().getBytes(), t1p.getHash().toByteArray());
assertEquals(Protos.Transaction.Pool.PENDING, t1p.getPool());
assertFalse(t1p.hasLockTime());
assertFalse(t1p.getTransactionInput(0).hasSequence());
assertArrayEquals(t1.getInput(0).getOutpoint().hash().getBytes(),
t1p.getTransactionInput(0).getTransactionOutPointHash().toByteArray());
assertEquals(0, t1p.getTransactionInput(0).getTransactionOutPointIndex());
assertEquals(t1p.getTransactionOutput(0).getValue(), v1.value);
}
@Test
public void raiseFeeTx() throws Exception {
// Check basic tx serialization.
Coin v1 = COIN;
Transaction t1 = createFakeTx(TESTNET.network(), v1, myAddress);
t1.setPurpose(Purpose.RAISE_FEE);
myWallet.receivePending(t1, null);
Wallet wallet1 = roundTrip(myWallet);
Transaction t1copy = wallet1.getTransaction(t1.getTxId());
assertEquals(Purpose.RAISE_FEE, t1copy.getPurpose());
}
@Test
public void doubleSpend() throws Exception {
// Check that we can serialize double spends correctly, as this is a slightly tricky case.
FakeTxBuilder.DoubleSpends doubleSpends = FakeTxBuilder.createFakeDoubleSpendTxns(myAddress);
// t1 spends to our wallet.
myWallet.receivePending(doubleSpends.t1, null);
// t2 rolls back t1 and spends somewhere else.
myWallet.receiveFromBlock(doubleSpends.t2, null, BlockChain.NewBlockType.BEST_CHAIN, 0);
Wallet wallet1 = roundTrip(myWallet);
assertEquals(1, wallet1.getTransactions(true).size());
Transaction t1 = wallet1.getTransaction(doubleSpends.t1.getTxId());
assertEquals(ConfidenceType.DEAD, t1.getConfidence().getConfidenceType());
assertEquals(Coin.ZERO, wallet1.getBalance());
// TODO: Wallet should store overriding transactions even if they are not wallet-relevant.
// assertEquals(doubleSpends.t2, t1.getConfidence().getOverridingTransaction());
}
@Test
public void testKeys() throws Exception {
for (int i = 0 ; i < 20 ; i++) {
myKey = new ECKey();
myAddress = myKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
myWallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
myWallet.importKey(myKey);
Wallet wallet1 = roundTrip(myWallet);
ECKey foundKey = wallet1.findKeyFromPubKeyHash(myKey.getPubKeyHash(), null);
assertArrayEquals(myKey.getPubKey(), foundKey.getPubKey());
assertArrayEquals(myKey.getPrivKeyBytes(), foundKey.getPrivKeyBytes());
}
}
@Test
public void testLastBlockSeenHash() throws Exception {
// Test the lastBlockSeenHash field works.
// LastBlockSeenHash should be empty if never set.
Wallet wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
Protos.Wallet walletProto = new WalletProtobufSerializer().walletToProto(wallet);
ByteString lastSeenBlockHash = walletProto.getLastSeenBlockHash();
assertTrue(lastSeenBlockHash.isEmpty());
// Create a block.
Block block = TESTNET.getDefaultSerializer().makeBlock(ByteBuffer.wrap(
ByteStreams.toByteArray(BlockTest.class.getResourceAsStream("block_testnet700000.dat"))));
Sha256Hash blockHash = block.getHash();
wallet.setLastBlockSeenHash(blockHash);
wallet.setLastBlockSeenHeight(1);
// Roundtrip the wallet and check it has stored the blockHash.
Wallet wallet1 = roundTrip(wallet);
assertEquals(blockHash, wallet1.getLastBlockSeenHash());
assertEquals(1, wallet1.getLastBlockSeenHeight());
// Test the Satoshi genesis block (hash of all zeroes) is roundtripped ok.
Block genesisBlock = MAINNET.getGenesisBlock();
wallet.setLastBlockSeenHash(genesisBlock.getHash());
Wallet wallet2 = roundTrip(wallet);
assertEquals(genesisBlock.getHash(), wallet2.getLastBlockSeenHash());
}
@Test
public void testSequenceNumber() throws Exception {
Wallet wallet = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
Transaction tx1 = createFakeTx(TESTNET.network(), Coin.COIN, wallet.currentReceiveAddress());
tx1.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE);
wallet.receivePending(tx1, null);
Transaction tx2 = createFakeTx(TESTNET.network(), Coin.COIN, wallet.currentReceiveAddress());
tx2.getInput(0).setSequenceNumber(TransactionInput.NO_SEQUENCE - 1);
wallet.receivePending(tx2, null);
Wallet walletCopy = roundTrip(wallet);
Transaction tx1copy = Objects.requireNonNull(walletCopy.getTransaction(tx1.getTxId()));
assertEquals(TransactionInput.NO_SEQUENCE, tx1copy.getInput(0).getSequenceNumber());
Transaction tx2copy = Objects.requireNonNull(walletCopy.getTransaction(tx2.getTxId()));
assertEquals(TransactionInput.NO_SEQUENCE - 1, tx2copy.getInput(0).getSequenceNumber());
}
@Test
public void testAppearedAtChainHeightDepthAndWorkDone() throws Exception {
// Test the TransactionConfidence appearedAtChainHeight, depth and workDone field are stored.
Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true));
BlockChain chain = new BlockChain(TESTNET, myWallet, new MemoryBlockStore(TESTNET.getGenesisBlock()));
final ArrayList<Transaction> txns = new ArrayList<>(2);
myWallet.addCoinsReceivedEventListener((wallet, tx, prevBalance, newBalance) -> txns.add(tx));
// Start by building two blocks on top of the genesis block.
Block b1 = TESTNET.getGenesisBlock().createNextBlock(myAddress);
BigInteger work1 = b1.getWork();
assertTrue(work1.signum() > 0);
Block b2 = b1.createNextBlock(myAddress);
BigInteger work2 = b2.getWork();
assertTrue(work2.signum() > 0);
assertTrue(chain.add(b1));
assertTrue(chain.add(b2));
// We now have the following chain:
// genesis -> b1 -> b2
// Check the transaction confidence levels are correct before wallet roundtrip.
Threading.waitForUserCode();
assertEquals(2, txns.size());
TransactionConfidence confidence0 = txns.get(0).getConfidence();
TransactionConfidence confidence1 = txns.get(1).getConfidence();
assertEquals(1, confidence0.getAppearedAtChainHeight());
assertEquals(2, confidence1.getAppearedAtChainHeight());
assertEquals(2, confidence0.getDepthInBlocks());
assertEquals(1, confidence1.getDepthInBlocks());
// Roundtrip the wallet and check it has stored the depth and workDone.
Wallet rebornWallet = roundTrip(myWallet);
Set<Transaction> rebornTxns = rebornWallet.getTransactions(false);
assertEquals(2, rebornTxns.size());
// The transactions are not guaranteed to be in the same order so sort them to be in chain height order if required.
Iterator<Transaction> it = rebornTxns.iterator();
Transaction txA = it.next();
Transaction txB = it.next();
Transaction rebornTx0, rebornTx1;
if (txA.getConfidence().getAppearedAtChainHeight() == 1) {
rebornTx0 = txA;
rebornTx1 = txB;
} else {
rebornTx0 = txB;
rebornTx1 = txA;
}
TransactionConfidence rebornConfidence0 = rebornTx0.getConfidence();
TransactionConfidence rebornConfidence1 = rebornTx1.getConfidence();
assertEquals(1, rebornConfidence0.getAppearedAtChainHeight());
assertEquals(2, rebornConfidence1.getAppearedAtChainHeight());
assertEquals(2, rebornConfidence0.getDepthInBlocks());
assertEquals(1, rebornConfidence1.getDepthInBlocks());
}
private static Wallet roundTrip(Wallet wallet) throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
new WalletProtobufSerializer().writeWallet(wallet, output);
ByteArrayInputStream test = new ByteArrayInputStream(output.toByteArray());
assertTrue(WalletProtobufSerializer.isWallet(test));
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
return new WalletProtobufSerializer().readWallet(input);
}
@Test
public void testRoundTripNormalWallet() throws Exception {
Wallet wallet1 = roundTrip(myWallet);
assertEquals(0, wallet1.getTransactions(true).size());
assertEquals(Coin.ZERO, wallet1.getBalance());
ECKey foundKey = wallet1.findKeyFromPubKeyHash(myKey.getPubKeyHash(), null);
assertArrayEquals(myKey.getPubKey(), foundKey.getPubKey());
assertArrayEquals(myKey.getPrivKeyBytes(), foundKey.getPrivKeyBytes());
assertEquals(myKey.creationTime(), foundKey.creationTime());
}
@Test
public void testRoundTripWatchingWallet() throws Exception {
final String xpub = "tpubD9LrDvFDrB6wYNhbR2XcRRaT4yCa37TjBR3YthBQvrtEwEq6CKeEXUs3TppQd38rfxmxD1qLkC99iP3vKcKwLESSSYdFAftbrpuhSnsw6XM";
final Instant creationTime = Instant.ofEpochSecond(1457019819);
Wallet wallet = Wallet.fromWatchingKeyB58(BitcoinNetwork.TESTNET, xpub, creationTime);
Wallet wallet2 = roundTrip(wallet);
Wallet wallet3 = roundTrip(wallet2);
assertEquals(xpub, wallet.getWatchingKey().serializePubB58(TESTNET.network()));
assertEquals(creationTime, wallet.getWatchingKey().creationTime().get());
assertEquals(creationTime, wallet2.getWatchingKey().creationTime().get());
assertEquals(creationTime, wallet3.getWatchingKey().creationTime().get());
assertEquals(creationTime, wallet.earliestKeyCreationTime());
assertEquals(creationTime, wallet2.earliestKeyCreationTime());
assertEquals(creationTime, wallet3.earliestKeyCreationTime());
}
@Test
public void roundtripVersionTwoTransaction() throws Exception {
Transaction tx = Transaction.read(ByteBuffer.wrap(ByteUtils.parseHex(
"0200000001d7902864af9310420c6e606b814c8f89f7902d40c130594e85df2e757a7cc301070000006b483045022100ca1757afa1af85c2bb014382d9ce411e1628d2b3d478df9d5d3e9e93cb25dcdd02206c5d272b31a23baf64e82793ee5c816e2bbef251e733a638b630ff2331fc83ba0121026ac2316508287761befbd0f7495ea794b396dbc5b556bf276639f56c0bd08911feffffff0274730700000000001976a91456da2d038a098c42390c77ef163e1cc23aedf24088ac91062300000000001976a9148ebf3467b9a8d7ae7b290da719e61142793392c188ac22e00600")));
assertEquals(tx.getVersion(), 2);
assertEquals(tx.getTxId().toString(), "0321b1413ed9048199815bd6bc2650cab1a9e8d543f109a42c769b1f18df4174");
myWallet.addWalletTransaction(new WalletTransaction(Pool.UNSPENT, tx));
Wallet wallet1 = roundTrip(myWallet);
Transaction tx2 = wallet1.getTransaction(tx.getTxId());
assertEquals(Objects.requireNonNull(tx2).getVersion(), 2);
}
@Test
public void coinbaseTxns() throws Exception {
// Covers issue 420 where the outpoint index of a coinbase tx input was being mis-serialized.
Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true));
Block b = TESTNET.getGenesisBlock().createNextBlockWithCoinbase(Block.BLOCK_VERSION_GENESIS, myKey.getPubKey(), FIFTY_COINS, Block.BLOCK_HEIGHT_GENESIS);
Transaction coinbase = b.getTransactions().get(0);
assertTrue(coinbase.isCoinBase());
BlockChain chain = new BlockChain(TESTNET, myWallet, new MemoryBlockStore(TESTNET.getGenesisBlock()));
assertTrue(chain.add(b));
// Wallet now has a coinbase tx in it.
assertEquals(1, myWallet.getTransactions(true).size());
assertTrue(myWallet.getTransaction(coinbase.getTxId()).isCoinBase());
Wallet wallet2 = roundTrip(myWallet);
assertEquals(1, wallet2.getTransactions(true).size());
assertTrue(wallet2.getTransaction(coinbase.getTxId()).isCoinBase());
}
@Test
public void tags() throws Exception {
myWallet.setTag("foo", ByteString.copyFromUtf8("bar"));
assertEquals("bar", myWallet.getTag("foo").toStringUtf8());
myWallet = roundTrip(myWallet);
assertEquals("bar", myWallet.getTag("foo").toStringUtf8());
}
@Test
public void extensions() throws Exception {
myWallet.addExtension(new FooWalletExtension("com.whatever.required", true));
Protos.Wallet proto = new WalletProtobufSerializer().walletToProto(myWallet);
// Initial extension is mandatory: try to read it back into a wallet that doesn't know about it.
try {
new WalletProtobufSerializer().readWallet(BitcoinNetwork.TESTNET, null, proto);
fail();
} catch (UnreadableWalletException e) {
assertTrue(e.getMessage().contains("mandatory"));
}
Wallet wallet = new WalletProtobufSerializer().readWallet(BitcoinNetwork.TESTNET,
new WalletExtension[]{ new FooWalletExtension("com.whatever.required", true) },
proto);
assertTrue(wallet.getExtensions().containsKey("com.whatever.required"));
// Non-mandatory extensions are ignored if the wallet doesn't know how to read them.
Wallet wallet2 = Wallet.createDeterministic(BitcoinNetwork.TESTNET, ScriptType.P2PKH);
wallet2.addExtension(new FooWalletExtension("com.whatever.optional", false));
Protos.Wallet proto2 = new WalletProtobufSerializer().walletToProto(wallet2);
Wallet wallet5 = new WalletProtobufSerializer().readWallet(BitcoinNetwork.TESTNET, null, proto2);
assertEquals(0, wallet5.getExtensions().size());
}
@Test
public void extensionsWithError() throws Exception {
WalletExtension extension = new WalletExtension() {
@Override
public String getWalletExtensionID() {
return "test";
}
@Override
public boolean isWalletExtensionMandatory() {
return false;
}
@Override
public byte[] serializeWalletExtension() {
return new byte[0];
}
@Override
public void deserializeWalletExtension(Wallet containingWallet, byte[] data) throws Exception {
throw new NullPointerException(); // Something went wrong!
}
};
myWallet.addExtension(extension);
Protos.Wallet proto = new WalletProtobufSerializer().walletToProto(myWallet);
Wallet wallet = new WalletProtobufSerializer().readWallet(BitcoinNetwork.TESTNET, new WalletExtension[]{extension}, proto);
assertEquals(0, wallet.getExtensions().size());
}
@Test(expected = UnreadableWalletException.FutureVersion.class)
public void versions() throws Exception {
Protos.Wallet.Builder proto = Protos.Wallet.newBuilder(new WalletProtobufSerializer().walletToProto(myWallet));
proto.setVersion(2);
new WalletProtobufSerializer().readWallet(BitcoinNetwork.TESTNET, null, proto.build());
}
@Test
public void storeWitnessTransactions() throws Exception {
// 3 inputs, inputs 0 and 2 have witnesses but not input 1
Transaction tx = Transaction.read(ByteBuffer.wrap(ByteUtils.parseHex(
"02000000000103fc8a5bea59392369e8a1b635395e507a5cbaeffd926e6967a00d17c669aef1d3010000001716001403c80a334ed6a92cf400d8c708522ea0d6fa5593ffffffffc0166d2218a2613b5384fc2c31238b1b6fa337080a1384220734e1bfd3629d3f0100000000ffffffffc0166d2218a2613b5384fc2c31238b1b6fa337080a1384220734e1bfd3629d3f0200000000ffffffff01a086010000000000220020eb72e573a9513d982a01f0e6a6b53e92764db81a0c26d2be94c5fc5b69a0db7d02473044022048e895b7af715303ce273a2be03d6110ed69b5700679f4f036000f8ba6eddd2802205f780423fcce9b3632ed41681b0a86f5d123766b71f303558c39c1be5fe43e2601210259eb16169df80dbe5856d082a226d84a97d191c895f8046c3544df525028a874000220c0166d2218a2613b5384fc2c31238b1b6fa337080a1384220734e1bfd3629d3f20c0166d2218a2613b5384fc2c31238b1b6fa337080a1384220734e1bfd3629d3f00000000")));
assertTrue(tx.hasWitnesses());
assertEquals(tx.getTxId().toString(), "1c687396f4710f26206dbdd8bf07a28c76398be6750226ddfaf05a1a80d30034");
myWallet.addWalletTransaction(new WalletTransaction(Pool.UNSPENT, tx));
Wallet wallet1 = roundTrip(myWallet);
Transaction tx2 = wallet1.getTransaction(tx.getTxId());
assertEquals(tx.getInput(0).getWitness(), tx2.getInput(0).getWitness());
}
}
| 23,814
| 49.242616
| 774
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/AddressComparatorSortTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.base;
import org.bitcoinj.base.internal.StreamUtils;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
/**
* Test sorting of {@link Address} (both {{@link LegacyAddress} and {@link SegwitAddress}}) with
* the default comparators.
*/
public class AddressComparatorSortTest {
private static final AddressParser addressParser = new DefaultAddressParser();
/**
* A manually sorted list of address for verifying sorting with our default comparator.
* See {@link Address#compareTo}.
*/
private static final List<Address> correctlySortedAddresses = Stream.of(
// Main net, Legacy
"1Dorian4RoXcnBv9hnQ4Y2C1an6NJ4UrjX",
"1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P",
// Main net, Segwit
"bc1qgdjqv0av3q56jvd82tkdjpy7gdp9ut8tlqmgrpmv24sq90ecnvqqjwvw97",
"bc1q5shngj24323nsrmxv99st02na6srekfctt30ch",
// Test net, Legacy
"moneyqMan7uh8FqdCA2BV5yZ8qVrc9ikLP",
"mpexoDuSkGGqvqrkrjiFng38QPkJQVFyqv",
// Test net, Segwit
"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7",
"tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx"
).map(addressParser::parseAddressAnyNetwork)
.collect(StreamUtils.toUnmodifiableList());
@Test
public void testAddressComparisonSortOrder() {
// Shuffle the list and then sort with the built-in comparator
List<Address> shuffled = shuffled(correctlySortedAddresses); // Shuffled copy
List<Address> sortedAfterShuffle = sorted(shuffled); // Sorted copy of shuffled copy
assertEquals(correctlySortedAddresses, sortedAfterShuffle);
}
// shuffle an immutable list producing a new immutable list
private static List<Address> shuffled(List<Address> addresses) {
List<Address> shuffled = new ArrayList<>(addresses); // Make modifiable copy
Collections.shuffle(shuffled); // shuffle it
return Collections.unmodifiableList(shuffled); // Return unmodifiable view
}
// sort an immutable list producing a new immutable list
private static List<Address> sorted(List<Address> addresses) {
return addresses.stream() // stream it
.sorted() // sort it
.collect(StreamUtils.toUnmodifiableList());
}
}
| 3,349
| 41.405063
| 103
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/SegwitAddressTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.base;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.bitcoinj.base.exceptions.AddressFormatException;
import org.bitcoinj.base.internal.ByteUtils;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.ScriptBuilder;
import org.bitcoinj.script.ScriptPattern;
import org.junit.Test;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.bitcoinj.base.BitcoinNetwork.MAINNET;
import static org.bitcoinj.base.BitcoinNetwork.TESTNET;
import static org.bitcoinj.base.BitcoinNetwork.SIGNET;
import static org.bitcoinj.base.BitcoinNetwork.REGTEST;
public class SegwitAddressTest {
private static final AddressParser addressParser = new DefaultAddressParser();
@Test
public void equalsContract() {
EqualsVerifier.forClass(SegwitAddress.class)
.withPrefabValues(BitcoinNetwork.class, MAINNET, TESTNET)
.suppress(Warning.NULL_FIELDS)
.suppress(Warning.TRANSIENT_FIELDS)
.usingGetClass()
.verify();
}
@Test
public void example_p2wpkh_mainnet() {
String bech32 = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4";
SegwitAddress address = SegwitAddress.fromBech32(bech32, MAINNET);
assertEquals(MAINNET, address.network());
assertEquals("0014751e76e8199196d454941c45d1b3a323f1433bd6",
ByteUtils.formatHex(ScriptBuilder.createOutputScript(address).program()));
assertEquals(ScriptType.P2WPKH, address.getOutputScriptType());
assertEquals(bech32.toLowerCase(Locale.ROOT), address.toBech32());
assertEquals(bech32.toLowerCase(Locale.ROOT), address.toString());
}
@Test
public void example_p2wsh_mainnet() {
String bech32 = "bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3";
SegwitAddress address = SegwitAddress.fromBech32(bech32, MAINNET);
assertEquals(MAINNET, address.network());
assertEquals("00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262",
ByteUtils.formatHex(ScriptBuilder.createOutputScript(address).program()));
assertEquals(ScriptType.P2WSH, address.getOutputScriptType());
assertEquals(bech32.toLowerCase(Locale.ROOT), address.toBech32());
assertEquals(bech32.toLowerCase(Locale.ROOT), address.toString());
}
@Test
public void example_p2wpkh_testnet() {
String bech32 = "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx";
SegwitAddress address = SegwitAddress.fromBech32(bech32, TESTNET);
assertEquals(TESTNET, address.network());
assertEquals("0014751e76e8199196d454941c45d1b3a323f1433bd6",
ByteUtils.formatHex(ScriptBuilder.createOutputScript(address).program()));
assertEquals(ScriptType.P2WPKH, address.getOutputScriptType());
assertEquals(bech32.toLowerCase(Locale.ROOT), address.toBech32());
assertEquals(bech32.toLowerCase(Locale.ROOT), address.toString());
}
@Test
public void equalityOfEquivalentNetworks() {
String bech32 = "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx";
SegwitAddress a = SegwitAddress.fromBech32(bech32, TESTNET);
SegwitAddress b = SegwitAddress.fromBech32(bech32, SIGNET);
assertEquals(a, b);
assertEquals(a.toString(), b.toString());
}
@Test
public void example_p2wpkh_regtest() {
String bcrt1_bech32 = "bcrt1qspfueag7fvty7m8htuzare3xs898zvh30fttu2";
SegwitAddress address = SegwitAddress.fromBech32(bcrt1_bech32, REGTEST);
assertEquals(REGTEST, address.network());
assertEquals("00148053ccf51e4b164f6cf75f05d1e62681ca7132f1",
ByteUtils.formatHex(ScriptBuilder.createOutputScript(address).program()));
assertEquals(ScriptType.P2WPKH, address.getOutputScriptType());
assertEquals(bcrt1_bech32.toLowerCase(Locale.ROOT), address.toBech32());
assertEquals(bcrt1_bech32.toLowerCase(Locale.ROOT), address.toString());
}
@Test
public void example_p2wpkh_regtest_any_network() {
String bcrt1_bech32 = "bcrt1qspfueag7fvty7m8htuzare3xs898zvh30fttu2";
Address address = addressParser.parseAddressAnyNetwork(bcrt1_bech32);
assertEquals(REGTEST, address.network());
assertEquals("00148053ccf51e4b164f6cf75f05d1e62681ca7132f1",
ByteUtils.formatHex(ScriptBuilder.createOutputScript(address).program()));
assertEquals(ScriptType.P2WPKH, address.getOutputScriptType());
assertEquals(bcrt1_bech32.toLowerCase(Locale.ROOT), ((SegwitAddress)address).toBech32());
assertEquals(bcrt1_bech32.toLowerCase(Locale.ROOT), address.toString());
}
@Test
public void example_p2wsh_testnet() {
String bech32 = "tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7";
SegwitAddress address = SegwitAddress.fromBech32(bech32, TESTNET);
assertEquals(TESTNET, address.network());
assertEquals("00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262",
ByteUtils.formatHex(ScriptBuilder.createOutputScript(address).program()));
assertEquals(ScriptType.P2WSH, address.getOutputScriptType());
assertEquals(bech32.toLowerCase(Locale.ROOT), address.toBech32());
assertEquals(bech32.toLowerCase(Locale.ROOT), address.toString());
}
@Test
public void validAddresses() {
for (AddressData valid : VALID_ADDRESSES) {
SegwitAddress address = (SegwitAddress) addressParser.parseAddressAnyNetwork(valid.address);
assertEquals(valid.expectedNetwork, address.network());
assertEquals(valid.expectedScriptPubKey,
ByteUtils.formatHex(ScriptBuilder.createOutputScript(address).program()));
assertEquals(valid.address.toLowerCase(Locale.ROOT), address.toBech32());
if (valid.expectedWitnessVersion == 0) {
Script expectedScriptPubKey = Script.parse(ByteUtils.parseHex(valid.expectedScriptPubKey));
assertEquals(address, SegwitAddress.fromHash(valid.expectedNetwork,
ScriptPattern.extractHashFromP2WH(expectedScriptPubKey)));
}
assertEquals(valid.expectedWitnessVersion, address.getWitnessVersion());
}
}
private static class AddressData {
final String address;
final BitcoinNetwork expectedNetwork;
final String expectedScriptPubKey;
final int expectedWitnessVersion;
AddressData(String address, BitcoinNetwork expectedNetwork, String expectedScriptPubKey,
int expectedWitnessVersion) {
this.address = address;
this.expectedNetwork = expectedNetwork;
this.expectedScriptPubKey = expectedScriptPubKey;
this.expectedWitnessVersion = expectedWitnessVersion;
}
@Override
public String toString() {
StringBuilder s = new StringBuilder(this.getClass().getSimpleName()).append('{');
s.append("address=").append(address).append(',');
s.append("expected=").append(expectedNetwork.id()).append(',').append(expectedScriptPubKey).append(',').append(expectedWitnessVersion);
return s.append('}').toString();
}
}
private static AddressData[] VALID_ADDRESSES = {
// from BIP350 (includes the corrected BIP173 vectors):
new AddressData("BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4", MAINNET,
"0014751e76e8199196d454941c45d1b3a323f1433bd6", 0),
new AddressData("tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7", TESTNET,
"00201863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262", 0),
new AddressData("BC1SW50QGDZ25J", MAINNET, "6002751e", 16),
new AddressData("bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs", MAINNET, "5210751e76e8199196d454941c45d1b3a323", 2),
new AddressData("tb1qqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesrxh6hy", TESTNET,
"0020000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433", 0),
new AddressData("tb1pqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesf3hn0c", TESTNET,
"5120000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433", 1),
new AddressData("bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0", MAINNET,
"512079be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", 1),
};
@Test
public void invalidAddresses() {
for (String invalid : INVALID_ADDRESSES) {
try {
addressParser.parseAddressAnyNetwork(invalid);
fail(invalid);
} catch (AddressFormatException x) {
// expected
}
}
}
private static String[] INVALID_ADDRESSES = {
// from BIP173:
"tc1qw508d6qejxtdg4y5r3zarvary0c5xw7kg3g4ty", // Invalid human-readable part
"bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t5", // Invalid checksum
"BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2", // Invalid witness version
"bc1rw5uspcuh", // Invalid program length
"bc10w508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kw5rljs90", // Invalid program length
"BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P", // Invalid program length for witness version 0 (per BIP141)
"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7", // Mixed case
"bc1zw508d6qejxtdg4y5r3zarvaryvqyzf3du", // Zero padding of more than 4 bits
"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv", // Non-zero padding in 8-to-5 conversion
"bc1gmk9yu", // Empty data section
// from BIP350:
"tc1qw508d6qejxtdg4y5r3zarvary0c5xw7kg3g4ty", // Invalid human-readable part
"bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t5", // Invalid checksum
"BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2", // Invalid witness version
"bc1rw5uspcuh", // Invalid program length
"bc10w508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kw5rljs90", // Invalid program length
"BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P", // Invalid program length for witness version 0 (per BIP141)
"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sL5k7", // Mixed case
"bc1zw508d6qejxtdg4y5r3zarvaryvqyzf3du", // zero padding of more than 4 bits
"tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv", // Non-zero padding in 8-to-5 conversion
"bc1gmk9yu", // Empty data section
};
@Test(expected = AddressFormatException.InvalidDataLength.class)
public void fromBech32_version0_invalidLength() {
addressParser.parseAddressAnyNetwork("BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P");
}
@Test(expected = AddressFormatException.InvalidDataLength.class)
public void fromBech32_tooShort() {
addressParser.parseAddressAnyNetwork("bc1rw5uspcuh");
}
@Test(expected = AddressFormatException.InvalidDataLength.class)
public void fromBech32_tooLong() {
addressParser.parseAddressAnyNetwork("bc10w508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kw5rljs90");
}
@Test(expected = AddressFormatException.InvalidDataLength.class)
public void fromBech32m_taprootTooShort() {
// Taproot, valid bech32m encoding, checksum ok, padding ok, but no valid Segwit v1 program
// (this program is 20 bytes long, but only 32 bytes program length are valid for Segwit v1/Taproot)
String taprootAddressWith20BytesWitnessProgram = "bc1pqypqzqspqgqsyqgzqypqzqspqgqsyqgzzezy58";
SegwitAddress.fromBech32(taprootAddressWith20BytesWitnessProgram, MAINNET);
}
@Test(expected = AddressFormatException.InvalidDataLength.class)
public void fromBech32m_taprootTooLong() {
// Taproot, valid bech32m encoding, checksum ok, padding ok, but no valid Segwit v1 program
// (this program is 40 bytes long, but only 32 bytes program length are valid for Segwit v1/Taproot)
String taprootAddressWith40BytesWitnessProgram = "bc1p6t0pcqrq3mvedn884lgj9s2cm52xp9vtnlc89cv5x77f5l725rrdjhqrld6m6rza67j62a";
SegwitAddress.fromBech32(taprootAddressWith40BytesWitnessProgram, MAINNET);
}
@Test(expected = AddressFormatException.InvalidPrefix.class)
public void fromBech32_invalidHrp() {
addressParser.parseAddressAnyNetwork("tc1qw508d6qejxtdg4y5r3zarvary0c5xw7kg3g4ty");
}
@Test(expected = AddressFormatException.WrongNetwork.class)
public void fromBech32_wrongNetwork() {
SegwitAddress.fromBech32("bc1zw508d6qejxtdg4y5r3zarvaryvg6kdaj", TESTNET);
}
}
| 13,634
| 47.523132
| 147
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/Sha256HashTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.base;
import org.junit.Test;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import static org.junit.Assert.assertEquals;
public class Sha256HashTest {
@Test
public void readAndWrite() {
Sha256Hash hash = Sha256Hash.of(new byte[32]); // hash should be pseudo-random
ByteBuffer buf = ByteBuffer.allocate(Sha256Hash.LENGTH);
hash.write(buf);
((Buffer) buf).rewind();
Sha256Hash hashCopy = Sha256Hash.read(buf);
assertEquals(hash, hashCopy);
}
}
| 1,145
| 29.972973
| 86
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/Base58DecodeCheckedInvalidChecksumTest.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.base;
import org.bitcoinj.base.exceptions.AddressFormatException;
import org.junit.Test;
public class Base58DecodeCheckedInvalidChecksumTest {
@Test(expected = AddressFormatException.InvalidChecksum.class)
public void testDecodeChecked_invalidChecksum() {
Base58.decodeChecked("4stwEBjT6FYyVW");
}
}
| 976
| 31.566667
| 75
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/Base58EncodeTest.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.base;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertEquals;
import static org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class Base58EncodeTest {
private byte[] input;
private String expected;
public Base58EncodeTest(byte[] input, String expected) {
this.input = input;
this.expected = expected;
}
@Parameters
public static Collection<Object[]> parameters() {
return Arrays.asList(new Object[][]{
{"Hello World".getBytes(), "JxF12TrwUP45BMd"},
{BigInteger.valueOf(3471844090L).toByteArray(), "16Ho7Hs"},
{new byte[1], "1"},
{new byte[7], "1111111"},
{new byte[0], ""}
});
}
@Test
public void testEncode() {
assertEquals(expected, Base58.encode(input));
}
}
| 1,682
| 28.017241
| 75
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/CoinTest.java
|
/*
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.base;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.math.BigDecimal;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import static org.bitcoinj.base.BitcoinNetwork.MAX_MONEY;
import static org.bitcoinj.base.Coin.CENT;
import static org.bitcoinj.base.Coin.COIN;
import static org.bitcoinj.base.Coin.FIFTY_COINS;
import static org.bitcoinj.base.Coin.NEGATIVE_SATOSHI;
import static org.bitcoinj.base.Coin.SATOSHI;
import static org.bitcoinj.base.Coin.ZERO;
import static org.bitcoinj.base.Coin.btcToSatoshi;
import static org.bitcoinj.base.Coin.parseCoin;
import static org.bitcoinj.base.Coin.parseCoinInexact;
import static org.bitcoinj.base.Coin.satoshiToBtc;
import static org.bitcoinj.base.Coin.valueOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(JUnitParamsRunner.class)
public class CoinTest {
@Test
public void testParseCoin() {
// String version
assertEquals(CENT, parseCoin("0.01"));
assertEquals(CENT, parseCoin("1E-2"));
assertEquals(COIN.add(CENT), parseCoin("1.01"));
assertEquals(COIN.negate(), parseCoin("-1"));
try {
parseCoin("2E-20");
org.junit.Assert.fail("should not have accepted fractional satoshis");
} catch (IllegalArgumentException expected) {
} catch (Exception e) {
org.junit.Assert.fail("should throw IllegalArgumentException");
}
assertEquals(1, parseCoin("0.00000001").value);
assertEquals(1, parseCoin("0.000000010").value);
}
@Test(expected = IllegalArgumentException.class)
public void testParseCoinOverprecise() {
parseCoin("0.000000011");
}
@Test
public void testParseCoinInexact() {
assertEquals(1, parseCoinInexact("0.00000001").value);
assertEquals(1, parseCoinInexact("0.000000011").value);
}
@Test
public void testValueOf() {
// int version
assertEquals(CENT, valueOf(0, 1));
assertEquals(SATOSHI, valueOf(1));
assertEquals(NEGATIVE_SATOSHI, valueOf(-1));
assertEquals(MAX_MONEY, valueOf(MAX_MONEY.value));
assertEquals(MAX_MONEY.negate(), valueOf(MAX_MONEY.value * -1));
valueOf(MAX_MONEY.value + 1);
valueOf((MAX_MONEY.value * -1) - 1);
valueOf(Long.MAX_VALUE);
valueOf(Long.MIN_VALUE);
try {
valueOf(1, -1);
fail();
} catch (IllegalArgumentException e) {}
try {
valueOf(-1, 0);
fail();
} catch (IllegalArgumentException e) {}
}
@Test
public void testBtcToSatoshi() {
assertEquals(Long.MIN_VALUE, btcToSatoshi(new BigDecimal("-92233720368.54775808")));
assertEquals(0L, btcToSatoshi(BigDecimal.ZERO));
assertEquals(COIN.value, btcToSatoshi(BigDecimal.ONE));
assertEquals(Long.MAX_VALUE, btcToSatoshi(new BigDecimal("92233720368.54775807")));
}
@Test(expected = ArithmeticException.class)
public void testBtcToSatoshi_tooSmall() {
btcToSatoshi(new BigDecimal("-92233720368.54775809")); // .00000001 less than minimum value
}
@Test(expected = ArithmeticException.class)
public void testBtcToSatoshi_tooBig() {
btcToSatoshi(new BigDecimal("92233720368.54775808")); // .00000001 more than maximum value
}
@Test(expected = ArithmeticException.class)
public void testBtcToSatoshi_tooPrecise1() {
btcToSatoshi(new BigDecimal("0.000000001")); // More than SMALLEST_UNIT_EXPONENT precision
}
@Test(expected = ArithmeticException.class)
public void testBtcToSatoshi_tooPrecise2() {
btcToSatoshi(new BigDecimal("92233720368.547758079")); // More than SMALLEST_UNIT_EXPONENT precision
}
@Test
public void testSatoshiToBtc() {
assertThat(new BigDecimal("-92233720368.54775808"), Matchers.comparesEqualTo(satoshiToBtc(Long.MIN_VALUE)));
assertThat(new BigDecimal("-0.00000001"), Matchers.comparesEqualTo(satoshiToBtc(NEGATIVE_SATOSHI.value)));
assertThat(BigDecimal.ZERO, Matchers.comparesEqualTo(satoshiToBtc(0L)));
assertThat(new BigDecimal("0.00000001"), Matchers.comparesEqualTo(satoshiToBtc(SATOSHI.value)));
assertThat(BigDecimal.ONE, Matchers.comparesEqualTo(satoshiToBtc(COIN.value)));
assertThat(new BigDecimal(50), Matchers.comparesEqualTo(satoshiToBtc(FIFTY_COINS.value)));
assertThat(new BigDecimal("92233720368.54775807"), Matchers.comparesEqualTo(satoshiToBtc(Long.MAX_VALUE)));
}
@Test
public void testOfBtc() {
assertEquals(Coin.valueOf(Long.MIN_VALUE), Coin.ofBtc(new BigDecimal("-92233720368.54775808")));
assertEquals(ZERO, Coin.ofBtc(BigDecimal.ZERO));
assertEquals(COIN, Coin.ofBtc(BigDecimal.ONE));
assertEquals(Coin.valueOf(Long.MAX_VALUE), Coin.ofBtc(new BigDecimal("92233720368.54775807")));
}
@Test
public void testOperators() {
assertTrue(SATOSHI.isPositive());
assertFalse(SATOSHI.isNegative());
assertFalse(SATOSHI.isZero());
assertFalse(NEGATIVE_SATOSHI.isPositive());
assertTrue(NEGATIVE_SATOSHI.isNegative());
assertFalse(NEGATIVE_SATOSHI.isZero());
assertFalse(ZERO.isPositive());
assertFalse(ZERO.isNegative());
assertTrue(ZERO.isZero());
assertTrue(valueOf(2).isGreaterThan(valueOf(1)));
assertFalse(valueOf(2).isGreaterThan(valueOf(2)));
assertFalse(valueOf(1).isGreaterThan(valueOf(2)));
assertTrue(valueOf(1).isLessThan(valueOf(2)));
assertFalse(valueOf(2).isLessThan(valueOf(2)));
assertFalse(valueOf(2).isLessThan(valueOf(1)));
}
@Test(expected = ArithmeticException.class)
public void testMultiplicationOverflow() {
Coin.valueOf(Long.MAX_VALUE).multiply(2);
}
@Test(expected = ArithmeticException.class)
public void testMultiplicationUnderflow() {
Coin.valueOf(Long.MIN_VALUE).multiply(2);
}
@Test(expected = ArithmeticException.class)
public void testAdditionOverflow() {
Coin.valueOf(Long.MAX_VALUE).add(Coin.SATOSHI);
}
@Test(expected = ArithmeticException.class)
public void testSubtractionUnderflow() {
Coin.valueOf(Long.MIN_VALUE).subtract(Coin.SATOSHI);
}
@Test
public void testToBtc() {
assertThat(new BigDecimal("-92233720368.54775808"), Matchers.comparesEqualTo(Coin.valueOf(Long.MIN_VALUE).toBtc()));
assertThat(new BigDecimal("-0.00000001"), Matchers.comparesEqualTo(NEGATIVE_SATOSHI.toBtc()));
assertThat(BigDecimal.ZERO, Matchers.comparesEqualTo(ZERO.toBtc()));
assertThat(new BigDecimal("0.00000001"), Matchers.comparesEqualTo(SATOSHI.toBtc()));
assertThat(BigDecimal.ONE, Matchers.comparesEqualTo(COIN.toBtc()));
assertThat(new BigDecimal(50), Matchers.comparesEqualTo(FIFTY_COINS.toBtc()));
assertThat(new BigDecimal("92233720368.54775807"), Matchers.comparesEqualTo(Coin.valueOf(Long.MAX_VALUE).toBtc()));
}
@Test
public void testToFriendlyString() {
assertEquals("1.00 BTC", COIN.toFriendlyString());
assertEquals("1.23 BTC", valueOf(1, 23).toFriendlyString());
assertEquals("0.001 BTC", COIN.divide(1000).toFriendlyString());
assertEquals("-1.23 BTC", valueOf(1, 23).negate().toFriendlyString());
}
/**
* Test the bitcoinValueToPlainString amount formatter
*/
@Test
public void testToPlainString() {
assertEquals("0.0015", Coin.valueOf(150000).toPlainString());
assertEquals("1.23", parseCoin("1.23").toPlainString());
assertEquals("0.1", parseCoin("0.1").toPlainString());
assertEquals("1.1", parseCoin("1.1").toPlainString());
assertEquals("21.12", parseCoin("21.12").toPlainString());
assertEquals("321.123", parseCoin("321.123").toPlainString());
assertEquals("4321.1234", parseCoin("4321.1234").toPlainString());
assertEquals("54321.12345", parseCoin("54321.12345").toPlainString());
assertEquals("654321.123456", parseCoin("654321.123456").toPlainString());
assertEquals("7654321.1234567", parseCoin("7654321.1234567").toPlainString());
assertEquals("87654321.12345678", parseCoin("87654321.12345678").toPlainString());
// check there are no trailing zeros
assertEquals("1", parseCoin("1.0").toPlainString());
assertEquals("2", parseCoin("2.00").toPlainString());
assertEquals("3", parseCoin("3.000").toPlainString());
assertEquals("4", parseCoin("4.0000").toPlainString());
assertEquals("5", parseCoin("5.00000").toPlainString());
assertEquals("6", parseCoin("6.000000").toPlainString());
assertEquals("7", parseCoin("7.0000000").toPlainString());
assertEquals("8", parseCoin("8.00000000").toPlainString());
}
@Test
@Parameters(method = "readAndWriteTestVectors")
public void readAndWrite(Coin coin) {
ByteBuffer buf = ByteBuffer.allocate(Coin.BYTES);
coin.write(buf);
assertFalse(buf.hasRemaining());
((Buffer) buf).rewind();
Coin coinCopy = Coin.read(buf);
assertFalse(buf.hasRemaining());
assertEquals(coin, coinCopy);
}
private Coin[] readAndWriteTestVectors() {
return new Coin[] {
Coin.ofSat(0),
Coin.ofSat(10),
Coin.ofSat(-10),
Coin.ofSat(Long.MAX_VALUE),
Coin.ofSat(Long.MIN_VALUE)
};
}
}
| 10,444
| 39.173077
| 125
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/Base58DecodeCheckedTest.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.base;
import org.bitcoinj.base.exceptions.AddressFormatException;
import org.junit.Assume;
import org.junit.Rule;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
@RunWith(Theories.class)
public class Base58DecodeCheckedTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
private static final String BASE58_ALPHABET = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
private boolean containsOnlyValidBase58Chars(String input) {
for(String s : input.split("")) {
if (!BASE58_ALPHABET.contains(s)) {
return false;
}
}
return true;
}
@DataPoints
public static String[] parameters = new String[]{
"4stwEBjT6FYyVV",
"93VYUMzRG9DdbRP72uQXjaWibbQwygnvaCu9DumcqDjGybD864T",
"J0F12TrwUP45BMd",
"4s"
};
@Theory
public void testDecodeChecked(String input) {
Assume.assumeTrue(containsOnlyValidBase58Chars(input));
Assume.assumeTrue(input.length() > 4);
Base58.decodeChecked(input);
}
@Theory
public void decode_invalidCharacter_notInAlphabet(String input) {
Assume.assumeFalse(containsOnlyValidBase58Chars(input));
Assume.assumeTrue(input.length() > 4);
expectedException.expect(AddressFormatException.InvalidCharacter.class);
Base58.decodeChecked(input);
}
@Theory
public void testDecodeChecked_shortInput(String input) {
Assume.assumeTrue(containsOnlyValidBase58Chars(input));
Assume.assumeTrue(input.length() < 4);
expectedException.expect(AddressFormatException.InvalidDataLength.class);
Base58.decodeChecked(input);
}
}
| 2,561
| 32.710526
| 111
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/LegacyAddressTest.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.base;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.bitcoinj.base.exceptions.AddressFormatException;
import org.bitcoinj.base.internal.ByteUtils;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.params.Networks;
import org.bitcoinj.script.ScriptBuilder;
import org.bitcoinj.script.ScriptPattern;
import org.bitcoinj.testing.MockAltNetworkParams;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.bitcoinj.base.BitcoinNetwork.MAINNET;
import static org.bitcoinj.base.BitcoinNetwork.TESTNET;
import static org.bitcoinj.base.BitcoinNetwork.SIGNET;
import static org.bitcoinj.base.BitcoinNetwork.REGTEST;
public class LegacyAddressTest {
@Test
public void equalsContract() {
EqualsVerifier.forClass(LegacyAddress.class)
.withPrefabValues(BitcoinNetwork.class, MAINNET, TESTNET)
.suppress(Warning.NULL_FIELDS)
.suppress(Warning.TRANSIENT_FIELDS)
.usingGetClass()
.verify();
}
@Test
public void stringification() {
// Test a testnet address.
LegacyAddress a = LegacyAddress.fromPubKeyHash(TESTNET, ByteUtils.parseHex("fda79a24e50ff70ff42f7d89585da5bd19d9e5cc"));
assertEquals("n4eA2nbYqErp7H6jebchxAN59DmNpksexv", a.toString());
assertEquals(ScriptType.P2PKH, a.getOutputScriptType());
LegacyAddress b = LegacyAddress.fromPubKeyHash(MAINNET, ByteUtils.parseHex("4a22c3c4cbb31e4d03b15550636762bda0baf85a"));
assertEquals("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL", b.toString());
assertEquals(ScriptType.P2PKH, b.getOutputScriptType());
}
@Test
public void decoding() {
LegacyAddress a = LegacyAddress.fromBase58("n4eA2nbYqErp7H6jebchxAN59DmNpksexv", TESTNET);
assertEquals("fda79a24e50ff70ff42f7d89585da5bd19d9e5cc", ByteUtils.formatHex(a.getHash()));
LegacyAddress b = LegacyAddress.fromBase58("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL", MAINNET);
assertEquals("4a22c3c4cbb31e4d03b15550636762bda0baf85a", ByteUtils.formatHex(b.getHash()));
}
@Test
public void equalityOfEquivalentNetworks() {
LegacyAddress a = LegacyAddress.fromBase58("n4eA2nbYqErp7H6jebchxAN59DmNpksexv", TESTNET);
LegacyAddress b = LegacyAddress.fromBase58("n4eA2nbYqErp7H6jebchxAN59DmNpksexv", SIGNET);
LegacyAddress c = LegacyAddress.fromBase58("n4eA2nbYqErp7H6jebchxAN59DmNpksexv", REGTEST);
assertEquals(a, b);
assertEquals(b, c);
assertEquals(a, c);
assertEquals(a.toString(), b.toString());
assertEquals(b.toString(), c.toString());
assertEquals(a.toString(), c.toString());
}
@Test
public void errorPaths() {
// Check what happens if we try and decode garbage.
try {
LegacyAddress.fromBase58("this is not a valid address!", TESTNET);
fail();
} catch (AddressFormatException.WrongNetwork e) {
fail();
} catch (AddressFormatException e) {
// Success.
}
// Check the empty case.
try {
LegacyAddress.fromBase58("", TESTNET);
fail();
} catch (AddressFormatException.WrongNetwork e) {
fail();
} catch (AddressFormatException e) {
// Success.
}
// Check the case of a mismatched network.
try {
LegacyAddress.fromBase58("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL", TESTNET);
fail();
} catch (AddressFormatException.WrongNetwork e) {
// Success.
} catch (AddressFormatException e) {
fail();
}
}
@Test
@Deprecated
// Test a deprecated method just to make sure we didn't break it
public void getNetworkViaParameters() {
NetworkParameters params = LegacyAddress.getParametersFromAddress("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL");
assertEquals(MAINNET.id(), params.getId());
params = LegacyAddress.getParametersFromAddress("n4eA2nbYqErp7H6jebchxAN59DmNpksexv");
assertEquals(TESTNET.id(), params.getId());
}
@Test
public void getNetwork() {
AddressParser parser = new DefaultAddressParser();
Network mainNet = parser.parseAddressAnyNetwork("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL").network();
assertEquals(MAINNET, mainNet);
Network testNet = parser.parseAddressAnyNetwork("n4eA2nbYqErp7H6jebchxAN59DmNpksexv").network();
assertEquals(TESTNET, testNet);
}
@Test
public void getAltNetworkUsingNetworks() {
// An alternative network
NetworkParameters altNetParams = new MockAltNetworkParams();
// Add new network params, this MODIFIES GLOBAL STATE in `Networks`
Networks.register(altNetParams);
try {
// Check if can parse address
Address altAddress = DefaultAddressParser.fromNetworks().parseAddressAnyNetwork("LLxSnHLN2CYyzB5eWTR9K9rS9uWtbTQFb6");
assertEquals(altNetParams.getId(), altAddress.network().id());
// Check if main network works as before
Address mainAddress = new DefaultAddressParser().parseAddressAnyNetwork("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL");
assertEquals(MAINNET.id(), mainAddress.network().id());
} finally {
// Unregister network. Do this in a finally block so other tests don't fail if the try block fails to complete
Networks.unregister(altNetParams);
}
try {
DefaultAddressParser.fromNetworks().parseAddressAnyNetwork("LLxSnHLN2CYyzB5eWTR9K9rS9uWtbTQFb6");
fail();
} catch (AddressFormatException e) { }
}
@Test
public void getAltNetworkUsingList() {
// An alternative network
NetworkParameters altNetParams = new MockAltNetworkParams();
// Create a parser that knows about the new network (this does not modify global state)
List<Network> nets = new ArrayList<>(DefaultAddressParser.DEFAULT_NETWORKS_LEGACY);
nets.add(altNetParams.network());
AddressParser customParser = new DefaultAddressParser(DefaultAddressParser.DEFAULT_NETWORKS_SEGWIT, nets);
// Unfortunately for NetworkParameters.of() to work properly we still have to modify gobal state
Networks.register(altNetParams);
try {
// Check if can parse address
Address altAddress = customParser.parseAddressAnyNetwork("LLxSnHLN2CYyzB5eWTR9K9rS9uWtbTQFb6");
assertEquals(altNetParams.getId(), altAddress.network().id());
// Check if main network works with custom parser
Address mainAddress = customParser.parseAddressAnyNetwork("17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL");
assertEquals(MAINNET.id(), mainAddress.network().id());
} finally {
// Unregister network. Do this in a finally block so other tests don't fail if the try block fails to complete
Networks.unregister(altNetParams);
}
try {
new DefaultAddressParser().parseAddressAnyNetwork("LLxSnHLN2CYyzB5eWTR9K9rS9uWtbTQFb6");
fail();
} catch (AddressFormatException e) { }
}
@Test
public void p2shAddress() {
// Test that we can construct P2SH addresses
LegacyAddress mainNetP2SHAddress = LegacyAddress.fromBase58("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU", MAINNET);
assertEquals(mainNetP2SHAddress.getVersion(), NetworkParameters.of(MAINNET).getP2SHHeader());
assertEquals(ScriptType.P2SH, mainNetP2SHAddress.getOutputScriptType());
LegacyAddress testNetP2SHAddress = LegacyAddress.fromBase58("2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe", TESTNET);
assertEquals(testNetP2SHAddress.getVersion(), NetworkParameters.of(TESTNET).getP2SHHeader());
assertEquals(ScriptType.P2SH, testNetP2SHAddress.getOutputScriptType());
AddressParser parser = new DefaultAddressParser();
// Test that we can determine what network a P2SH address belongs to
Network mainNet = parser.parseAddressAnyNetwork("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU").network();
assertEquals(MAINNET, mainNet);
Network testNet = parser.parseAddressAnyNetwork("2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe").network();
assertEquals(TESTNET, testNet);
// Test that we can convert them from hashes
byte[] hex = ByteUtils.parseHex("2ac4b0b501117cc8119c5797b519538d4942e90e");
LegacyAddress a = LegacyAddress.fromScriptHash(MAINNET, hex);
assertEquals("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU", a.toString());
LegacyAddress b = LegacyAddress.fromScriptHash(TESTNET, ByteUtils.parseHex("18a0e827269b5211eb51a4af1b2fa69333efa722"));
assertEquals("2MuVSxtfivPKJe93EC1Tb9UhJtGhsoWEHCe", b.toString());
LegacyAddress c = LegacyAddress.fromScriptHash(MAINNET,
ScriptPattern.extractHashFromP2SH(ScriptBuilder.createP2SHOutputScript(hex)));
assertEquals("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU", c.toString());
}
@Test
public void p2shAddressFromScriptHash() {
byte[] p2shScriptHash = ByteUtils.parseHex("defdb71910720a2c854529019189228b4245eddd");
LegacyAddress address = LegacyAddress.fromScriptHash(MAINNET, p2shScriptHash);
assertEquals("3N25saC4dT24RphDAwLtD8LUN4E2gZPJke", address.toString());
}
@Test
public void roundtripBase58() {
String base58 = "17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL";
assertEquals(base58, LegacyAddress.fromBase58(base58, MAINNET).toBase58());
}
@Test
public void comparisonLessThan() {
LegacyAddress a = LegacyAddress.fromBase58("1Dorian4RoXcnBv9hnQ4Y2C1an6NJ4UrjX", MAINNET);
LegacyAddress b = LegacyAddress.fromBase58("1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P", MAINNET);
int result = a.compareTo(b);
assertTrue(result < 0);
}
@Test
public void comparisonGreaterThan() {
LegacyAddress a = LegacyAddress.fromBase58("1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P", MAINNET);
LegacyAddress b = LegacyAddress.fromBase58("1Dorian4RoXcnBv9hnQ4Y2C1an6NJ4UrjX", MAINNET);
int result = a.compareTo(b);
assertTrue(result > 0);
}
@Test
public void comparisonNotEquals() {
// These addresses only differ by version byte
LegacyAddress a = LegacyAddress.fromBase58("14wivxvNTv9THhewPotsooizZawaWbEKE2", MAINNET);
LegacyAddress b = LegacyAddress.fromBase58("35djrWQp1pTqNsMNWuZUES5vi7EJ74m9Eh", MAINNET);
int result = a.compareTo(b);
assertTrue(result != 0);
}
@Test
public void comparisonBytesVsString() throws Exception {
BufferedReader dataSetReader = new BufferedReader(
new InputStreamReader(getClass().getResourceAsStream("LegacyAddressTestDataset.txt")));
String line;
while ((line = dataSetReader.readLine()) != null) {
String addr[] = line.split(",");
LegacyAddress first = LegacyAddress.fromBase58(addr[0], MAINNET);
LegacyAddress second = LegacyAddress.fromBase58(addr[1], MAINNET);
assertTrue(first.compareTo(second) < 0);
assertTrue(first.toString().compareTo(second.toString()) < 0);
}
}
}
| 12,226
| 42.204947
| 130
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/Bech32Test.java
|
/*
* Copyright 2018 Coinomi Ltd
*
* 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.
*/
package org.bitcoinj.base;
import org.bitcoinj.base.exceptions.AddressFormatException;
import org.junit.Test;
import java.util.Locale;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class Bech32Test {
@Test
public void valid_bech32() {
for (String valid : VALID_BECH32)
valid(valid);
}
@Test
public void valid_bech32m() {
for (String valid : VALID_BECH32M)
valid(valid);
}
private void valid(String valid) {
Bech32.Bech32Data bechData = Bech32.decode(valid);
String recode = Bech32.encode(bechData);
assertEquals(String.format("Failed to roundtrip '%s' -> '%s'", valid, recode),
valid.toLowerCase(Locale.ROOT), recode.toLowerCase(Locale.ROOT));
// Test encoding with an uppercase HRP
recode = Bech32.encode(bechData.encoding, bechData.hrp.toUpperCase(Locale.ROOT), bechData.data);
assertEquals(String.format("Failed to roundtrip '%s' -> '%s'", valid, recode),
valid.toLowerCase(Locale.ROOT), recode.toLowerCase(Locale.ROOT));
}
private static final String[] VALID_BECH32 = {
"A12UEL5L",
"a12uel5l",
"an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1tt5tgs",
"abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw",
"11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j",
"split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w",
"?1ezyfcl",
};
private static final String[] VALID_BECH32M = {
"A1LQFN3A",
"a1lqfn3a",
"an83characterlonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11sg7hg6",
"abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqzd3ryx",
"11llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllludsr8",
"split1checkupstagehandshakeupstreamerranterredcaperredlc445v",
"?1v759aa"
};
@Test
public void invalid_bech32() {
for (String invalid : INVALID_BECH32)
invalid(invalid);
}
@Test
public void invalid_bech32m() {
for (String invalid : INVALID_BECH32M)
invalid(invalid);
}
private void invalid(String invalid) {
try {
Bech32.decode(invalid);
fail(String.format("Parsed an invalid code: '%s'", invalid));
} catch (AddressFormatException x) {
/* expected */
}
}
private static final String[] INVALID_BECH32 = {
" 1nwldj5", // HRP character out of range
new String(new char[] { 0x7f }) + "1axkwrx", // HRP character out of range
new String(new char[] { 0x80 }) + "1eym55h", // HRP character out of range
"an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx", // overall max length exceeded
"pzry9x0s0muk", // No separator character
"1pzry9x0s0muk", // Empty HRP
"x1b4n0q5v", // Invalid data character
"li1dgmt3", // Too short checksum
"de1lg7wt" + new String(new char[] { 0xff }), // Invalid character in checksum
"A1G7SGD8", // checksum calculated with uppercase form of HRP
"10a06t8", // empty HRP
"1qzzfhee", // empty HRP
};
private static final String[] INVALID_BECH32M = {
" 1xj0phk", // HRP character out of range
new String(new char[] { 0x7f }) + "1g6xzxy", // HRP character out of range
new String(new char[] { 0x80 }) + "1vctc34", // HRP character out of range
"an84characterslonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11d6pts4", // overall max length exceeded
"qyrz8wqd2c9m", // No separator character
"1qyrz8wqd2c9m", // Empty HRP
"y1b0jsk6g", // Invalid data character
"lt1igcx5c0", // Invalid data character
"in1muywd", // Too short checksum
"mm1crxm3i", // Invalid character in checksum
"au1s5cgom", // Invalid character in checksum
"M1VUXWEZ", // checksum calculated with uppercase form of HRP
"16plkw9", // empty HRP
"1p2gdwpf", // empty HRP
};
@Test(expected = AddressFormatException.InvalidCharacter.class)
public void decode_invalidCharacter_notInAlphabet() {
Bech32.decode("A12OUEL5X");
}
@Test(expected = AddressFormatException.InvalidCharacter.class)
public void decode_invalidCharacter_upperLowerMix() {
Bech32.decode("A12UeL5X");
}
@Test(expected = AddressFormatException.InvalidChecksum.class)
public void decode_invalidNetwork() {
Bech32.decode("A12UEL5X");
}
@Test(expected = AddressFormatException.InvalidPrefix.class)
public void decode_invalidHrp() {
Bech32.decode("1pzry9x0s0muk");
}
}
| 5,630
| 38.377622
| 137
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/Base58DecodeTest.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.base;
import org.bitcoinj.base.exceptions.AddressFormatException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class Base58DecodeTest {
private String input;
private byte[] expected;
public Base58DecodeTest(String input, byte[] expected) {
this.input = input;
this.expected = expected;
}
@Parameters
public static Collection<Object[]> parameters() {
return Arrays.asList(new Object[][]{
{"JxF12TrwUP45BMd", "Hello World".getBytes()},
{"1", new byte[1]},
{"1111", new byte[4]}
});
}
@Test
public void testDecode() {
byte[] actualBytes = Base58.decode(input);
assertArrayEquals(input, actualBytes, expected);
}
@Test
public void testDecode_emptyString() {
assertEquals(0, Base58.decode("").length);
}
@Test(expected = AddressFormatException.class)
public void testDecode_invalidBase58() {
Base58.decode("This isn't valid base58");
}
}
| 1,968
| 27.955882
| 75
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/BitcoinNetworkTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.base;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class BitcoinNetworkTest {
@Test
public void valueOf() {
assertEquals(BitcoinNetwork.MAINNET, BitcoinNetwork.valueOf("MAINNET"));
assertEquals(BitcoinNetwork.TESTNET, BitcoinNetwork.valueOf("TESTNET"));
assertEquals(BitcoinNetwork.SIGNET, BitcoinNetwork.valueOf("SIGNET"));
assertEquals(BitcoinNetwork.REGTEST, BitcoinNetwork.valueOf("REGTEST"));
}
@Test(expected = IllegalArgumentException.class)
public void valueOf_alternate() {
BitcoinNetwork.valueOf("PROD");
}
@Test(expected = IllegalArgumentException.class)
public void valueOf_notExisting() {
BitcoinNetwork.valueOf("xxx");
}
@Test
public void fromString() {
assertEquals(BitcoinNetwork.MAINNET, BitcoinNetwork.fromString("mainnet").get());
assertEquals(BitcoinNetwork.MAINNET, BitcoinNetwork.fromString("main").get());
assertEquals(BitcoinNetwork.MAINNET, BitcoinNetwork.fromString("prod").get());
assertEquals(BitcoinNetwork.TESTNET, BitcoinNetwork.fromString("test").get());
assertEquals(BitcoinNetwork.TESTNET, BitcoinNetwork.fromString("testnet").get());
assertEquals(BitcoinNetwork.SIGNET, BitcoinNetwork.fromString("signet").get());
assertEquals(BitcoinNetwork.SIGNET, BitcoinNetwork.fromString("sig").get());
assertEquals(BitcoinNetwork.REGTEST, BitcoinNetwork.fromString("regtest").get());
}
@Test
public void fromString_uppercase() {
assertFalse(BitcoinNetwork.fromString("MAIN").isPresent());
}
@Test
public void fromString_notExisting() {
assertFalse(BitcoinNetwork.fromString("xxx").isPresent());
}
@Test
public void fromIdString() {
assertEquals(BitcoinNetwork.MAINNET, BitcoinNetwork.fromIdString("org.bitcoin.production").get());
assertEquals(BitcoinNetwork.TESTNET, BitcoinNetwork.fromIdString("org.bitcoin.test").get());
assertEquals(BitcoinNetwork.SIGNET, BitcoinNetwork.fromIdString("org.bitcoin.signet").get());
assertEquals(BitcoinNetwork.REGTEST, BitcoinNetwork.fromIdString("org.bitcoin.regtest").get());
}
@Test
public void fromIdString_uppercase() {
assertFalse(BitcoinNetwork.fromIdString("ORG.BITCOIN.PRODUCTION").isPresent());
}
@Test
public void fromIdString_notExisting() {
assertFalse(BitcoinNetwork.fromIdString("a.b.c").isPresent());
}
}
| 3,184
| 37.373494
| 106
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/Base58DecodeToBigIntegerTest.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.base;
import org.bitcoinj.base.internal.ByteUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Base58DecodeToBigIntegerTest {
@Test
public void testDecodeToBigInteger() {
byte[] input = Base58.decode("129");
assertEquals(ByteUtils.bytesToBigInteger(input), Base58.decodeToBigInteger("129"));
}
}
| 1,018
| 29.878788
| 91
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/AddressTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.base;
// TODO: Maybe add some tests here. Address has minimal functionality now, however -- see LegacyAddress and SegwitAddress
public class AddressTest {
}
| 792
| 35.045455
| 121
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/VarIntTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.base;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@RunWith(JUnitParamsRunner.class)
public class VarIntTest {
@Test
@Parameters(method = "integerTestVectors")
public void testIntCreation(int value, int size) {
VarInt a = VarInt.of(value);
assertTrue(a.fitsInt());
assertEquals(value, a.intValue());
assertEquals(size, a.getSizeInBytes());
assertEquals(size, a.getOriginalSizeInBytes());
assertEquals(size, a.serialize().length);
assertEquals(value, VarInt.ofBytes(a.serialize(), 0).intValue());
}
@Test(expected = RuntimeException.class)
@Parameters(method = "longTestVectors")
public void testIntGetErr(int value, int size) {
VarInt a = VarInt.of(value);
assertFalse(a.fitsInt());
a.intValue();
}
@Test(expected = RuntimeException.class)
@Parameters(method = "longTestVectors")
public void testIntGetErr2(int value, int size) {
VarInt a = VarInt.of(value);
assertFalse(a.fitsInt());
VarInt.ofBytes(a.serialize(), 0).intValue();
}
@Test
@Parameters(method = "longTestVectors")
public void testLongCreation(long value, int size) {
VarInt a = VarInt.of(value);
assertEquals(value, a.longValue());
assertEquals(size, a.getSizeInBytes());
assertEquals(size, a.getOriginalSizeInBytes());
assertEquals(size, a.serialize().length);
assertEquals(value, VarInt.ofBytes(a.serialize(), 0).longValue());
}
@Test
@Parameters(method = "longTestVectors")
public void writeThenRead(long value, int size) {
VarInt varInt = VarInt.of(value);
ByteBuffer buf = ByteBuffer.allocate(varInt.getSizeInBytes());
varInt.write(buf);
assertFalse(buf.hasRemaining());
((Buffer) buf).rewind();
VarInt varIntCopy = VarInt.read(buf);
assertFalse(buf.hasRemaining());
assertEquals(varInt, varIntCopy);
}
private Object[] integerTestVectors() {
return new Object[]{
new Object[]{ 0, 1},
new Object[]{ 10, 1},
new Object[]{ 252, 1},
new Object[]{ 253, 3},
new Object[]{ 64000, 3},
new Object[]{ 0x7FFF, 3},
new Object[]{ 0x8000, 3},
new Object[]{ 0x10000, 5},
new Object[]{ Integer.MAX_VALUE, 5},
};
}
private Object[] longTestVectors() {
return new Object[]{
new Object[]{ 0x7FFFL, 3},
new Object[]{ 0x8000L, 3},
new Object[]{ 0xFFFFL, 3},
new Object[]{ 0x10000L, 5},
new Object[]{ 0xAABBCCDDL, 5},
new Object[]{ 0xFFFFFFFFL, 5},
new Object[]{ 0xCAFEBABEDEADBEEFL, 9},
new Object[]{ Integer.MIN_VALUE, 9},
new Object[]{ Long.MIN_VALUE, 9},
new Object[]{ Long.MAX_VALUE, 9},
new Object[]{ -1L, 9}
};
}
}
| 3,943
| 33
| 75
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/Base58EncodeCheckedTest.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.base;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import org.bitcoinj.base.internal.ByteUtils;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class Base58EncodeCheckedTest {
private int version;
private byte[] input;
private String expected;
@Parameters
public static Collection<Object[]> parameters() {
return Arrays.asList(new Object[][]{
{111, new byte[LegacyAddress.LENGTH], "mfWxJ45yp2SFn7UciZyNpvDKrzbhyfKrY8"},
{128, new byte[32], "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAbuatmU"},
{111, ByteUtils.parseHex("fda79a24e50ff70ff42f7d89585da5bd19d9e5cc"), "n4eA2nbYqErp7H6jebchxAN59DmNpksexv"},
{0, ByteUtils.parseHex("4a22c3c4cbb31e4d03b15550636762bda0baf85a"), "17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL"}
});
}
public Base58EncodeCheckedTest(int version, byte[] input, String expected) {
this.version = version;
this.input = input;
this.expected = expected;
}
@Test
public void testEncode() {
assertEquals(expected, Base58.encodeChecked(version, input));
}
}
| 1,972
| 32.440678
| 124
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/utils/FiatTest.java
|
/*
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.base.utils;
import org.bitcoinj.base.utils.Fiat;
import org.junit.Test;
import static org.bitcoinj.base.utils.Fiat.parseFiat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class FiatTest {
@Test
public void testParseAndValueOf() {
assertEquals(Fiat.valueOf("EUR", 10000), parseFiat("EUR", "1"));
assertEquals(Fiat.valueOf("EUR", 100), parseFiat("EUR", "0.01"));
assertEquals(Fiat.valueOf("EUR", 1), parseFiat("EUR", "0.0001"));
assertEquals(Fiat.valueOf("EUR", -10000), parseFiat("EUR", "-1"));
}
@Test
public void testParseFiat() {
assertEquals(1, Fiat.parseFiat("EUR", "0.0001").value);
assertEquals(1, Fiat.parseFiat("EUR", "0.00010").value);
}
@Test(expected = IllegalArgumentException.class)
public void testParseFiatOverprecise() {
Fiat.parseFiat("EUR", "0.00011");
}
@Test
public void testParseFiatInexact() {
assertEquals(1, Fiat.parseFiatInexact("EUR", "0.0001").value);
assertEquals(1, Fiat.parseFiatInexact("EUR", "0.00011").value);
}
@Test(expected = IllegalArgumentException.class)
public void testParseFiatInexactInvalidAmount() {
Fiat.parseFiatInexact("USD", "33.xx");
}
@Test
public void testToFriendlyString() {
assertEquals("1.00 EUR", parseFiat("EUR", "1").toFriendlyString());
assertEquals("1.23 EUR", parseFiat("EUR", "1.23").toFriendlyString());
assertEquals("0.0010 EUR", parseFiat("EUR", "0.001").toFriendlyString());
assertEquals("-1.23 EUR", parseFiat("EUR", "-1.23").toFriendlyString());
}
@Test
public void testToPlainString() {
assertEquals("0.0015", Fiat.valueOf("EUR", 15).toPlainString());
assertEquals("1.23", parseFiat("EUR", "1.23").toPlainString());
assertEquals("0.1", parseFiat("EUR", "0.1").toPlainString());
assertEquals("1.1", parseFiat("EUR", "1.1").toPlainString());
assertEquals("21.12", parseFiat("EUR", "21.12").toPlainString());
assertEquals("321.123", parseFiat("EUR", "321.123").toPlainString());
assertEquals("4321.1234", parseFiat("EUR", "4321.1234").toPlainString());
// check there are no trailing zeros
assertEquals("1", parseFiat("EUR", "1.0").toPlainString());
assertEquals("2", parseFiat("EUR", "2.00").toPlainString());
assertEquals("3", parseFiat("EUR", "3.000").toPlainString());
assertEquals("4", parseFiat("EUR", "4.0000").toPlainString());
}
@Test
public void testComparing() {
assertTrue(parseFiat("EUR", "1.11").isLessThan(parseFiat("EUR", "6.66")));
assertTrue(parseFiat("EUR", "6.66").isGreaterThan(parseFiat("EUR", "2.56")));
}
@Test
public void testSign() {
assertTrue(parseFiat("EUR", "-1").isNegative());
assertTrue(parseFiat("EUR", "-1").negate().isPositive());
assertTrue(parseFiat("EUR", "1").isPositive());
assertTrue(parseFiat("EUR", "0.00").isZero());
}
@Test
public void testCurrencyCode() {
assertEquals("RUB", parseFiat("RUB", "66.6").getCurrencyCode());
}
@Test
public void testValueFetching() {
Fiat fiat = parseFiat("USD", "666");
assertEquals(6660000, fiat.longValue());
assertEquals("6660000", fiat.toString());
}
@Test
public void testOperations() {
Fiat fiatA = parseFiat("USD", "666");
Fiat fiatB = parseFiat("USD", "2");
Fiat sumResult = fiatA.add(fiatB);
assertEquals(6680000, sumResult.getValue());
assertEquals("USD", sumResult.getCurrencyCode());
Fiat subResult = fiatA.subtract(fiatB);
assertEquals(6640000, subResult.getValue());
assertEquals("USD", subResult.getCurrencyCode());
Fiat divResult = fiatA.divide(2);
assertEquals(3330000, divResult.getValue());
assertEquals("USD", divResult.getCurrencyCode());
long ldivResult = fiatA.divide(fiatB);
assertEquals(333, ldivResult);
Fiat mulResult = fiatA.multiply(2);
assertEquals(13320000, mulResult.getValue());
Fiat[] fiats = fiatA.divideAndRemainder(3);
assertEquals(2, fiats.length);
Fiat fiat1 = fiats[0];
assertEquals(2220000, fiat1.getValue());
assertEquals("USD", fiat1.getCurrencyCode());
Fiat fiat2 = fiats[1];
assertEquals(0, fiat2.getValue());
assertEquals("USD", fiat2.getCurrencyCode());
}
}
| 5,163
| 34.369863
| 85
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/utils/MonetaryFormatTest.java
|
/*
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.base.utils;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.utils.Fiat;
import org.bitcoinj.base.utils.MonetaryFormat;
import org.bitcoinj.base.Coin;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Locale;
import static org.bitcoinj.base.Coin.CENT;
import static org.bitcoinj.base.Coin.COIN;
import static org.bitcoinj.base.Coin.SATOSHI;
import static org.bitcoinj.base.Coin.ZERO;
import static org.junit.Assert.assertEquals;
public class MonetaryFormatTest {
private static final MonetaryFormat NO_CODE = MonetaryFormat.BTC.noCode();
@Test
public void testSigns() {
assertEquals("-1.00", NO_CODE.format(Coin.COIN.negate()).toString());
assertEquals("@1.00", NO_CODE.negativeSign('@').format(Coin.COIN.negate()).toString());
assertEquals("1.00", NO_CODE.format(Coin.COIN).toString());
assertEquals("+1.00", NO_CODE.positiveSign('+').format(Coin.COIN).toString());
}
@Test
public void testDigits() {
assertEquals("١٢.٣٤٥٦٧٨٩٠", NO_CODE.digits('\u0660').format(Coin.valueOf(1234567890l)).toString());
}
@Test
public void testDecimalMark() {
assertEquals("1.00", NO_CODE.format(Coin.COIN).toString());
assertEquals("1,00", NO_CODE.decimalMark(',').format(Coin.COIN).toString());
}
@Test
public void testGrouping() {
assertEquals("0.1", format(Coin.parseCoin("0.1"), 0, 1, 2, 3));
assertEquals("0.010", format(Coin.parseCoin("0.01"), 0, 1, 2, 3));
assertEquals("0.001", format(Coin.parseCoin("0.001"), 0, 1, 2, 3));
assertEquals("0.000100", format(Coin.parseCoin("0.0001"), 0, 1, 2, 3));
assertEquals("0.000010", format(Coin.parseCoin("0.00001"), 0, 1, 2, 3));
assertEquals("0.000001", format(Coin.parseCoin("0.000001"), 0, 1, 2, 3));
}
@Test
public void btcRounding() {
assertEquals("0", format(ZERO, 0, 0));
assertEquals("0.00", format(ZERO, 0, 2));
assertEquals("1", format(COIN, 0, 0));
assertEquals("1.0", format(COIN, 0, 1));
assertEquals("1.00", format(COIN, 0, 2, 2));
assertEquals("1.00", format(COIN, 0, 2, 2, 2));
assertEquals("1.00", format(COIN, 0, 2, 2, 2, 2));
assertEquals("1.000", format(COIN, 0, 3));
assertEquals("1.0000", format(COIN, 0, 4));
final Coin justNot = COIN.subtract(SATOSHI);
assertEquals("1", format(justNot, 0, 0));
assertEquals("1.0", format(justNot, 0, 1));
assertEquals("1.00", format(justNot, 0, 2, 2));
assertEquals("1.00", format(justNot, 0, 2, 2, 2));
assertEquals("0.99999999", format(justNot, 0, 2, 2, 2, 2));
assertEquals("1.000", format(justNot, 0, 3));
assertEquals("1.0000", format(justNot, 0, 4));
final Coin slightlyMore = COIN.add(SATOSHI);
assertEquals("1", format(slightlyMore, 0, 0));
assertEquals("1.0", format(slightlyMore, 0, 1));
assertEquals("1.00", format(slightlyMore, 0, 2, 2));
assertEquals("1.00", format(slightlyMore, 0, 2, 2, 2));
assertEquals("1.00000001", format(slightlyMore, 0, 2, 2, 2, 2));
assertEquals("1.000", format(slightlyMore, 0, 3));
assertEquals("1.0000", format(slightlyMore, 0, 4));
final Coin pivot = COIN.add(SATOSHI.multiply(5));
assertEquals("1.00000005", format(pivot, 0, 8));
assertEquals("1.00000005", format(pivot, 0, 7, 1));
assertEquals("1.0000001", format(pivot, 0, 7));
final Coin value = Coin.valueOf(1122334455667788l);
assertEquals("11223345", format(value, 0, 0));
assertEquals("11223344.6", format(value, 0, 1));
assertEquals("11223344.5567", format(value, 0, 2, 2));
assertEquals("11223344.556678", format(value, 0, 2, 2, 2));
assertEquals("11223344.55667788", format(value, 0, 2, 2, 2, 2));
assertEquals("11223344.557", format(value, 0, 3));
assertEquals("11223344.5567", format(value, 0, 4));
}
@Test
public void mBtcRounding() {
assertEquals("0", format(ZERO, 3, 0));
assertEquals("0.00", format(ZERO, 3, 2));
assertEquals("1000", format(COIN, 3, 0));
assertEquals("1000.0", format(COIN, 3, 1));
assertEquals("1000.00", format(COIN, 3, 2));
assertEquals("1000.00", format(COIN, 3, 2, 2));
assertEquals("1000.000", format(COIN, 3, 3));
assertEquals("1000.0000", format(COIN, 3, 4));
final Coin justNot = COIN.subtract(SATOSHI.multiply(10));
assertEquals("1000", format(justNot, 3, 0));
assertEquals("1000.0", format(justNot, 3, 1));
assertEquals("1000.00", format(justNot, 3, 2));
assertEquals("999.9999", format(justNot, 3, 2, 2));
assertEquals("1000.000", format(justNot, 3, 3));
assertEquals("999.9999", format(justNot, 3, 4));
final Coin slightlyMore = COIN.add(SATOSHI.multiply(10));
assertEquals("1000", format(slightlyMore, 3, 0));
assertEquals("1000.0", format(slightlyMore, 3, 1));
assertEquals("1000.00", format(slightlyMore, 3, 2));
assertEquals("1000.000", format(slightlyMore, 3, 3));
assertEquals("1000.0001", format(slightlyMore, 3, 2, 2));
assertEquals("1000.0001", format(slightlyMore, 3, 4));
final Coin pivot = COIN.add(SATOSHI.multiply(50));
assertEquals("1000.0005", format(pivot, 3, 4));
assertEquals("1000.0005", format(pivot, 3, 3, 1));
assertEquals("1000.001", format(pivot, 3, 3));
final Coin value = Coin.valueOf(1122334455667788l);
assertEquals("11223344557", format(value, 3, 0));
assertEquals("11223344556.7", format(value, 3, 1));
assertEquals("11223344556.68", format(value, 3, 2));
assertEquals("11223344556.6779", format(value, 3, 2, 2));
assertEquals("11223344556.678", format(value, 3, 3));
assertEquals("11223344556.6779", format(value, 3, 4));
}
@Test
public void uBtcRounding() {
assertEquals("0", format(ZERO, 6, 0));
assertEquals("0.00", format(ZERO, 6, 2));
assertEquals("1000000", format(COIN, 6, 0));
assertEquals("1000000", format(COIN, 6, 0, 2));
assertEquals("1000000.0", format(COIN, 6, 1));
assertEquals("1000000.00", format(COIN, 6, 2));
final Coin justNot = COIN.subtract(SATOSHI);
assertEquals("1000000", format(justNot, 6, 0));
assertEquals("999999.99", format(justNot, 6, 0, 2));
assertEquals("1000000.0", format(justNot, 6, 1));
assertEquals("999999.99", format(justNot, 6, 2));
final Coin slightlyMore = COIN.add(SATOSHI);
assertEquals("1000000", format(slightlyMore, 6, 0));
assertEquals("1000000.01", format(slightlyMore, 6, 0, 2));
assertEquals("1000000.0", format(slightlyMore, 6, 1));
assertEquals("1000000.01", format(slightlyMore, 6, 2));
final Coin pivot = COIN.add(SATOSHI.multiply(5));
assertEquals("1000000.05", format(pivot, 6, 2));
assertEquals("1000000.05", format(pivot, 6, 0, 2));
assertEquals("1000000.1", format(pivot, 6, 1));
assertEquals("1000000.1", format(pivot, 6, 0, 1));
final Coin value = Coin.valueOf(1122334455667788l);
assertEquals("11223344556678", format(value, 6, 0));
assertEquals("11223344556677.88", format(value, 6, 2));
assertEquals("11223344556677.9", format(value, 6, 1));
assertEquals("11223344556677.88", format(value, 6, 2));
}
@Test
public void sat() {
assertEquals("0", format(ZERO, 8, 0));
assertEquals("100000000", format(COIN, 8, 0));
assertEquals("2100000000000000", format(BitcoinNetwork.MAX_MONEY, 8, 0));
}
private String format(Coin coin, int shift, int minDecimals, int... decimalGroups) {
return NO_CODE.shift(shift).minDecimals(minDecimals).optionalDecimals(decimalGroups).format(coin).toString();
}
@Test
public void repeatOptionalDecimals() {
assertEquals("0.00000001", formatRepeat(SATOSHI, 2, 4));
assertEquals("0.00000010", formatRepeat(SATOSHI.multiply(10), 2, 4));
assertEquals("0.01", formatRepeat(CENT, 2, 4));
assertEquals("0.10", formatRepeat(CENT.multiply(10), 2, 4));
assertEquals("0", formatRepeat(SATOSHI, 2, 2));
assertEquals("0", formatRepeat(SATOSHI.multiply(10), 2, 2));
assertEquals("0.01", formatRepeat(CENT, 2, 2));
assertEquals("0.10", formatRepeat(CENT.multiply(10), 2, 2));
assertEquals("0", formatRepeat(CENT, 2, 0));
assertEquals("0", formatRepeat(CENT.multiply(10), 2, 0));
}
private String formatRepeat(Coin coin, int decimals, int repetitions) {
return NO_CODE.minDecimals(0).repeatOptionalDecimals(decimals, repetitions).format(coin).toString();
}
@Test
public void standardCodes() {
assertEquals("BTC 0.00", MonetaryFormat.BTC.format(Coin.ZERO).toString());
assertEquals("mBTC 0.00", MonetaryFormat.MBTC.format(Coin.ZERO).toString());
assertEquals("µBTC 0", MonetaryFormat.UBTC.format(Coin.ZERO).toString());
assertEquals("sat 0", MonetaryFormat.SAT.format(Coin.ZERO).toString());
}
@Test
public void standardSymbol() {
assertEquals(MonetaryFormat.SYMBOL_BTC + " 0.00", new MonetaryFormat(true).format(Coin.ZERO).toString());
}
@Test
public void customCode() {
assertEquals("dBTC 0", MonetaryFormat.UBTC.code(1, "dBTC").shift(1).format(Coin.ZERO).toString());
}
/**
* Test clearing all codes, and then setting codes after clearing.
*/
@Test
public void noCode() {
assertEquals("0", MonetaryFormat.UBTC.noCode().shift(0).format(Coin.ZERO).toString());
// Ensure that inserting a code after codes are wiped, works
assertEquals("dBTC 0", MonetaryFormat.UBTC.noCode().code(1, "dBTC").shift(1).format(Coin.ZERO).toString());
}
@Test
public void codeOrientation() {
assertEquals("BTC 0.00", MonetaryFormat.BTC.prefixCode().format(Coin.ZERO).toString());
assertEquals("0.00 BTC", MonetaryFormat.BTC.postfixCode().format(Coin.ZERO).toString());
}
@Test
public void codeSeparator() {
assertEquals("BTC@0.00", MonetaryFormat.BTC.codeSeparator('@').format(Coin.ZERO).toString());
}
@Test(expected = NumberFormatException.class)
public void missingCode() {
MonetaryFormat.UBTC.shift(1).format(Coin.ZERO);
}
@Test
public void withLocale() {
final Coin value = Coin.valueOf(-1234567890l);
assertEquals("-12.34567890", NO_CODE.withLocale(Locale.US).format(value).toString());
assertEquals("-12,34567890", NO_CODE.withLocale(Locale.GERMANY).format(value).toString());
}
@Ignore("non-determinism between OpenJDK versions")
@Test
public void withLocaleDevanagari() {
final Coin value = Coin.valueOf(-1234567890l);
assertEquals("-१२.३४५६७८९०", NO_CODE.withLocale(new Locale("hi", "IN")).format(value).toString()); // Devanagari
}
@Test
public void parse() {
assertEquals(Coin.COIN, NO_CODE.parse("1"));
assertEquals(Coin.COIN, NO_CODE.parse("1."));
assertEquals(Coin.COIN, NO_CODE.parse("1.0"));
assertEquals(Coin.COIN, NO_CODE.decimalMark(',').parse("1,0"));
assertEquals(Coin.COIN, NO_CODE.parse("01.0000000000"));
assertEquals(Coin.COIN, NO_CODE.positiveSign('+').parse("+1.0"));
assertEquals(Coin.COIN.negate(), NO_CODE.parse("-1"));
assertEquals(Coin.COIN.negate(), NO_CODE.parse("-1.0"));
assertEquals(Coin.CENT, NO_CODE.parse(".01"));
assertEquals(Coin.MILLICOIN, MonetaryFormat.MBTC.parse("1"));
assertEquals(Coin.MILLICOIN, MonetaryFormat.MBTC.parse("1.0"));
assertEquals(Coin.MILLICOIN, MonetaryFormat.MBTC.parse("01.0000000000"));
assertEquals(Coin.MILLICOIN, MonetaryFormat.MBTC.positiveSign('+').parse("+1.0"));
assertEquals(Coin.MILLICOIN.negate(), MonetaryFormat.MBTC.parse("-1"));
assertEquals(Coin.MILLICOIN.negate(), MonetaryFormat.MBTC.parse("-1.0"));
assertEquals(Coin.MICROCOIN, MonetaryFormat.UBTC.parse("1"));
assertEquals(Coin.MICROCOIN, MonetaryFormat.UBTC.parse("1.0"));
assertEquals(Coin.MICROCOIN, MonetaryFormat.UBTC.parse("01.0000000000"));
assertEquals(Coin.MICROCOIN, MonetaryFormat.UBTC.positiveSign('+').parse("+1.0"));
assertEquals(Coin.MICROCOIN.negate(), MonetaryFormat.UBTC.parse("-1"));
assertEquals(Coin.MICROCOIN.negate(), MonetaryFormat.UBTC.parse("-1.0"));
assertEquals(Coin.SATOSHI, MonetaryFormat.SAT.parse("1"));
assertEquals(Coin.SATOSHI, MonetaryFormat.SAT.parse("01"));
assertEquals(Coin.SATOSHI, MonetaryFormat.SAT.positiveSign('+').parse("+1"));
assertEquals(Coin.SATOSHI.negate(), MonetaryFormat.SAT.parse("-1"));
assertEquals(Coin.CENT, NO_CODE.withLocale(new Locale("hi", "IN")).parse(".०१")); // Devanagari
}
@Test(expected = NumberFormatException.class)
public void parseInvalidEmpty() {
NO_CODE.parse("");
}
@Test(expected = NumberFormatException.class)
public void parseInvalidWhitespaceBefore() {
NO_CODE.parse(" 1");
}
@Test(expected = NumberFormatException.class)
public void parseInvalidWhitespaceSign() {
NO_CODE.parse("- 1");
}
@Test(expected = NumberFormatException.class)
public void parseInvalidWhitespaceAfter() {
NO_CODE.parse("1 ");
}
@Test(expected = NumberFormatException.class)
public void parseInvalidMultipleDecimalMarks() {
NO_CODE.parse("1.0.0");
}
@Test(expected = NumberFormatException.class)
public void parseInvalidDecimalMark() {
NO_CODE.decimalMark(',').parse("1.0");
}
@Test(expected = NumberFormatException.class)
public void parseInvalidPositiveSign() {
NO_CODE.positiveSign('@').parse("+1.0");
}
@Test(expected = NumberFormatException.class)
public void parseInvalidNegativeSign() {
NO_CODE.negativeSign('@').parse("-1.0");
}
@Test(expected = NumberFormatException.class)
public void parseInvalidHugeNumber() {
NO_CODE.parse("99999999999999999999");
}
@Test(expected = NumberFormatException.class)
public void parseInvalidHugeNegativeNumber() {
NO_CODE.parse("-99999999999999999999");
}
private static final Fiat ONE_EURO = Fiat.parseFiat("EUR", "1");
@Test
public void fiat() {
assertEquals(ONE_EURO, NO_CODE.parseFiat("EUR", "1"));
}
@Test
public void testEquals() {
MonetaryFormat mf1 = new MonetaryFormat(true);
MonetaryFormat mf2 = new MonetaryFormat(true);
assertEquals(mf1, mf2);
}
@Test
public void testHashCode() {
MonetaryFormat mf1 = new MonetaryFormat(true);
MonetaryFormat mf2 = new MonetaryFormat(true);
assertEquals(mf1.hashCode(), mf2.hashCode());
}
}
| 15,702
| 39.787013
| 120
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/internal/StopwatchTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.base.internal;
import org.junit.Before;
import org.junit.Test;
import java.time.Duration;
import java.time.Instant;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class StopwatchTest {
private Stopwatch stopwatch;
@Before
public void setUp() {
stopwatch = Stopwatch.start();
}
@Test
public void toString_() {
stopwatch.toString();
}
@Test
public void stop() {
stopwatch.stop();
}
@Test
public void addSubstract() {
Instant i1 = Instant.now();
Instant i2 = i1.plus(stopwatch.stop());
Instant i3 = i2.minus(stopwatch);
assertEquals(i1, i3);
assertTrue(i2.compareTo(i1) >= 0);
assertTrue(i3.compareTo(i2) <= 0);
}
@Test
public void compareTo() {
Duration hour = Duration.ofHours(1);
assertTrue(stopwatch.elapsed().compareTo(hour) < 0);
assertTrue(hour.compareTo(stopwatch.elapsed()) > 0);
}
}
| 1,689
| 25.40625
| 75
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/internal/TimeUtilsTest.java
|
/*
* Copyright 2011 Thilo Planz
* Copyright 2014 Andreas Schildbach
* Copyright 2017 Nicola Atzei
*
* 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.
*/
package org.bitcoinj.base.internal;
import org.junit.Before;
import org.junit.Test;
import java.time.Duration;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class TimeUtilsTest {
@Before
public void setUp() {
TimeUtils.clearMockClock();
}
@Test
public void setAndRollMockClock() {
TimeUtils.setMockClock(Instant.ofEpochSecond(25200));
assertEquals(Instant.from(DateTimeFormatter.ISO_INSTANT.parse("1970-01-01T07:00:00Z")), TimeUtils.currentTime());
TimeUtils.rollMockClock(Duration.ofSeconds(8));
assertEquals(Instant.from(DateTimeFormatter.ISO_INSTANT.parse("1970-01-01T07:00:08Z")), TimeUtils.currentTime());
}
@Test(expected = IllegalStateException.class)
public void rollMockClock_uninitialized() {
TimeUtils.rollMockClock(Duration.ofMinutes(1));
}
@Test
public void dateTimeFormat() {
long ms = 1416135273781L;
assertEquals("2014-11-16T10:54:33.781Z", TimeUtils.dateTimeFormat(Instant.ofEpochMilli(ms)));
}
@Test
public void earlier() {
Instant t1 = Instant.now(); // earlier
Instant t2 = t1.plusSeconds(1); // later
assertEquals(t1, TimeUtils.earlier(t1, t2));
assertEquals(t1, TimeUtils.earlier(t2, t1));
assertEquals(t1, TimeUtils.earlier(t1, t1));
assertEquals(t2, TimeUtils.earlier(t2, t2));
}
@Test
public void later() {
Instant t1 = Instant.now(); // earlier
Instant t2 = t1.plusSeconds(1); // later
assertEquals(t2, TimeUtils.later(t1, t2));
assertEquals(t2, TimeUtils.later(t2, t1));
assertEquals(t1, TimeUtils.later(t1, t1));
assertEquals(t2, TimeUtils.later(t2, t2));
}
@Test
public void longest() {
Duration d1 = Duration.ofMinutes(1); // shorter
Duration d2 = Duration.ofMinutes(1); // longer
assertEquals(d2, TimeUtils.longest(d1, d2));
assertEquals(d2, TimeUtils.longest(d2, d1));
assertEquals(d1, TimeUtils.longest(d1, d1));
assertEquals(d2, TimeUtils.longest(d2, d2));
}
}
| 2,945
| 32.477273
| 121
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/internal/StreamUtilsTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.base.internal;
import org.bitcoinj.base.internal.StreamUtils;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class StreamUtilsTest {
@Test
public void convertToUnmodifiableProducesFaithfulCopy() {
List<Integer> list = Arrays.asList(1, 2, 3);
List<Integer> unmodifiable = list.stream().collect(StreamUtils.toUnmodifiableList());
assertEquals(list, unmodifiable);
}
@Test(expected = UnsupportedOperationException.class)
public void convertToUnmodifiableProducesUnmodifiable() {
List<Integer> list = Arrays.asList(1, 2, 3);
List<Integer> unmodifiable = list.stream().collect(StreamUtils.toUnmodifiableList());
unmodifiable.add(666);
}
}
| 1,423
| 31.363636
| 93
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/internal/PlatformUtilsTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.base.internal;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Tests for PlatformUtils
*/
public class PlatformUtilsTest {
@Test
public void runtime() {
// This test assumes it is run within a Java runtime for desktop computers.
assertTrue(PlatformUtils.isOpenJDKRuntime() || PlatformUtils.isOracleJavaRuntime());
assertFalse(PlatformUtils.isAndroidRuntime());
}
}
| 1,108
| 30.685714
| 92
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/internal/ByteUtilsTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.base.internal;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.math.BigInteger;
import java.util.Comparator;
import java.util.Random;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
@RunWith(JUnitParamsRunner.class)
public class ByteUtilsTest {
@Test
@Parameters(method = "bytesToHexStringVectors")
public void formatHexValid(byte[] bytes, String expectedHexString) {
String actual = ByteUtils.formatHex(bytes);
assertEquals("incorrect hex formatted string", expectedHexString, actual);
}
@Test
@Parameters(method = "bytesToHexStringVectors")
public void parseHexValid(byte[] expectedBytes, String hexString) {
byte[] actual = ByteUtils.parseHex(hexString);
assertArrayEquals("incorrect hex formatted string", expectedBytes, actual);
}
@Test
@Parameters(method = "hexStringToBytesVectors")
public void parseHexValidUppercase(String hexString, byte[] expectedBytes) {
byte[] actual = ByteUtils.parseHex(hexString);
assertArrayEquals("incorrect hex formatted string", expectedBytes, actual);
}
// Two-way test vectors (can be used to validate mapping in both directions)
private Object[] bytesToHexStringVectors() {
return new Object[]{
new Object[]{ new byte[] {}, ""},
new Object[]{ new byte[] {0x00}, "00"},
new Object[]{ new byte[] {(byte) 0xff}, "ff"},
new Object[]{ new byte[] {(byte) 0xab, (byte) 0xcd, (byte) 0xef}, "abcdef"}
};
}
// Test vectors for verifying upper-case Strings map properly (only used to map one-way: from string to bytes)
private Object[] hexStringToBytesVectors() {
return new Object[]{
new Object[]{ "AB", new byte[] {(byte) 0xab}},
new Object[]{ "FF", new byte[] {(byte) 0xff}},
new Object[]{ "ABCDEF", new byte[] {(byte) 0xab, (byte) 0xcd, (byte) 0xef}},
};
}
@Test(expected = IllegalArgumentException.class)
@Parameters(method = "invalidHexStrings")
public void parseHexInvalid(String hexString) {
byte[] actual = ByteUtils.parseHex(hexString);
}
private String[] invalidHexStrings() {
return new String[]{
"a", // Odd number of characters
"aabbccddeeffa", // Odd number of characters
"0@", // Invalid character
"$@", // Invalid characters
"55$@" // Invalid characters
};
}
@Test
@Parameters(method = "arrayUnsignedComparatorVectors")
public void testArrayUnsignedComparator(String stringA, String stringB, int expectedResult) {
Comparator<byte[]> comparator = ByteUtils.arrayUnsignedComparator();
byte[] a = ByteUtils.parseHex(stringA);
byte[] b = ByteUtils.parseHex(stringB);
int actual = comparator.compare(a, b);
assertEquals("", expectedResult, Integer.signum(actual));
}
private Object[] arrayUnsignedComparatorVectors() {
return new Object[]{
new Object[]{ "00", "00", 0},
new Object[]{ "FF", "FF", 0},
new Object[]{ "00", "01", -1},
new Object[]{ "80", "81", -1},
new Object[]{ "FE", "FF", -1},
new Object[]{ "01", "00", 1},
new Object[]{ "81", "80", 1},
new Object[]{ "FF", "FE", 1},
new Object[]{ "00", "0001", -1},
new Object[]{ "FF", "FF00", -1},
new Object[]{ "0001", "00", 1},
new Object[]{ "FF00", "FF", 1},
new Object[]{ "000102030405060708090A", "000102030405060708090A", 0},
new Object[]{ "FF0102030405060708090A", "000102030405060708090A", 1},
new Object[]{ "000102030405060708090A", "FF0102030405060708090A", -1},
new Object[]{ "0001", "000102030405060708090A", -1},
new Object[]{ "FF01", "000102030405060708090A", 1},
new Object[]{ "0001", "FF0102030405060708090A", -1},
new Object[]{ "", "", 0}
};
}
@Test
public void testReverseBytes() {
assertArrayEquals(new byte[]{1, 2, 3, 4, 5}, ByteUtils.reverseBytes(new byte[]{5, 4, 3, 2, 1}));
assertArrayEquals(new byte[]{0}, ByteUtils.reverseBytes(new byte[]{0}));
assertArrayEquals(new byte[]{}, ByteUtils.reverseBytes(new byte[]{}));
}
@Test
public void compactEncoding() {
assertEquals(new BigInteger("1234560000", 16), ByteUtils.decodeCompactBits(0x05123456L));
assertEquals(new BigInteger("c0de000000", 16), ByteUtils.decodeCompactBits(0x0600c0de));
assertEquals(0x05123456L, ByteUtils.encodeCompactBits(new BigInteger("1234560000", 16)));
assertEquals(0x0600c0deL, ByteUtils.encodeCompactBits(new BigInteger("c0de000000", 16)));
// UnitTest difficulty
assertEquals(new BigInteger("7fffff0000000000000000000000000000000000000000000000000000000000", 16), ByteUtils.decodeCompactBits(0x207fFFFFL));
assertEquals(0x207fFFFFL, ByteUtils.encodeCompactBits(new BigInteger("7fffff0000000000000000000000000000000000000000000000000000000000", 16)));
// MainNet starting difficulty
assertEquals(new BigInteger("00000000FFFF0000000000000000000000000000000000000000000000000000", 16), ByteUtils.decodeCompactBits(0x1d00ffffL));
assertEquals(0x1d00ffffL, ByteUtils.encodeCompactBits(new BigInteger("00000000FFFF0000000000000000000000000000000000000000000000000000", 16)));
}
@Test
public void bigIntegerToBytes_roundTrip() {
int ITERATIONS = 100;
int LENGTH = 32;
Random rnd = new Random();
byte[] bytes = new byte[LENGTH];
for (int i = 0; i < ITERATIONS; i++) {
rnd.nextBytes(bytes);
BigInteger bi = ByteUtils.bytesToBigInteger(bytes);
assertArrayEquals(ByteUtils.formatHex(bytes), bytes, ByteUtils.bigIntegerToBytes(bi, LENGTH));
}
}
@Test(expected = IllegalArgumentException.class)
public void bigIntegerToBytes_convertNegativeNumber() {
BigInteger b = BigInteger.valueOf(-1);
ByteUtils.bigIntegerToBytes(b, 32);
}
@Test(expected = IllegalArgumentException.class)
public void bigIntegerToBytes_convertWithNegativeLength() {
BigInteger b = BigInteger.valueOf(10);
ByteUtils.bigIntegerToBytes(b, -1);
}
@Test(expected = IllegalArgumentException.class)
public void bigIntegerToBytes_convertWithZeroLength() {
BigInteger b = BigInteger.valueOf(10);
ByteUtils.bigIntegerToBytes(b, 0);
}
@Test(expected = IllegalArgumentException.class)
public void bigIntegerToBytes_insufficientLength() {
BigInteger b = BigInteger.valueOf(0b1000__0000_0000); // base 2
ByteUtils.bigIntegerToBytes(b, 1);
}
@Test
public void bigIntegerToBytes_convertZero() {
BigInteger b = BigInteger.valueOf(0);
byte[] expected = new byte[]{0b0000_0000};
byte[] actual = ByteUtils.bigIntegerToBytes(b, 1);
assertArrayEquals(expected, actual);
}
@Test
public void bigIntegerToBytes_singleByteSignFit() {
BigInteger b = BigInteger.valueOf(0b0000_1111);
byte[] expected = new byte[]{0b0000_1111};
byte[] actual = ByteUtils.bigIntegerToBytes(b, 1);
assertArrayEquals(expected, actual);
}
@Test
public void bigIntegerToBytes_paddedSingleByte() {
BigInteger b = BigInteger.valueOf(0b0000_1111);
byte[] expected = new byte[]{0, 0b0000_1111};
byte[] actual = ByteUtils.bigIntegerToBytes(b, 2);
assertArrayEquals(expected, actual);
}
@Test
public void bigIntegerToBytes_singleByteSignDoesNotFit() {
BigInteger b = BigInteger.valueOf(0b1000_0000); // 128 (2-compl does not fit in one byte)
byte[] expected = new byte[]{-128}; // -128 == 1000_0000 (compl-2)
byte[] actual = ByteUtils.bigIntegerToBytes(b, 1);
assertArrayEquals(expected, actual);
}
@Test
public void testReadUint16() {
assertEquals(258L, ByteUtils.readUint16(new byte[]{2, 1}, 0));
assertEquals(258L, ByteUtils.readUint16(new byte[]{2, 1, 3, 4}, 0));
assertEquals(772L, ByteUtils.readUint16(new byte[]{1, 2, 4, 3}, 2));
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint16ThrowsException1() {
ByteUtils.readUint16(new byte[]{1}, 2);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint16ThrowsException2() {
ByteUtils.readUint16(new byte[]{1, 2, 3}, 2);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint16ThrowsException3() {
ByteUtils.readUint16(new byte[]{1, 2, 3}, -1);
}
@Test
public void testReadUint32() {
assertEquals(258L, ByteUtils.readUint32(new byte[]{2, 1, 0, 0}, 0));
assertEquals(258L, ByteUtils.readUint32(new byte[]{2, 1, 0, 0, 3, 4}, 0));
assertEquals(772L, ByteUtils.readUint32(new byte[]{1, 2, 4, 3, 0, 0}, 2));
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint32ThrowsException1() {
ByteUtils.readUint32(new byte[]{1, 2, 3}, 2);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint32ThrowsException2() {
ByteUtils.readUint32(new byte[]{1, 2, 3, 4, 5}, 2);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint32ThrowsException3() {
ByteUtils.readUint32(new byte[]{1, 2, 3, 4, 5}, -1);
}
@Test
public void testReadInt64() {
assertEquals(258L, ByteUtils.readInt64(new byte[]{2, 1, 0, 0, 0, 0, 0, 0}, 0));
assertEquals(258L, ByteUtils.readInt64(new byte[]{2, 1, 0, 0, 0, 0, 0, 0, 3, 4}, 0));
assertEquals(772L, ByteUtils.readInt64(new byte[]{1, 2, 4, 3, 0, 0, 0, 0, 0, 0}, 2));
assertEquals(-1L, ByteUtils.readInt64(new byte[]{-1, -1, -1, -1, -1, -1, -1, -1}, 0));
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadInt64ThrowsException1() {
ByteUtils.readInt64(new byte[]{1, 2, 3, 4, 5, 6, 7}, 2);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadInt64ThrowsException2() {
ByteUtils.readInt64(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, 2);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadInt64ThrowsException3() {
ByteUtils.readInt64(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, -1);
}
@Test
public void testReadUInt32BE() {
assertEquals(258L, ByteUtils.readUint32BE(new byte[]{0, 0, 1, 2}, 0));
assertEquals(258L, ByteUtils.readUint32BE(new byte[]{0, 0, 1, 2, 3, 4}, 0));
assertEquals(772L, ByteUtils.readUint32BE(new byte[]{1, 2, 0, 0, 3, 4}, 2));
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint32BEThrowsException1() {
ByteUtils.readUint32BE(new byte[]{1, 2, 3}, 2);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint32BEThrowsException2() {
ByteUtils.readUint32BE(new byte[]{1, 2, 3, 4, 5}, 2);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint32BEThrowsException3() {
ByteUtils.readUint32BE(new byte[]{1, 2, 3, 4, 5}, -1);
}
@Test
public void testReadUint16BE() {
assertEquals(258L, ByteUtils.readUint16BE(new byte[]{1, 2}, 0));
assertEquals(258L, ByteUtils.readUint16BE(new byte[]{1, 2, 3, 4}, 0));
assertEquals(772L, ByteUtils.readUint16BE(new byte[]{0, 0, 3, 4}, 2));
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint16BEThrowsException1() {
ByteUtils.readUint16BE(new byte[]{1}, 2);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint16BEThrowsException2() {
ByteUtils.readUint16BE(new byte[]{1, 2, 3}, 2);
}
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testReadUint16BEThrowsException3() {
ByteUtils.readUint16BE(new byte[]{1, 2, 3}, -1);
}
@Test
public void testDecodeMPI() {
assertEquals(BigInteger.ZERO, ByteUtils.decodeMPI(new byte[]{}, false));
}
}
| 13,343
| 38.952096
| 151
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/internal/ByteArrayTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.base.internal;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
@RunWith(JUnitParamsRunner.class)
public class ByteArrayTest {
@Test
public void testImmutability() {
byte[] bytes = new byte[]{0x00};
ByteArray ba = new ByteArray(bytes);
// Modify original array
bytes[0] = (byte) 0xFF;
// Verify ByteArray not modified (due to defensive copy)
assertNotEquals(ba.bytes, bytes);
}
@Test
public void equalsContract() {
EqualsVerifier.forClass(ByteArray.class)
.suppress(Warning.NULL_FIELDS)
.suppress(Warning.TRANSIENT_FIELDS)
.usingGetClass()
.verify();
}
@Test
@Parameters(method = "bytesToHexStringVectors")
public void formatHexValid(byte[] bytes, String expectedHexString) {
ByteArray ba = new ByteArray(bytes);
assertEquals("incorrect hex formatted string", expectedHexString, ba.formatHex());
}
// Two-way test vectors (can be used to validate mapping in both directions)
private Object[] bytesToHexStringVectors() {
return new Object[]{
new Object[]{ new byte[] {}, ""},
new Object[]{ new byte[] {0x00}, "00"},
new Object[]{ new byte[] {(byte) 0xff}, "ff"},
new Object[]{ new byte[] {(byte) 0xab, (byte) 0xcd, (byte) 0xef}, "abcdef"}
};
}
}
| 2,309
| 32.478261
| 91
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/base/internal/PreconditionsTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.base.internal;
import org.junit.Test;
public class PreconditionsTest {
@Test
public void check_true() {
Preconditions.check(true, ArithmeticException::new);
}
@Test(expected = ArithmeticException.class)
public void check_false() {
Preconditions.check(false, ArithmeticException::new);
}
}
| 966
| 29.21875
| 75
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/net/discovery/DnsDiscoveryTest.java
|
/*
* Copyright 2019 Tim Strasser
*
* 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.
*/
package org.bitcoinj.net.discovery;
import org.bitcoinj.params.MainNetParams;
import org.junit.Test;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class DnsDiscoveryTest {
@Test
public void testBuildDiscoveries() throws PeerDiscoveryException {
String[] seeds = new String[] { "seed.bitcoin.sipa.be", "dnsseed.bluematt.me" };
DnsDiscovery dnsDiscovery = new DnsDiscovery(seeds, MainNetParams.get());
assertTrue(dnsDiscovery.seeds.size() == 2);
for (PeerDiscovery peerDiscovery : dnsDiscovery.seeds) {
assertTrue(peerDiscovery.getPeers(0, Duration.ofMillis(100)).size() > 0);
}
}
@Test(expected = PeerDiscoveryException.class)
public void testGetPeersThrowsPeerDiscoveryExceptionWithServicesGreaterThanZero() throws PeerDiscoveryException {
DnsDiscovery.DnsSeedDiscovery dnsSeedDiscovery = new DnsDiscovery.DnsSeedDiscovery(MainNetParams.get(), "");
dnsSeedDiscovery.getPeers(1, Duration.ofMillis(100));
}
@Test
public void testGetPeersReturnsNotEmptyListOfSocketAddresses() throws PeerDiscoveryException {
DnsDiscovery.DnsSeedDiscovery dnsSeedDiscovery = new DnsDiscovery.DnsSeedDiscovery(MainNetParams.get(),
"localhost");
List<InetSocketAddress> inetSocketAddresses = dnsSeedDiscovery.getPeers(0, Duration.ofMillis(100));
assertNotEquals(0, inetSocketAddresses.size());
}
@Test(expected = PeerDiscoveryException.class)
public void testGetPeersThrowsPeerDiscoveryExceptionForUnknownHost() throws PeerDiscoveryException {
DnsDiscovery.DnsSeedDiscovery dnsSeedDiscovery = new DnsDiscovery.DnsSeedDiscovery(MainNetParams.get(),
"unknown host");
dnsSeedDiscovery.getPeers(0, Duration.ofMillis(100));
}
}
| 2,568
| 39.777778
| 117
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/net/discovery/SeedPeersTest.java
|
/*
* Copyright 2011 Micheal Swiggs
* Copyright 2015 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.net.discovery;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.params.MainNetParams;
import org.junit.Test;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
public class SeedPeersTest {
private static final NetworkParameters MAINNET = MainNetParams.get();
@Test
public void getPeer_one() throws Exception{
SeedPeers seedPeers = new SeedPeers(MAINNET);
assertThat(seedPeers.getPeer(), notNullValue());
}
@Test
public void getPeer_all() throws Exception{
SeedPeers seedPeers = new SeedPeers(MAINNET);
for (int i = 0; i < MAINNET.getAddrSeeds().length; ++i) {
assertThat("Failed on index: "+i, seedPeers.getPeer(), notNullValue());
}
assertThat(seedPeers.getPeer(), equalTo(null));
}
@Test
public void getPeers_length() throws Exception{
SeedPeers seedPeers = new SeedPeers(MAINNET);
List<InetSocketAddress> addresses = seedPeers.getPeers(0, Duration.ZERO);
assertThat(addresses.size(), equalTo(MAINNET.getAddrSeeds().length));
}
}
| 1,932
| 32.912281
| 83
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/utils/BaseTaggableObjectTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.utils;
import com.google.protobuf.ByteString;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class BaseTaggableObjectTest {
private BaseTaggableObject obj;
@Before
public void setUp() {
obj = new BaseTaggableObject();
}
@Test
public void tags() {
assertNull(obj.maybeGetTag("foo"));
obj.setTag("foo", ByteString.copyFromUtf8("bar"));
assertEquals("bar", obj.getTag("foo").toStringUtf8());
}
@Test(expected = IllegalArgumentException.class)
public void exception() {
obj.getTag("non existent");
}
}
| 1,314
| 28.222222
| 75
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/utils/BtcFixedFormatThrowsIllegalStateExceptionTest.java
|
/*
* Copyright 2019 Tim Strasser
*
* 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.
*/
package org.bitcoinj.utils;
import org.junit.Test;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Locale;
public class BtcFixedFormatThrowsIllegalStateExceptionTest {
@Test(expected = IllegalStateException.class)
public void testScaleThrowsIllegalStateException() {
BtcFixedFormat btcFixedFormat = new BtcFixedFormat(Locale.getDefault(), BtcFormat.MILLICOIN_SCALE, 2,
new ArrayList<Integer>());
btcFixedFormat.scale(new BigInteger("2000"), 0);
}
}
| 1,119
| 31.941176
| 109
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/utils/BriefLogFormatterTest.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.utils;
import org.junit.Test;
import java.time.Instant;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import static org.junit.Assert.assertEquals;
public class BriefLogFormatterTest {
@Test
public void format() {
BriefLogFormatter formatter = new BriefLogFormatter();
LogRecord record = new LogRecord(Level.INFO, "message");
record.setSourceClassName("org.example.Class");
record.setSourceMethodName("method");
record.setMillis(Instant.EPOCH.toEpochMilli());
record.setThreadID(123);
assertEquals("00:00:00 123 Class.method: message\n", formatter.format(record));
}
}
| 1,296
| 32.25641
| 87
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/utils/ExponentialBackoffTest.java
|
/*
* Copyright 2013 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.
*/
package org.bitcoinj.utils;
import org.bitcoinj.base.internal.TimeUtils;
import org.junit.Before;
import org.junit.Test;
import java.util.PriorityQueue;
import static org.junit.Assert.assertEquals;
public class ExponentialBackoffTest {
private ExponentialBackoff.Params params;
private ExponentialBackoff backoff;
@Before
public void setUp() {
TimeUtils.setMockClock();
params = new ExponentialBackoff.Params();
backoff = new ExponentialBackoff(params);
}
@Test
public void testSuccess() {
assertEquals(TimeUtils.currentTime(), backoff.retryTime());
backoff.trackFailure();
backoff.trackFailure();
backoff.trackSuccess();
assertEquals(TimeUtils.currentTime(), backoff.retryTime());
}
@Test
public void testFailure() {
assertEquals(TimeUtils.currentTime(), backoff.retryTime());
backoff.trackFailure();
backoff.trackFailure();
backoff.trackFailure();
assertEquals(TimeUtils.currentTime().plusMillis(121), backoff.retryTime());
}
@Test
public void testInQueue() {
PriorityQueue<ExponentialBackoff> queue = new PriorityQueue<>();
ExponentialBackoff backoff1 = new ExponentialBackoff(params);
backoff.trackFailure();
backoff.trackFailure();
backoff1.trackFailure();
backoff1.trackFailure();
backoff1.trackFailure();
queue.offer(backoff);
queue.offer(backoff1);
assertEquals(queue.poll(), backoff); // The one with soonest retry time
assertEquals(queue.peek(), backoff1);
queue.offer(backoff);
assertEquals(queue.poll(), backoff); // Still the same one
}
}
| 2,325
| 28.443038
| 83
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/utils/AppDataDirectoryTest.java
|
/*
* Copyright 2019 Michael Sean Gilligan
* Copyright 2019 Tim Strasser
*
* 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.
*/
package org.bitcoinj.utils;
import org.bitcoinj.base.internal.PlatformUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Basic test of AppDataDirectory
*/
public class AppDataDirectoryTest {
private static final String HOMEDIR = System.getProperty("user.home");
private static final String WINAPPDATA = System.getenv("APPDATA");
@Test
public void worksOnCurrentPlatform() {
final String appName = "bitcoinj";
String path = AppDataDirectory.get(appName).toString();
if (PlatformUtils.isWindows()) {
assertEquals("Path wrong on Windows", winPath(appName), path);
} else if (PlatformUtils.isMac()) {
assertEquals("Path wrong on Mac", macPath(appName), path);
} else if (PlatformUtils.isLinux()) {
assertEquals("Path wrong on Linux", unixPath(appName), path);
} else {
assertEquals("Path wrong on unknown/default", unixPath(appName), path);
}
}
@Test
public void worksOnCurrentPlatformForBitcoinCore() {
final String appName = "Bitcoin";
String path = AppDataDirectory.get(appName).toString();
if (PlatformUtils.isWindows()) {
assertEquals("Path wrong on Windows", winPath(appName), path);
} else if (PlatformUtils.isMac()) {
assertEquals("Path wrong on Mac", macPath(appName), path);
} else if (PlatformUtils.isLinux()) {
assertEquals("Path wrong on Linux", unixPath(appName), path);
} else {
assertEquals("Path wrong on unknown/default", unixPath(appName), path);
}
}
@Test(expected = RuntimeException.class)
public void throwsIOExceptionIfPathNotFound() {
// Force exceptions with illegal characters
if (PlatformUtils.isWindows()) {
AppDataDirectory.get(":"); // Illegal character for Windows
}
if (PlatformUtils.isMac()) {
// NUL character
AppDataDirectory.get("\0"); // Illegal character for Mac
}
if (PlatformUtils.isLinux()) {
// NUL character
AppDataDirectory.get("\0"); // Illegal character for Linux
}
}
private static String winPath(String appName) {
return WINAPPDATA + "\\" + appName.toLowerCase();
}
private static String macPath(String appName) {
return HOMEDIR + "/Library/Application Support/" + appName;
}
private static String unixPath(String appName) {
return HOMEDIR + "/." + appName.toLowerCase();
}
}
| 3,221
| 34.406593
| 84
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/utils/VersionTallyTest.java
|
/*
* Copyright 2015 Ross Nicoll.
*
* 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.
*/
package org.bitcoinj.utils;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.core.BlockChain;
import org.bitcoinj.core.Context;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.StoredBlock;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.store.BlockStore;
import org.bitcoinj.store.BlockStoreException;
import org.bitcoinj.store.MemoryBlockStore;
import org.bitcoinj.testing.FakeTxBuilder;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class VersionTallyTest {
private static final NetworkParameters TESTNET = TestNet3Params.get();
public VersionTallyTest() {
}
@BeforeClass
public static void setUpClass() {
TimeUtils.clearMockClock();
}
@Before
public void setUp() {
BriefLogFormatter.initVerbose();
}
/**
* Verify that the version tally returns null until it collects enough data.
*/
@Test
public void testNullWhileEmpty() {
VersionTally instance = new VersionTally(TESTNET);
for (int i = 0; i < TESTNET.getMajorityWindow(); i++) {
assertNull(instance.getCountAtOrAbove(1));
instance.add(1);
}
assertEquals(TESTNET.getMajorityWindow(), instance.getCountAtOrAbove(1).intValue());
}
/**
* Verify that the size of the version tally matches the network parameters.
*/
@Test
public void testSize() {
VersionTally instance = new VersionTally(TESTNET);
assertEquals(TESTNET.getMajorityWindow(), instance.size());
}
/**
* Verify that version count and substitution works correctly.
*/
@Test
public void testVersionCounts() {
VersionTally instance = new VersionTally(TESTNET);
// Fill the tally with 1s
for (int i = 0; i < TESTNET.getMajorityWindow(); i++) {
assertNull(instance.getCountAtOrAbove(1));
instance.add(1);
}
assertEquals(TESTNET.getMajorityWindow(), instance.getCountAtOrAbove(1).intValue());
// Check the count updates as we replace with 2s
for (int i = 0; i < TESTNET.getMajorityWindow(); i++) {
assertEquals(i, instance.getCountAtOrAbove(2).intValue());
instance.add(2);
}
// Inject a rogue 1
instance.add(1);
assertEquals(TESTNET.getMajorityWindow() - 1, instance.getCountAtOrAbove(2).intValue());
// Check we accept high values as well
instance.add(10);
assertEquals(TESTNET.getMajorityWindow() - 1, instance.getCountAtOrAbove(2).intValue());
}
@Test
public void testInitialize() throws BlockStoreException {
Context.propagate(new Context(100, Transaction.DEFAULT_TX_FEE, false, true));
final BlockStore blockStore = new MemoryBlockStore(TESTNET.getGenesisBlock());
final BlockChain chain = new BlockChain(TESTNET, blockStore);
// Build a historical chain of version 2 blocks
Instant time = Instant.ofEpochSecond(1231006505);
StoredBlock chainHead = null;
for (int height = 0; height < TESTNET.getMajorityWindow(); height++) {
chainHead = FakeTxBuilder.createFakeBlock(blockStore, 2, time, height).storedBlock;
assertEquals(2, chainHead.getHeader().getVersion());
time = time.plus(1, ChronoUnit.MINUTES);
}
VersionTally instance = new VersionTally(TESTNET);
instance.initialize(blockStore, chainHead);
assertEquals(TESTNET.getMajorityWindow(), instance.getCountAtOrAbove(2).intValue());
}
}
| 4,397
| 33.629921
| 96
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/utils/ExchangeRateTest.java
|
/*
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.utils;
import org.bitcoinj.base.utils.Fiat;
import org.bitcoinj.base.Coin;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ExchangeRateTest {
@Test
public void normalRate() {
ExchangeRate rate = new ExchangeRate(Fiat.parseFiat("EUR", "500"));
assertEquals("0.5", rate.coinToFiat(Coin.MILLICOIN).toPlainString());
assertEquals("0.002", rate.fiatToCoin(Fiat.parseFiat("EUR", "1")).toPlainString());
}
@Test
public void bigRate() {
ExchangeRate rate = new ExchangeRate(Coin.parseCoin("0.0001"), Fiat.parseFiat("BYR", "5320387.3"));
assertEquals("53203873000", rate.coinToFiat(Coin.COIN).toPlainString());
assertEquals("0", rate.fiatToCoin(Fiat.parseFiat("BYR", "1")).toPlainString()); // Tiny value!
}
@Test
public void smallRate() {
ExchangeRate rate = new ExchangeRate(Coin.parseCoin("1000"), Fiat.parseFiat("XXX", "0.0001"));
assertEquals("0", rate.coinToFiat(Coin.COIN).toPlainString()); // Tiny value!
assertEquals("10000000", rate.fiatToCoin(Fiat.parseFiat("XXX", "1")).toPlainString());
}
@Test(expected = IllegalArgumentException.class)
public void currencyCodeMismatch() {
ExchangeRate rate = new ExchangeRate(Fiat.parseFiat("EUR", "500"));
rate.fiatToCoin(Fiat.parseFiat("USD", "1"));
}
@Test(expected = IllegalArgumentException.class)
public void constructMissingCurrencyCode() {
new ExchangeRate(Fiat.valueOf(null, 1));
}
@Test(expected = IllegalArgumentException.class)
public void constructNegativeCoin() {
new ExchangeRate(Coin.valueOf(-1), Fiat.valueOf("EUR", 1));
}
@Test(expected = IllegalArgumentException.class)
public void constructFiatCoin() {
new ExchangeRate(Fiat.valueOf("EUR", -1));
}
}
| 2,472
| 34.84058
| 107
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/utils/BtcFixedFormatTest.java
|
/*
* Copyright 2019 Tim Strasser
*
* 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.
*/
package org.bitcoinj.utils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import static org.bitcoinj.utils.BtcFormat.COIN_SCALE;
import static org.bitcoinj.utils.BtcFormat.MICROCOIN_SCALE;
import static org.bitcoinj.utils.BtcFormat.MILLICOIN_SCALE;
import static org.junit.Assert.assertEquals;
@RunWith(Parameterized.class)
public class BtcFixedFormatTest {
private final ArrayList<Integer> groups;
private int input;
private String expectedOutput;
private BtcFixedFormat btcFixedFormat;
public BtcFixedFormatTest(int input, String expectedOutput) {
this.input = input;
this.expectedOutput = expectedOutput;
this.groups = new ArrayList<>();
}
@Parameterized.Parameters
public static Collection<Object[]> parameters() {
return Arrays.asList(new Object[][]{
{COIN_SCALE, "Coin-"},
{1, "Decicoin-"},
{2, "Centicoin-"},
{MILLICOIN_SCALE, "Millicoin-"},
{MICROCOIN_SCALE, "Microcoin-"},
{-1, "Dekacoin-"},
{-2, "Hectocoin-"},
{-3, "Kilocoin-"},
{-6, "Megacoin-"},
{-100, "Fixed (-100) "}
});
}
@Before
public void initBtcFixedFormat() {
this.btcFixedFormat = new BtcFixedFormat(Locale.getDefault(), input, 2, groups);
}
@Test
public void testPrefixLabel() {
assertEquals(String.format("%s%s %s", expectedOutput, "format", btcFixedFormat.pattern()),
btcFixedFormat.toString());
}
}
| 2,355
| 30.413333
| 98
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/utils/BtcFormatTest.java
|
/*
* Copyright 2014 Adam Mackler
*
* 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.
*/
package org.bitcoinj.utils;
import org.bitcoinj.base.Coin;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.math.BigDecimal;
import java.text.AttributedCharacterIterator;
import java.text.AttributedCharacterIterator.Attribute;
import java.text.CharacterIterator;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import static java.text.NumberFormat.Field.DECIMAL_SEPARATOR;
import static java.util.Locale.CHINA;
import static java.util.Locale.FRANCE;
import static java.util.Locale.GERMANY;
import static java.util.Locale.ITALY;
import static java.util.Locale.JAPAN;
import static java.util.Locale.TAIWAN;
import static java.util.Locale.US;
import static org.bitcoinj.base.Coin.COIN;
import static org.bitcoinj.base.Coin.SATOSHI;
import static org.bitcoinj.base.Coin.SMALLEST_UNIT_EXPONENT;
import static org.bitcoinj.base.Coin.ZERO;
import static org.bitcoinj.base.Coin.parseCoin;
import static org.bitcoinj.base.Coin.valueOf;
import static org.bitcoinj.base.BitcoinNetwork.MAX_MONEY;
import static org.bitcoinj.utils.BtcAutoFormat.Style.CODE;
import static org.bitcoinj.utils.BtcAutoFormat.Style.SYMBOL;
import static org.bitcoinj.utils.BtcFixedFormat.REPEATING_DOUBLETS;
import static org.bitcoinj.utils.BtcFixedFormat.REPEATING_TRIPLETS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(Parameterized.class)
public class BtcFormatTest {
@Parameters
public static Set<Locale[]> data() {
Set<Locale[]> localeSet = new HashSet<>();
for (Locale locale : Locale.getAvailableLocales()) {
localeSet.add(new Locale[]{locale});
}
return localeSet;
}
public BtcFormatTest(Locale defaultLocale) {
Locale.setDefault(defaultLocale);
}
@Test
public void prefixTest() { // prefix b/c symbol is prefixed
BtcFormat usFormat = BtcFormat.getSymbolInstance(Locale.US);
assertEquals("฿1.00", usFormat.format(COIN));
assertEquals("฿1.01", usFormat.format(101000000));
assertEquals("₥฿0.01", usFormat.format(1000));
assertEquals("₥฿1,011.00", usFormat.format(101100000));
assertEquals("₥฿1,000.01", usFormat.format(100001000));
assertEquals("µ฿1,000,001.00", usFormat.format(100000100));
assertEquals("µ฿1,000,000.10", usFormat.format(100000010));
assertEquals("µ฿1,000,000.01", usFormat.format(100000001));
assertEquals("µ฿1.00", usFormat.format(100));
assertEquals("µ฿0.10", usFormat.format(10));
assertEquals("µ฿0.01", usFormat.format(1));
}
@Ignore("non-determinism between OpenJDK versions")
@Test
public void suffixTest() {
BtcFormat deFormat = BtcFormat.getSymbolInstance(Locale.GERMANY);
// int
assertEquals("1,00 ฿", deFormat.format(100000000));
assertEquals("1,01 ฿", deFormat.format(101000000));
assertEquals("1.011,00 ₥฿", deFormat.format(101100000));
assertEquals("1.000,01 ₥฿", deFormat.format(100001000));
assertEquals("1.000.001,00 µ฿", deFormat.format(100000100));
assertEquals("1.000.000,10 µ฿", deFormat.format(100000010));
assertEquals("1.000.000,01 µ฿", deFormat.format(100000001));
}
@Test
public void defaultLocaleTest() {
assertEquals(
"Default Locale is " + Locale.getDefault().toString(),
BtcFormat.getInstance().pattern(), BtcFormat.getInstance(Locale.getDefault()).pattern()
);
assertEquals(
"Default Locale is " + Locale.getDefault().toString(),
BtcFormat.getCodeInstance().pattern(),
BtcFormat.getCodeInstance(Locale.getDefault()).pattern()
);
}
@Test
public void symbolCollisionTest() {
Locale[] locales = BtcFormat.getAvailableLocales();
for (Locale locale : locales) {
String cs = ((DecimalFormat) NumberFormat.getCurrencyInstance(locale)).
getDecimalFormatSymbols().getCurrencySymbol();
if (cs.contains("฿")) {
BtcFormat bf = BtcFormat.getSymbolInstance(locale);
String coin = bf.format(COIN);
assertTrue(coin.contains("Ƀ"));
assertFalse(coin.contains("฿"));
String milli = bf.format(valueOf(10000));
assertTrue(milli.contains("₥Ƀ"));
assertFalse(milli.contains("฿"));
String micro = bf.format(valueOf(100));
assertTrue(micro.contains("µɃ"));
assertFalse(micro.contains("฿"));
BtcFormat ff = BtcFormat.builder().scale(0).locale(locale).pattern("¤#.#").build();
assertEquals("Ƀ", ((BtcFixedFormat) ff).symbol());
assertEquals("Ƀ", ff.coinSymbol());
coin = ff.format(COIN);
assertTrue(coin.contains("Ƀ"));
assertFalse(coin.contains("฿"));
BtcFormat mlff = BtcFormat.builder().scale(3).locale(locale).pattern("¤#.#").build();
assertEquals("₥Ƀ", ((BtcFixedFormat) mlff).symbol());
assertEquals("Ƀ", mlff.coinSymbol());
milli = mlff.format(valueOf(10000));
assertTrue(milli.contains("₥Ƀ"));
assertFalse(milli.contains("฿"));
BtcFormat mcff = BtcFormat.builder().scale(6).locale(locale).pattern("¤#.#").build();
assertEquals("µɃ", ((BtcFixedFormat) mcff).symbol());
assertEquals("Ƀ", mcff.coinSymbol());
micro = mcff.format(valueOf(100));
assertTrue(micro.contains("µɃ"));
assertFalse(micro.contains("฿"));
}
if (cs.contains("Ƀ")) { // NB: We don't know of any such existing locale, but check anyway.
BtcFormat bf = BtcFormat.getInstance(locale);
String coin = bf.format(COIN);
assertTrue(coin.contains("฿"));
assertFalse(coin.contains("Ƀ"));
String milli = bf.format(valueOf(10000));
assertTrue(milli.contains("₥฿"));
assertFalse(milli.contains("Ƀ"));
String micro = bf.format(valueOf(100));
assertTrue(micro.contains("µ฿"));
assertFalse(micro.contains("Ƀ"));
}
}
}
@Ignore("non-determinism between OpenJDK versions")
@Test
public void argumentTypeTest() {
BtcFormat usFormat = BtcFormat.getSymbolInstance(Locale.US);
// longs are tested above
// Coin
assertEquals("µ฿1,000,000.01", usFormat.format(COIN.add(valueOf(1))));
// Integer
assertEquals("µ฿21,474,836.47" ,usFormat.format(Integer.MAX_VALUE));
assertEquals("(µ฿21,474,836.48)" ,usFormat.format(Integer.MIN_VALUE));
// Long
assertEquals("µ฿92,233,720,368,547,758.07" ,usFormat.format(Long.MAX_VALUE));
assertEquals("(µ฿92,233,720,368,547,758.08)" ,usFormat.format(Long.MIN_VALUE));
// BigInteger
assertEquals("µ฿0.10" ,usFormat.format(java.math.BigInteger.TEN));
assertEquals("฿0.00" ,usFormat.format(java.math.BigInteger.ZERO));
// BigDecimal
assertEquals("฿1.00" ,usFormat.format(java.math.BigDecimal.ONE));
assertEquals("฿0.00" ,usFormat.format(java.math.BigDecimal.ZERO));
// use of Double not encouraged but no way to stop user from converting one to BigDecimal
assertEquals(
"฿179,769,313,486,231,570,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000.00",
usFormat.format(java.math.BigDecimal.valueOf(Double.MAX_VALUE)));
assertEquals("฿0.00", usFormat.format(java.math.BigDecimal.valueOf(Double.MIN_VALUE)));
assertEquals(
"฿340,282,346,638,528,860,000,000,000,000,000,000,000.00",
usFormat.format(java.math.BigDecimal.valueOf(Float.MAX_VALUE)));
// Bad type
try {
usFormat.format("1");
fail("should not have tried to format a String");
} catch (IllegalArgumentException e) {
}
}
@Test
public void columnAlignmentTest() {
BtcFormat germany = BtcFormat.getCoinInstance(2,BtcFixedFormat.REPEATING_PLACES);
char separator = germany.symbols().getDecimalSeparator();
Coin[] rows = {MAX_MONEY, MAX_MONEY.subtract(SATOSHI), Coin.parseCoin("1234"),
COIN, COIN.add(SATOSHI), COIN.subtract(SATOSHI),
COIN.divide(1000).add(SATOSHI), COIN.divide(1000), COIN.divide(1000).subtract(SATOSHI),
valueOf(100), valueOf(1000), valueOf(10000),
SATOSHI};
FieldPosition fp = new FieldPosition(DECIMAL_SEPARATOR);
String[] output = new String[rows.length];
int[] indexes = new int[rows.length];
int maxIndex = 0;
for (int i = 0; i < rows.length; i++) {
output[i] = germany.format(rows[i], new StringBuffer(), fp).toString();
indexes[i] = fp.getBeginIndex();
if (indexes[i] > maxIndex) maxIndex = indexes[i];
}
for (int i = 0; i < output.length; i++) {
// uncomment to watch printout
// System.out.println(repeat(" ", (maxIndex - indexes[i])) + output[i]);
assertEquals(output[i].indexOf(separator), indexes[i]);
}
}
@Test
public void repeatingPlaceTest() {
BtcFormat mega = BtcFormat.getInstance(-6, US);
Coin value = MAX_MONEY.subtract(SATOSHI);
assertEquals("20.99999999999999", mega.format(value, 0, BtcFixedFormat.REPEATING_PLACES));
assertEquals("20.99999999999999", mega.format(value, 0, BtcFixedFormat.REPEATING_PLACES));
assertEquals("20.99999999999999", mega.format(value, 1, BtcFixedFormat.REPEATING_PLACES));
assertEquals("20.99999999999999", mega.format(value, 2, BtcFixedFormat.REPEATING_PLACES));
assertEquals("20.99999999999999", mega.format(value, 3, BtcFixedFormat.REPEATING_PLACES));
assertEquals("20.99999999999999", mega.format(value, 0, BtcFixedFormat.REPEATING_DOUBLETS));
assertEquals("20.99999999999999", mega.format(value, 1, BtcFixedFormat.REPEATING_DOUBLETS));
assertEquals("20.99999999999999", mega.format(value, 2, BtcFixedFormat.REPEATING_DOUBLETS));
assertEquals("20.99999999999999", mega.format(value, 3, BtcFixedFormat.REPEATING_DOUBLETS));
assertEquals("20.99999999999999", mega.format(value, 0, BtcFixedFormat.REPEATING_TRIPLETS));
assertEquals("20.99999999999999", mega.format(value, 1, BtcFixedFormat.REPEATING_TRIPLETS));
assertEquals("20.99999999999999", mega.format(value, 2, BtcFixedFormat.REPEATING_TRIPLETS));
assertEquals("20.99999999999999", mega.format(value, 3, BtcFixedFormat.REPEATING_TRIPLETS));
assertEquals("1.00000005", BtcFormat.getCoinInstance(US).
format(COIN.add(Coin.valueOf(5)), 0, BtcFixedFormat.REPEATING_PLACES));
}
@Test
public void characterIteratorTest() {
BtcFormat usFormat = BtcFormat.getInstance(Locale.US);
AttributedCharacterIterator i = usFormat.formatToCharacterIterator(parseCoin("1234.5"));
java.util.Set<Attribute> a = i.getAllAttributeKeys();
assertTrue("Missing currency attribute", a.contains(NumberFormat.Field.CURRENCY));
assertTrue("Missing integer attribute", a.contains(NumberFormat.Field.INTEGER));
assertTrue("Missing fraction attribute", a.contains(NumberFormat.Field.FRACTION));
assertTrue("Missing decimal separator attribute", a.contains(NumberFormat.Field.DECIMAL_SEPARATOR));
assertTrue("Missing grouping separator attribute", a.contains(NumberFormat.Field.GROUPING_SEPARATOR));
assertTrue("Missing currency attribute", a.contains(NumberFormat.Field.CURRENCY));
char c;
i = BtcFormat.getCodeInstance(Locale.US).formatToCharacterIterator(new BigDecimal("0.19246362747414458"));
// formatted as "µBTC 192,463.63"
assertEquals(0, i.getBeginIndex());
assertEquals(15, i.getEndIndex());
int n = 0;
for(c = i.first(); i.getAttribute(NumberFormat.Field.CURRENCY) != null; c = i.next()) {
n++;
}
assertEquals(4, n);
n = 0;
for(i.next(); i.getAttribute(NumberFormat.Field.INTEGER) != null && i.getAttribute(NumberFormat.Field.GROUPING_SEPARATOR) != NumberFormat.Field.GROUPING_SEPARATOR; c = i.next()) {
n++;
}
assertEquals(3, n);
assertEquals(NumberFormat.Field.INTEGER, i.getAttribute(NumberFormat.Field.INTEGER));
n = 0;
for(c = i.next(); i.getAttribute(NumberFormat.Field.INTEGER) != null; c = i.next()) {
n++;
}
assertEquals(3, n);
assertEquals(NumberFormat.Field.DECIMAL_SEPARATOR, i.getAttribute(NumberFormat.Field.DECIMAL_SEPARATOR));
n = 0;
for(c = i.next(); c != CharacterIterator.DONE; c = i.next()) {
n++;
assertNotNull(i.getAttribute(NumberFormat.Field.FRACTION));
}
assertEquals(2,n);
// immutability check
BtcFormat fa = BtcFormat.getSymbolInstance(US);
BtcFormat fb = BtcFormat.getSymbolInstance(US);
assertEquals(fa, fb);
assertEquals(fa.hashCode(), fb.hashCode());
fa.formatToCharacterIterator(COIN.multiply(1000000));
assertEquals(fa, fb);
assertEquals(fa.hashCode(), fb.hashCode());
fb.formatToCharacterIterator(COIN.divide(1000000));
assertEquals(fa, fb);
assertEquals(fa.hashCode(), fb.hashCode());
}
@Ignore("non-determinism between OpenJDK versions")
@Test
public void parseTest() throws java.text.ParseException {
BtcFormat us = BtcFormat.getSymbolInstance(Locale.US);
BtcFormat usCoded = BtcFormat.getCodeInstance(Locale.US);
// Coins
assertEquals(valueOf(200000000), us.parseObject("BTC2"));
assertEquals(valueOf(200000000), us.parseObject("XBT2"));
assertEquals(valueOf(200000000), us.parseObject("฿2"));
assertEquals(valueOf(200000000), us.parseObject("Ƀ2"));
assertEquals(valueOf(200000000), us.parseObject("2"));
assertEquals(valueOf(200000000), usCoded.parseObject("BTC 2"));
assertEquals(valueOf(200000000), usCoded.parseObject("XBT 2"));
assertEquals(valueOf(200000000), us.parseObject("฿2.0"));
assertEquals(valueOf(200000000), us.parseObject("Ƀ2.0"));
assertEquals(valueOf(200000000), us.parseObject("2.0"));
assertEquals(valueOf(200000000), us.parseObject("BTC2.0"));
assertEquals(valueOf(200000000), us.parseObject("XBT2.0"));
assertEquals(valueOf(200000000), usCoded.parseObject("฿ 2"));
assertEquals(valueOf(200000000), usCoded.parseObject("Ƀ 2"));
assertEquals(valueOf(200000000), usCoded.parseObject(" 2"));
assertEquals(valueOf(200000000), usCoded.parseObject("BTC 2"));
assertEquals(valueOf(200000000), usCoded.parseObject("XBT 2"));
assertEquals(valueOf(202222420000000L), us.parseObject("2,022,224.20"));
assertEquals(valueOf(202222420000000L), us.parseObject("฿2,022,224.20"));
assertEquals(valueOf(202222420000000L), us.parseObject("Ƀ2,022,224.20"));
assertEquals(valueOf(202222420000000L), us.parseObject("BTC2,022,224.20"));
assertEquals(valueOf(202222420000000L), us.parseObject("XBT2,022,224.20"));
assertEquals(valueOf(220200000000L), us.parseObject("2,202.0"));
assertEquals(valueOf(2100000000000000L), us.parseObject("21000000.00000000"));
// MilliCoins
assertEquals(valueOf(200000), usCoded.parseObject("mBTC 2"));
assertEquals(valueOf(200000), usCoded.parseObject("mXBT 2"));
assertEquals(valueOf(200000), usCoded.parseObject("m฿ 2"));
assertEquals(valueOf(200000), usCoded.parseObject("mɃ 2"));
assertEquals(valueOf(200000), us.parseObject("mBTC2"));
assertEquals(valueOf(200000), us.parseObject("mXBT2"));
assertEquals(valueOf(200000), us.parseObject("₥฿2"));
assertEquals(valueOf(200000), us.parseObject("₥Ƀ2"));
assertEquals(valueOf(200000), us.parseObject("₥2"));
assertEquals(valueOf(200000), usCoded.parseObject("₥BTC 2.00"));
assertEquals(valueOf(200000), usCoded.parseObject("₥XBT 2.00"));
assertEquals(valueOf(200000), usCoded.parseObject("₥BTC 2"));
assertEquals(valueOf(200000), usCoded.parseObject("₥XBT 2"));
assertEquals(valueOf(200000), usCoded.parseObject("₥฿ 2"));
assertEquals(valueOf(200000), usCoded.parseObject("₥Ƀ 2"));
assertEquals(valueOf(200000), usCoded.parseObject("₥ 2"));
assertEquals(valueOf(202222400000L), us.parseObject("₥฿2,022,224"));
assertEquals(valueOf(202222420000L), us.parseObject("₥Ƀ2,022,224.20"));
assertEquals(valueOf(202222400000L), us.parseObject("m฿2,022,224"));
assertEquals(valueOf(202222420000L), us.parseObject("mɃ2,022,224.20"));
assertEquals(valueOf(202222400000L), us.parseObject("₥BTC2,022,224"));
assertEquals(valueOf(202222400000L), us.parseObject("₥XBT2,022,224"));
assertEquals(valueOf(202222400000L), us.parseObject("mBTC2,022,224"));
assertEquals(valueOf(202222400000L), us.parseObject("mXBT2,022,224"));
assertEquals(valueOf(202222420000L), us.parseObject("₥2,022,224.20"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("₥฿ 2,022,224"));
assertEquals(valueOf(202222420000L), usCoded.parseObject("₥Ƀ 2,022,224.20"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("m฿ 2,022,224"));
assertEquals(valueOf(202222420000L), usCoded.parseObject("mɃ 2,022,224.20"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("₥BTC 2,022,224"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("₥XBT 2,022,224"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("mBTC 2,022,224"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("mXBT 2,022,224"));
assertEquals(valueOf(202222420000L), usCoded.parseObject("₥ 2,022,224.20"));
// Microcoins
assertEquals(valueOf(435), us.parseObject("µ฿4.35"));
assertEquals(valueOf(435), us.parseObject("uɃ4.35"));
assertEquals(valueOf(435), us.parseObject("u฿4.35"));
assertEquals(valueOf(435), us.parseObject("µɃ4.35"));
assertEquals(valueOf(435), us.parseObject("uBTC4.35"));
assertEquals(valueOf(435), us.parseObject("uXBT4.35"));
assertEquals(valueOf(435), us.parseObject("µBTC4.35"));
assertEquals(valueOf(435), us.parseObject("µXBT4.35"));
assertEquals(valueOf(435), usCoded.parseObject("uBTC 4.35"));
assertEquals(valueOf(435), usCoded.parseObject("uXBT 4.35"));
assertEquals(valueOf(435), usCoded.parseObject("µBTC 4.35"));
assertEquals(valueOf(435), usCoded.parseObject("µXBT 4.35"));
// fractional satoshi; round up
assertEquals(valueOf(435), us.parseObject("uBTC4.345"));
assertEquals(valueOf(435), us.parseObject("uXBT4.345"));
// negative with mu symbol
assertEquals(valueOf(-1), usCoded.parseObject("(µ฿ 0.01)"));
assertEquals(valueOf(-10), us.parseObject("(µBTC0.100)"));
assertEquals(valueOf(-10), us.parseObject("(µXBT0.100)"));
// Same thing with addition of custom code, symbol
us = BtcFormat.builder().locale(US).style(SYMBOL).symbol("£").code("XYZ").build();
usCoded = BtcFormat.builder().locale(US).scale(0).symbol("£").code("XYZ").
pattern("¤ #,##0.00").build();
// Coins
assertEquals(valueOf(200000000), us.parseObject("XYZ2"));
assertEquals(valueOf(200000000), us.parseObject("BTC2"));
assertEquals(valueOf(200000000), us.parseObject("XBT2"));
assertEquals(valueOf(200000000), us.parseObject("£2"));
assertEquals(valueOf(200000000), us.parseObject("฿2"));
assertEquals(valueOf(200000000), us.parseObject("Ƀ2"));
assertEquals(valueOf(200000000), us.parseObject("2"));
assertEquals(valueOf(200000000), usCoded.parseObject("XYZ 2"));
assertEquals(valueOf(200000000), usCoded.parseObject("BTC 2"));
assertEquals(valueOf(200000000), usCoded.parseObject("XBT 2"));
assertEquals(valueOf(200000000), us.parseObject("£2.0"));
assertEquals(valueOf(200000000), us.parseObject("฿2.0"));
assertEquals(valueOf(200000000), us.parseObject("Ƀ2.0"));
assertEquals(valueOf(200000000), us.parseObject("2.0"));
assertEquals(valueOf(200000000), us.parseObject("XYZ2.0"));
assertEquals(valueOf(200000000), us.parseObject("BTC2.0"));
assertEquals(valueOf(200000000), us.parseObject("XBT2.0"));
assertEquals(valueOf(200000000), usCoded.parseObject("£ 2"));
assertEquals(valueOf(200000000), usCoded.parseObject("฿ 2"));
assertEquals(valueOf(200000000), usCoded.parseObject("Ƀ 2"));
assertEquals(valueOf(200000000), usCoded.parseObject(" 2"));
assertEquals(valueOf(200000000), usCoded.parseObject("XYZ 2"));
assertEquals(valueOf(200000000), usCoded.parseObject("BTC 2"));
assertEquals(valueOf(200000000), usCoded.parseObject("XBT 2"));
assertEquals(valueOf(202222420000000L), us.parseObject("2,022,224.20"));
assertEquals(valueOf(202222420000000L), us.parseObject("£2,022,224.20"));
assertEquals(valueOf(202222420000000L), us.parseObject("฿2,022,224.20"));
assertEquals(valueOf(202222420000000L), us.parseObject("Ƀ2,022,224.20"));
assertEquals(valueOf(202222420000000L), us.parseObject("XYZ2,022,224.20"));
assertEquals(valueOf(202222420000000L), us.parseObject("BTC2,022,224.20"));
assertEquals(valueOf(202222420000000L), us.parseObject("XBT2,022,224.20"));
assertEquals(valueOf(220200000000L), us.parseObject("2,202.0"));
assertEquals(valueOf(2100000000000000L), us.parseObject("21000000.00000000"));
// MilliCoins
assertEquals(valueOf(200000), usCoded.parseObject("mXYZ 2"));
assertEquals(valueOf(200000), usCoded.parseObject("mBTC 2"));
assertEquals(valueOf(200000), usCoded.parseObject("mXBT 2"));
assertEquals(valueOf(200000), usCoded.parseObject("m£ 2"));
assertEquals(valueOf(200000), usCoded.parseObject("m฿ 2"));
assertEquals(valueOf(200000), usCoded.parseObject("mɃ 2"));
assertEquals(valueOf(200000), us.parseObject("mXYZ2"));
assertEquals(valueOf(200000), us.parseObject("mBTC2"));
assertEquals(valueOf(200000), us.parseObject("mXBT2"));
assertEquals(valueOf(200000), us.parseObject("₥£2"));
assertEquals(valueOf(200000), us.parseObject("₥฿2"));
assertEquals(valueOf(200000), us.parseObject("₥Ƀ2"));
assertEquals(valueOf(200000), us.parseObject("₥2"));
assertEquals(valueOf(200000), usCoded.parseObject("₥XYZ 2.00"));
assertEquals(valueOf(200000), usCoded.parseObject("₥BTC 2.00"));
assertEquals(valueOf(200000), usCoded.parseObject("₥XBT 2.00"));
assertEquals(valueOf(200000), usCoded.parseObject("₥XYZ 2"));
assertEquals(valueOf(200000), usCoded.parseObject("₥BTC 2"));
assertEquals(valueOf(200000), usCoded.parseObject("₥XBT 2"));
assertEquals(valueOf(200000), usCoded.parseObject("₥£ 2"));
assertEquals(valueOf(200000), usCoded.parseObject("₥฿ 2"));
assertEquals(valueOf(200000), usCoded.parseObject("₥Ƀ 2"));
assertEquals(valueOf(200000), usCoded.parseObject("₥ 2"));
assertEquals(valueOf(202222400000L), us.parseObject("₥£2,022,224"));
assertEquals(valueOf(202222400000L), us.parseObject("₥฿2,022,224"));
assertEquals(valueOf(202222420000L), us.parseObject("₥Ƀ2,022,224.20"));
assertEquals(valueOf(202222400000L), us.parseObject("m£2,022,224"));
assertEquals(valueOf(202222400000L), us.parseObject("m฿2,022,224"));
assertEquals(valueOf(202222420000L), us.parseObject("mɃ2,022,224.20"));
assertEquals(valueOf(202222400000L), us.parseObject("₥XYZ2,022,224"));
assertEquals(valueOf(202222400000L), us.parseObject("₥BTC2,022,224"));
assertEquals(valueOf(202222400000L), us.parseObject("₥XBT2,022,224"));
assertEquals(valueOf(202222400000L), us.parseObject("mXYZ2,022,224"));
assertEquals(valueOf(202222400000L), us.parseObject("mBTC2,022,224"));
assertEquals(valueOf(202222400000L), us.parseObject("mXBT2,022,224"));
assertEquals(valueOf(202222420000L), us.parseObject("₥2,022,224.20"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("₥£ 2,022,224"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("₥฿ 2,022,224"));
assertEquals(valueOf(202222420000L), usCoded.parseObject("₥Ƀ 2,022,224.20"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("m£ 2,022,224"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("m฿ 2,022,224"));
assertEquals(valueOf(202222420000L), usCoded.parseObject("mɃ 2,022,224.20"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("₥XYZ 2,022,224"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("₥BTC 2,022,224"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("₥XBT 2,022,224"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("mXYZ 2,022,224"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("mBTC 2,022,224"));
assertEquals(valueOf(202222400000L), usCoded.parseObject("mXBT 2,022,224"));
assertEquals(valueOf(202222420000L), usCoded.parseObject("₥ 2,022,224.20"));
// Microcoins
assertEquals(valueOf(435), us.parseObject("µ£4.35"));
assertEquals(valueOf(435), us.parseObject("µ฿4.35"));
assertEquals(valueOf(435), us.parseObject("uɃ4.35"));
assertEquals(valueOf(435), us.parseObject("u£4.35"));
assertEquals(valueOf(435), us.parseObject("u฿4.35"));
assertEquals(valueOf(435), us.parseObject("µɃ4.35"));
assertEquals(valueOf(435), us.parseObject("uXYZ4.35"));
assertEquals(valueOf(435), us.parseObject("uBTC4.35"));
assertEquals(valueOf(435), us.parseObject("uXBT4.35"));
assertEquals(valueOf(435), us.parseObject("µXYZ4.35"));
assertEquals(valueOf(435), us.parseObject("µBTC4.35"));
assertEquals(valueOf(435), us.parseObject("µXBT4.35"));
assertEquals(valueOf(435), usCoded.parseObject("uXYZ 4.35"));
assertEquals(valueOf(435), usCoded.parseObject("uBTC 4.35"));
assertEquals(valueOf(435), usCoded.parseObject("uXBT 4.35"));
assertEquals(valueOf(435), usCoded.parseObject("µXYZ 4.35"));
assertEquals(valueOf(435), usCoded.parseObject("µBTC 4.35"));
assertEquals(valueOf(435), usCoded.parseObject("µXBT 4.35"));
// fractional satoshi; round up
assertEquals(valueOf(435), us.parseObject("uXYZ4.345"));
assertEquals(valueOf(435), us.parseObject("uBTC4.345"));
assertEquals(valueOf(435), us.parseObject("uXBT4.345"));
// negative with mu symbol
assertEquals(valueOf(-1), usCoded.parseObject("µ£ -0.01"));
assertEquals(valueOf(-1), usCoded.parseObject("µ฿ -0.01"));
assertEquals(valueOf(-10), us.parseObject("(µXYZ0.100)"));
assertEquals(valueOf(-10), us.parseObject("(µBTC0.100)"));
assertEquals(valueOf(-10), us.parseObject("(µXBT0.100)"));
// parse() method as opposed to parseObject
try {
BtcFormat.getInstance().parse("abc");
fail("bad parse must raise exception");
} catch (ParseException e) {}
}
@Test
public void parseMetricTest() throws ParseException {
BtcFormat cp = BtcFormat.getCodeInstance(Locale.US);
BtcFormat sp = BtcFormat.getSymbolInstance(Locale.US);
// coin
assertEquals(parseCoin("1"), cp.parseObject("BTC 1.00"));
assertEquals(parseCoin("1"), sp.parseObject("BTC1.00"));
assertEquals(parseCoin("1"), cp.parseObject("฿ 1.00"));
assertEquals(parseCoin("1"), sp.parseObject("฿1.00"));
assertEquals(parseCoin("1"), cp.parseObject("B⃦ 1.00"));
assertEquals(parseCoin("1"), sp.parseObject("B⃦1.00"));
assertEquals(parseCoin("1"), cp.parseObject("Ƀ 1.00"));
assertEquals(parseCoin("1"), sp.parseObject("Ƀ1.00"));
// milli
assertEquals(parseCoin("0.001"), cp.parseObject("mBTC 1.00"));
assertEquals(parseCoin("0.001"), sp.parseObject("mBTC1.00"));
assertEquals(parseCoin("0.001"), cp.parseObject("m฿ 1.00"));
assertEquals(parseCoin("0.001"), sp.parseObject("m฿1.00"));
assertEquals(parseCoin("0.001"), cp.parseObject("mB⃦ 1.00"));
assertEquals(parseCoin("0.001"), sp.parseObject("mB⃦1.00"));
assertEquals(parseCoin("0.001"), cp.parseObject("mɃ 1.00"));
assertEquals(parseCoin("0.001"), sp.parseObject("mɃ1.00"));
assertEquals(parseCoin("0.001"), cp.parseObject("₥BTC 1.00"));
assertEquals(parseCoin("0.001"), sp.parseObject("₥BTC1.00"));
assertEquals(parseCoin("0.001"), cp.parseObject("₥฿ 1.00"));
assertEquals(parseCoin("0.001"), sp.parseObject("₥฿1.00"));
assertEquals(parseCoin("0.001"), cp.parseObject("₥B⃦ 1.00"));
assertEquals(parseCoin("0.001"), sp.parseObject("₥B⃦1.00"));
assertEquals(parseCoin("0.001"), cp.parseObject("₥Ƀ 1.00"));
assertEquals(parseCoin("0.001"), sp.parseObject("₥Ƀ1.00"));
// micro
assertEquals(parseCoin("0.000001"), cp.parseObject("uBTC 1.00"));
assertEquals(parseCoin("0.000001"), sp.parseObject("uBTC1.00"));
assertEquals(parseCoin("0.000001"), cp.parseObject("u฿ 1.00"));
assertEquals(parseCoin("0.000001"), sp.parseObject("u฿1.00"));
assertEquals(parseCoin("0.000001"), cp.parseObject("uB⃦ 1.00"));
assertEquals(parseCoin("0.000001"), sp.parseObject("uB⃦1.00"));
assertEquals(parseCoin("0.000001"), cp.parseObject("uɃ 1.00"));
assertEquals(parseCoin("0.000001"), sp.parseObject("uɃ1.00"));
assertEquals(parseCoin("0.000001"), cp.parseObject("µBTC 1.00"));
assertEquals(parseCoin("0.000001"), sp.parseObject("µBTC1.00"));
assertEquals(parseCoin("0.000001"), cp.parseObject("µ฿ 1.00"));
assertEquals(parseCoin("0.000001"), sp.parseObject("µ฿1.00"));
assertEquals(parseCoin("0.000001"), cp.parseObject("µB⃦ 1.00"));
assertEquals(parseCoin("0.000001"), sp.parseObject("µB⃦1.00"));
assertEquals(parseCoin("0.000001"), cp.parseObject("µɃ 1.00"));
assertEquals(parseCoin("0.000001"), sp.parseObject("µɃ1.00"));
// satoshi
assertEquals(parseCoin("0.00000001"), cp.parseObject("uBTC 0.01"));
assertEquals(parseCoin("0.00000001"), sp.parseObject("uBTC0.01"));
assertEquals(parseCoin("0.00000001"), cp.parseObject("u฿ 0.01"));
assertEquals(parseCoin("0.00000001"), sp.parseObject("u฿0.01"));
assertEquals(parseCoin("0.00000001"), cp.parseObject("uB⃦ 0.01"));
assertEquals(parseCoin("0.00000001"), sp.parseObject("uB⃦0.01"));
assertEquals(parseCoin("0.00000001"), cp.parseObject("uɃ 0.01"));
assertEquals(parseCoin("0.00000001"), sp.parseObject("uɃ0.01"));
assertEquals(parseCoin("0.00000001"), cp.parseObject("µBTC 0.01"));
assertEquals(parseCoin("0.00000001"), sp.parseObject("µBTC0.01"));
assertEquals(parseCoin("0.00000001"), cp.parseObject("µ฿ 0.01"));
assertEquals(parseCoin("0.00000001"), sp.parseObject("µ฿0.01"));
assertEquals(parseCoin("0.00000001"), cp.parseObject("µB⃦ 0.01"));
assertEquals(parseCoin("0.00000001"), sp.parseObject("µB⃦0.01"));
assertEquals(parseCoin("0.00000001"), cp.parseObject("µɃ 0.01"));
assertEquals(parseCoin("0.00000001"), sp.parseObject("µɃ0.01"));
// cents
assertEquals(parseCoin("0.01234567"), cp.parseObject("cBTC 1.234567"));
assertEquals(parseCoin("0.01234567"), sp.parseObject("cBTC1.234567"));
assertEquals(parseCoin("0.01234567"), cp.parseObject("c฿ 1.234567"));
assertEquals(parseCoin("0.01234567"), sp.parseObject("c฿1.234567"));
assertEquals(parseCoin("0.01234567"), cp.parseObject("cB⃦ 1.234567"));
assertEquals(parseCoin("0.01234567"), sp.parseObject("cB⃦1.234567"));
assertEquals(parseCoin("0.01234567"), cp.parseObject("cɃ 1.234567"));
assertEquals(parseCoin("0.01234567"), sp.parseObject("cɃ1.234567"));
assertEquals(parseCoin("0.01234567"), cp.parseObject("¢BTC 1.234567"));
assertEquals(parseCoin("0.01234567"), sp.parseObject("¢BTC1.234567"));
assertEquals(parseCoin("0.01234567"), cp.parseObject("¢฿ 1.234567"));
assertEquals(parseCoin("0.01234567"), sp.parseObject("¢฿1.234567"));
assertEquals(parseCoin("0.01234567"), cp.parseObject("¢B⃦ 1.234567"));
assertEquals(parseCoin("0.01234567"), sp.parseObject("¢B⃦1.234567"));
assertEquals(parseCoin("0.01234567"), cp.parseObject("¢Ƀ 1.234567"));
assertEquals(parseCoin("0.01234567"), sp.parseObject("¢Ƀ1.234567"));
// dekacoins
assertEquals(parseCoin("12.34567"), cp.parseObject("daBTC 1.234567"));
assertEquals(parseCoin("12.34567"), sp.parseObject("daBTC1.234567"));
assertEquals(parseCoin("12.34567"), cp.parseObject("da฿ 1.234567"));
assertEquals(parseCoin("12.34567"), sp.parseObject("da฿1.234567"));
assertEquals(parseCoin("12.34567"), cp.parseObject("daB⃦ 1.234567"));
assertEquals(parseCoin("12.34567"), sp.parseObject("daB⃦1.234567"));
assertEquals(parseCoin("12.34567"), cp.parseObject("daɃ 1.234567"));
assertEquals(parseCoin("12.34567"), sp.parseObject("daɃ1.234567"));
// hectocoins
assertEquals(parseCoin("123.4567"), cp.parseObject("hBTC 1.234567"));
assertEquals(parseCoin("123.4567"), sp.parseObject("hBTC1.234567"));
assertEquals(parseCoin("123.4567"), cp.parseObject("h฿ 1.234567"));
assertEquals(parseCoin("123.4567"), sp.parseObject("h฿1.234567"));
assertEquals(parseCoin("123.4567"), cp.parseObject("hB⃦ 1.234567"));
assertEquals(parseCoin("123.4567"), sp.parseObject("hB⃦1.234567"));
assertEquals(parseCoin("123.4567"), cp.parseObject("hɃ 1.234567"));
assertEquals(parseCoin("123.4567"), sp.parseObject("hɃ1.234567"));
// kilocoins
assertEquals(parseCoin("1234.567"), cp.parseObject("kBTC 1.234567"));
assertEquals(parseCoin("1234.567"), sp.parseObject("kBTC1.234567"));
assertEquals(parseCoin("1234.567"), cp.parseObject("k฿ 1.234567"));
assertEquals(parseCoin("1234.567"), sp.parseObject("k฿1.234567"));
assertEquals(parseCoin("1234.567"), cp.parseObject("kB⃦ 1.234567"));
assertEquals(parseCoin("1234.567"), sp.parseObject("kB⃦1.234567"));
assertEquals(parseCoin("1234.567"), cp.parseObject("kɃ 1.234567"));
assertEquals(parseCoin("1234.567"), sp.parseObject("kɃ1.234567"));
// megacoins
assertEquals(parseCoin("1234567"), cp.parseObject("MBTC 1.234567"));
assertEquals(parseCoin("1234567"), sp.parseObject("MBTC1.234567"));
assertEquals(parseCoin("1234567"), cp.parseObject("M฿ 1.234567"));
assertEquals(parseCoin("1234567"), sp.parseObject("M฿1.234567"));
assertEquals(parseCoin("1234567"), cp.parseObject("MB⃦ 1.234567"));
assertEquals(parseCoin("1234567"), sp.parseObject("MB⃦1.234567"));
assertEquals(parseCoin("1234567"), cp.parseObject("MɃ 1.234567"));
assertEquals(parseCoin("1234567"), sp.parseObject("MɃ1.234567"));
}
@Test
public void parsePositionTest() {
BtcFormat usCoded = BtcFormat.getCodeInstance(Locale.US);
// Test the field constants
FieldPosition intField = new FieldPosition(NumberFormat.Field.INTEGER);
assertEquals(
"987,654,321",
usCoded.format(valueOf(98765432123L), new StringBuffer(), intField).
substring(intField.getBeginIndex(), intField.getEndIndex())
);
FieldPosition fracField = new FieldPosition(NumberFormat.Field.FRACTION);
assertEquals(
"23",
usCoded.format(valueOf(98765432123L), new StringBuffer(), fracField).
substring(fracField.getBeginIndex(), fracField.getEndIndex())
);
// for currency we use a locale that puts the units at the end
BtcFormat de = BtcFormat.getSymbolInstance(Locale.GERMANY);
BtcFormat deCoded = BtcFormat.getCodeInstance(Locale.GERMANY);
FieldPosition currField = new FieldPosition(NumberFormat.Field.CURRENCY);
assertEquals(
"µ฿",
de.format(valueOf(98765432123L), new StringBuffer(), currField).
substring(currField.getBeginIndex(), currField.getEndIndex())
);
assertEquals(
"µBTC",
deCoded.format(valueOf(98765432123L), new StringBuffer(), currField).
substring(currField.getBeginIndex(), currField.getEndIndex())
);
assertEquals(
"₥฿",
de.format(valueOf(98765432000L), new StringBuffer(), currField).
substring(currField.getBeginIndex(), currField.getEndIndex())
);
assertEquals(
"mBTC",
deCoded.format(valueOf(98765432000L), new StringBuffer(), currField).
substring(currField.getBeginIndex(), currField.getEndIndex())
);
assertEquals(
"฿",
de.format(valueOf(98765000000L), new StringBuffer(), currField).
substring(currField.getBeginIndex(), currField.getEndIndex())
);
assertEquals(
"BTC",
deCoded.format(valueOf(98765000000L), new StringBuffer(), currField).
substring(currField.getBeginIndex(), currField.getEndIndex())
);
}
@Ignore("non-determinism between OpenJDK versions")
@Test
public void currencyCodeTest() {
/* Insert needed space AFTER currency-code */
BtcFormat usCoded = BtcFormat.getCodeInstance(Locale.US);
assertEquals("µBTC 0.01", usCoded.format(1));
assertEquals("BTC 1.00", usCoded.format(COIN));
/* Do not insert unneeded space BEFORE currency-code */
BtcFormat frCoded = BtcFormat.getCodeInstance(Locale.FRANCE);
assertEquals("0,01 µBTC", frCoded.format(1));
assertEquals("1,00 BTC", frCoded.format(COIN));
/* Insert needed space BEFORE currency-code: no known currency pattern does this? */
/* Do not insert unneeded space AFTER currency-code */
BtcFormat deCoded = BtcFormat.getCodeInstance(Locale.ITALY);
assertEquals("µBTC 0,01", deCoded.format(1));
assertEquals("BTC 1,00", deCoded.format(COIN));
}
@Test
public void coinScaleTest() throws Exception {
BtcFormat coinFormat = BtcFormat.getCoinInstance(Locale.US);
assertEquals("1.00", coinFormat.format(Coin.COIN));
assertEquals("-1.00", coinFormat.format(Coin.COIN.negate()));
assertEquals(Coin.parseCoin("1"), coinFormat.parseObject("1.00"));
assertEquals(valueOf(1000000), coinFormat.parseObject("0.01"));
assertEquals(Coin.parseCoin("1000"), coinFormat.parseObject("1,000.00"));
assertEquals(Coin.parseCoin("1000"), coinFormat.parseObject("1000"));
}
@Test
public void millicoinScaleTest() throws Exception {
BtcFormat coinFormat = BtcFormat.getMilliInstance(Locale.US);
assertEquals("1,000.00", coinFormat.format(Coin.COIN));
assertEquals("-1,000.00", coinFormat.format(Coin.COIN.negate()));
assertEquals(Coin.parseCoin("0.001"), coinFormat.parseObject("1.00"));
assertEquals(valueOf(1000), coinFormat.parseObject("0.01"));
assertEquals(Coin.parseCoin("1"), coinFormat.parseObject("1,000.00"));
assertEquals(Coin.parseCoin("1"), coinFormat.parseObject("1000"));
}
@Test
public void microcoinScaleTest() throws Exception {
BtcFormat coinFormat = BtcFormat.getMicroInstance(Locale.US);
assertEquals("1,000,000.00", coinFormat.format(Coin.COIN));
assertEquals("-1,000,000.00", coinFormat.format(Coin.COIN.negate()));
assertEquals("1,000,000.10", coinFormat.format(Coin.COIN.add(valueOf(10))));
assertEquals(Coin.parseCoin("0.000001"), coinFormat.parseObject("1.00"));
assertEquals(valueOf(1), coinFormat.parseObject("0.01"));
assertEquals(Coin.parseCoin("0.001"), coinFormat.parseObject("1,000.00"));
assertEquals(Coin.parseCoin("0.001"), coinFormat.parseObject("1000"));
}
@Test
public void testGrouping() {
BtcFormat usCoin = BtcFormat.getInstance(0, Locale.US, 1, 2, 3);
assertEquals("0.1", usCoin.format(Coin.parseCoin("0.1")));
assertEquals("0.010", usCoin.format(Coin.parseCoin("0.01")));
assertEquals("0.001", usCoin.format(Coin.parseCoin("0.001")));
assertEquals("0.000100", usCoin.format(Coin.parseCoin("0.0001")));
assertEquals("0.000010", usCoin.format(Coin.parseCoin("0.00001")));
assertEquals("0.000001", usCoin.format(Coin.parseCoin("0.000001")));
// no more than two fractional decimal places for the default coin-denomination
assertEquals("0.01", BtcFormat.getCoinInstance(Locale.US).format(Coin.parseCoin("0.005")));
BtcFormat usMilli = BtcFormat.getInstance(3, Locale.US, 1, 2, 3);
assertEquals("0.1", usMilli.format(Coin.parseCoin("0.0001")));
assertEquals("0.010", usMilli.format(Coin.parseCoin("0.00001")));
assertEquals("0.001", usMilli.format(Coin.parseCoin("0.000001")));
// even though last group is 3, that would result in fractional satoshis, which we don't do
assertEquals("0.00010", usMilli.format(Coin.valueOf(10)));
assertEquals("0.00001", usMilli.format(Coin.valueOf(1)));
BtcFormat usMicro = BtcFormat.getInstance(6, Locale.US, 1, 2, 3);
assertEquals("0.1", usMicro.format(Coin.valueOf(10)));
// even though second group is 2, that would result in fractional satoshis, which we don't do
assertEquals("0.01", usMicro.format(Coin.valueOf(1)));
}
/* These just make sure factory methods don't raise exceptions.
* Other tests inspect their return values. */
@Test
public void factoryTest() {
BtcFormat coded = BtcFormat.getInstance(0, 1, 2, 3);
BtcFormat.getInstance(BtcAutoFormat.Style.CODE);
BtcAutoFormat symbolic = (BtcAutoFormat)BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL);
assertEquals(2, symbolic.fractionPlaces());
BtcFormat.getInstance(BtcAutoFormat.Style.CODE, 3);
assertEquals(3, ((BtcAutoFormat)BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL, 3)).fractionPlaces());
BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL, Locale.US, 3);
BtcFormat.getInstance(BtcAutoFormat.Style.CODE, Locale.US);
BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL, Locale.US);
BtcFormat.getCoinInstance(2, BtcFixedFormat.REPEATING_PLACES);
BtcFormat.getMilliInstance(1, 2, 3);
BtcFormat.getInstance(2);
BtcFormat.getInstance(2, Locale.US);
BtcFormat.getCodeInstance(3);
BtcFormat.getSymbolInstance(3);
BtcFormat.getCodeInstance(Locale.US, 3);
BtcFormat.getSymbolInstance(Locale.US, 3);
try {
BtcFormat.getInstance(SMALLEST_UNIT_EXPONENT + 1);
fail("should not have constructed an instance with denomination less than satoshi");
} catch (IllegalArgumentException e) {}
}
@Test
public void factoryArgumentsTest() {
Locale locale;
if (Locale.getDefault().equals(GERMANY)) locale = FRANCE;
else locale = GERMANY;
assertEquals(BtcFormat.getInstance(), BtcFormat.getCodeInstance());
assertEquals(BtcFormat.getInstance(locale), BtcFormat.getCodeInstance(locale));
assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.CODE), BtcFormat.getCodeInstance());
assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL), BtcFormat.getSymbolInstance());
assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.CODE,3), BtcFormat.getCodeInstance(3));
assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL,3), BtcFormat.getSymbolInstance(3));
assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.CODE,locale), BtcFormat.getCodeInstance(locale));
assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL,locale), BtcFormat.getSymbolInstance(locale));
assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.CODE,locale,3), BtcFormat.getCodeInstance(locale,3));
assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL,locale,3), BtcFormat.getSymbolInstance(locale,3));
assertEquals(BtcFormat.getCoinInstance(), BtcFormat.getInstance(0));
assertEquals(BtcFormat.getMilliInstance(), BtcFormat.getInstance(3));
assertEquals(BtcFormat.getMicroInstance(), BtcFormat.getInstance(6));
assertEquals(BtcFormat.getCoinInstance(3), BtcFormat.getInstance(0,3));
assertEquals(BtcFormat.getMilliInstance(3), BtcFormat.getInstance(3,3));
assertEquals(BtcFormat.getMicroInstance(3), BtcFormat.getInstance(6,3));
assertEquals(BtcFormat.getCoinInstance(3,4,5), BtcFormat.getInstance(0,3,4,5));
assertEquals(BtcFormat.getMilliInstance(3,4,5), BtcFormat.getInstance(3,3,4,5));
assertEquals(BtcFormat.getMicroInstance(3,4,5), BtcFormat.getInstance(6,3,4,5));
assertEquals(BtcFormat.getCoinInstance(locale), BtcFormat.getInstance(0,locale));
assertEquals(BtcFormat.getMilliInstance(locale), BtcFormat.getInstance(3,locale));
assertEquals(BtcFormat.getMicroInstance(locale), BtcFormat.getInstance(6,locale));
assertEquals(BtcFormat.getCoinInstance(locale,4,5), BtcFormat.getInstance(0,locale,4,5));
assertEquals(BtcFormat.getMilliInstance(locale,4,5), BtcFormat.getInstance(3,locale,4,5));
assertEquals(BtcFormat.getMicroInstance(locale,4,5), BtcFormat.getInstance(6,locale,4,5));
}
@Test
public void autoDecimalTest() {
BtcFormat codedZero = BtcFormat.getCodeInstance(Locale.US, 0);
BtcFormat symbolZero = BtcFormat.getSymbolInstance(Locale.US, 0);
assertEquals("฿1", symbolZero.format(COIN));
assertEquals("BTC 1", codedZero.format(COIN));
assertEquals("µ฿1,000,000", symbolZero.format(COIN.subtract(SATOSHI)));
assertEquals("µBTC 1,000,000", codedZero.format(COIN.subtract(SATOSHI)));
assertEquals("µ฿1,000,000", symbolZero.format(COIN.subtract(Coin.valueOf(50))));
assertEquals("µBTC 1,000,000", codedZero.format(COIN.subtract(Coin.valueOf(50))));
assertEquals("µ฿999,999", symbolZero.format(COIN.subtract(Coin.valueOf(51))));
assertEquals("µBTC 999,999", codedZero.format(COIN.subtract(Coin.valueOf(51))));
assertEquals("฿1,000", symbolZero.format(COIN.multiply(1000)));
assertEquals("BTC 1,000", codedZero.format(COIN.multiply(1000)));
assertEquals("µ฿1", symbolZero.format(Coin.valueOf(100)));
assertEquals("µBTC 1", codedZero.format(Coin.valueOf(100)));
assertEquals("µ฿1", symbolZero.format(Coin.valueOf(50)));
assertEquals("µBTC 1", codedZero.format(Coin.valueOf(50)));
assertEquals("µ฿0", symbolZero.format(Coin.valueOf(49)));
assertEquals("µBTC 0", codedZero.format(Coin.valueOf(49)));
assertEquals("µ฿0", symbolZero.format(Coin.valueOf(1)));
assertEquals("µBTC 0", codedZero.format(Coin.valueOf(1)));
assertEquals("µ฿500,000", symbolZero.format(Coin.valueOf(49999999)));
assertEquals("µBTC 500,000", codedZero.format(Coin.valueOf(49999999)));
assertEquals("µ฿499,500", symbolZero.format(Coin.valueOf(49950000)));
assertEquals("µBTC 499,500", codedZero.format(Coin.valueOf(49950000)));
assertEquals("µ฿499,500", symbolZero.format(Coin.valueOf(49949999)));
assertEquals("µBTC 499,500", codedZero.format(Coin.valueOf(49949999)));
assertEquals("µ฿500,490", symbolZero.format(Coin.valueOf(50049000)));
assertEquals("µBTC 500,490", codedZero.format(Coin.valueOf(50049000)));
assertEquals("µ฿500,490", symbolZero.format(Coin.valueOf(50049001)));
assertEquals("µBTC 500,490", codedZero.format(Coin.valueOf(50049001)));
assertEquals("µ฿500,000", symbolZero.format(Coin.valueOf(49999950)));
assertEquals("µBTC 500,000", codedZero.format(Coin.valueOf(49999950)));
assertEquals("µ฿499,999", symbolZero.format(Coin.valueOf(49999949)));
assertEquals("µBTC 499,999", codedZero.format(Coin.valueOf(49999949)));
assertEquals("µ฿500,000", symbolZero.format(Coin.valueOf(50000049)));
assertEquals("µBTC 500,000", codedZero.format(Coin.valueOf(50000049)));
assertEquals("µ฿500,001", symbolZero.format(Coin.valueOf(50000050)));
assertEquals("µBTC 500,001", codedZero.format(Coin.valueOf(50000050)));
BtcFormat codedTwo = BtcFormat.getCodeInstance(Locale.US, 2);
BtcFormat symbolTwo = BtcFormat.getSymbolInstance(Locale.US, 2);
assertEquals("฿1.00", symbolTwo.format(COIN));
assertEquals("BTC 1.00", codedTwo.format(COIN));
assertEquals("µ฿999,999.99", symbolTwo.format(COIN.subtract(SATOSHI)));
assertEquals("µBTC 999,999.99", codedTwo.format(COIN.subtract(SATOSHI)));
assertEquals("฿1,000.00", symbolTwo.format(COIN.multiply(1000)));
assertEquals("BTC 1,000.00", codedTwo.format(COIN.multiply(1000)));
assertEquals("µ฿1.00", symbolTwo.format(Coin.valueOf(100)));
assertEquals("µBTC 1.00", codedTwo.format(Coin.valueOf(100)));
assertEquals("µ฿0.50", symbolTwo.format(Coin.valueOf(50)));
assertEquals("µBTC 0.50", codedTwo.format(Coin.valueOf(50)));
assertEquals("µ฿0.49", symbolTwo.format(Coin.valueOf(49)));
assertEquals("µBTC 0.49", codedTwo.format(Coin.valueOf(49)));
assertEquals("µ฿0.01", symbolTwo.format(Coin.valueOf(1)));
assertEquals("µBTC 0.01", codedTwo.format(Coin.valueOf(1)));
BtcFormat codedThree = BtcFormat.getCodeInstance(Locale.US, 3);
BtcFormat symbolThree = BtcFormat.getSymbolInstance(Locale.US, 3);
assertEquals("฿1.000", symbolThree.format(COIN));
assertEquals("BTC 1.000", codedThree.format(COIN));
assertEquals("µ฿999,999.99", symbolThree.format(COIN.subtract(SATOSHI)));
assertEquals("µBTC 999,999.99", codedThree.format(COIN.subtract(SATOSHI)));
assertEquals("฿1,000.000", symbolThree.format(COIN.multiply(1000)));
assertEquals("BTC 1,000.000", codedThree.format(COIN.multiply(1000)));
assertEquals("₥฿0.001", symbolThree.format(Coin.valueOf(100)));
assertEquals("mBTC 0.001", codedThree.format(Coin.valueOf(100)));
assertEquals("µ฿0.50", symbolThree.format(Coin.valueOf(50)));
assertEquals("µBTC 0.50", codedThree.format(Coin.valueOf(50)));
assertEquals("µ฿0.49", symbolThree.format(Coin.valueOf(49)));
assertEquals("µBTC 0.49", codedThree.format(Coin.valueOf(49)));
assertEquals("µ฿0.01", symbolThree.format(Coin.valueOf(1)));
assertEquals("µBTC 0.01", codedThree.format(Coin.valueOf(1)));
}
@Test
public void symbolsCodesTest() {
BtcFixedFormat coin = (BtcFixedFormat)BtcFormat.getCoinInstance(US);
assertEquals("BTC", coin.code());
assertEquals("฿", coin.symbol());
BtcFixedFormat cent = (BtcFixedFormat)BtcFormat.getInstance(2, US);
assertEquals("cBTC", cent.code());
assertEquals("¢฿", cent.symbol());
BtcFixedFormat milli = (BtcFixedFormat)BtcFormat.getInstance(3, US);
assertEquals("mBTC", milli.code());
assertEquals("₥฿", milli.symbol());
BtcFixedFormat micro = (BtcFixedFormat)BtcFormat.getInstance(6, US);
assertEquals("µBTC", micro.code());
assertEquals("µ฿", micro.symbol());
BtcFixedFormat deka = (BtcFixedFormat)BtcFormat.getInstance(-1, US);
assertEquals("daBTC", deka.code());
assertEquals("da฿", deka.symbol());
BtcFixedFormat hecto = (BtcFixedFormat)BtcFormat.getInstance(-2, US);
assertEquals("hBTC", hecto.code());
assertEquals("h฿", hecto.symbol());
BtcFixedFormat kilo = (BtcFixedFormat)BtcFormat.getInstance(-3, US);
assertEquals("kBTC", kilo.code());
assertEquals("k฿", kilo.symbol());
BtcFixedFormat mega = (BtcFixedFormat)BtcFormat.getInstance(-6, US);
assertEquals("MBTC", mega.code());
assertEquals("M฿", mega.symbol());
BtcFixedFormat noSymbol = (BtcFixedFormat)BtcFormat.getInstance(4, US);
try {
noSymbol.symbol();
fail("non-standard denomination has no symbol()");
} catch (IllegalStateException e) {}
try {
noSymbol.code();
fail("non-standard denomination has no code()");
} catch (IllegalStateException e) {}
BtcFixedFormat symbolCoin = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(0).
symbol("B\u20e6").build();
assertEquals("BTC", symbolCoin.code());
assertEquals("B⃦", symbolCoin.symbol());
BtcFixedFormat symbolCent = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(2).
symbol("B\u20e6").build();
assertEquals("cBTC", symbolCent.code());
assertEquals("¢B⃦", symbolCent.symbol());
BtcFixedFormat symbolMilli = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(3).
symbol("B\u20e6").build();
assertEquals("mBTC", symbolMilli.code());
assertEquals("₥B⃦", symbolMilli.symbol());
BtcFixedFormat symbolMicro = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(6).
symbol("B\u20e6").build();
assertEquals("µBTC", symbolMicro.code());
assertEquals("µB⃦", symbolMicro.symbol());
BtcFixedFormat symbolDeka = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-1).
symbol("B\u20e6").build();
assertEquals("daBTC", symbolDeka.code());
assertEquals("daB⃦", symbolDeka.symbol());
BtcFixedFormat symbolHecto = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-2).
symbol("B\u20e6").build();
assertEquals("hBTC", symbolHecto.code());
assertEquals("hB⃦", symbolHecto.symbol());
BtcFixedFormat symbolKilo = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-3).
symbol("B\u20e6").build();
assertEquals("kBTC", symbolKilo.code());
assertEquals("kB⃦", symbolKilo.symbol());
BtcFixedFormat symbolMega = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-6).
symbol("B\u20e6").build();
assertEquals("MBTC", symbolMega.code());
assertEquals("MB⃦", symbolMega.symbol());
BtcFixedFormat codeCoin = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(0).
code("XBT").build();
assertEquals("XBT", codeCoin.code());
assertEquals("฿", codeCoin.symbol());
BtcFixedFormat codeCent = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(2).
code("XBT").build();
assertEquals("cXBT", codeCent.code());
assertEquals("¢฿", codeCent.symbol());
BtcFixedFormat codeMilli = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(3).
code("XBT").build();
assertEquals("mXBT", codeMilli.code());
assertEquals("₥฿", codeMilli.symbol());
BtcFixedFormat codeMicro = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(6).
code("XBT").build();
assertEquals("µXBT", codeMicro.code());
assertEquals("µ฿", codeMicro.symbol());
BtcFixedFormat codeDeka = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-1).
code("XBT").build();
assertEquals("daXBT", codeDeka.code());
assertEquals("da฿", codeDeka.symbol());
BtcFixedFormat codeHecto = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-2).
code("XBT").build();
assertEquals("hXBT", codeHecto.code());
assertEquals("h฿", codeHecto.symbol());
BtcFixedFormat codeKilo = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-3).
code("XBT").build();
assertEquals("kXBT", codeKilo.code());
assertEquals("k฿", codeKilo.symbol());
BtcFixedFormat codeMega = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-6).
code("XBT").build();
assertEquals("MXBT", codeMega.code());
assertEquals("M฿", codeMega.symbol());
BtcFixedFormat symbolCodeCoin = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(0).
symbol("B\u20e6").code("XBT").build();
assertEquals("XBT", symbolCodeCoin.code());
assertEquals("B⃦", symbolCodeCoin.symbol());
BtcFixedFormat symbolCodeCent = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(2).
symbol("B\u20e6").code("XBT").build();
assertEquals("cXBT", symbolCodeCent.code());
assertEquals("¢B⃦", symbolCodeCent.symbol());
BtcFixedFormat symbolCodeMilli = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(3).
symbol("B\u20e6").code("XBT").build();
assertEquals("mXBT", symbolCodeMilli.code());
assertEquals("₥B⃦", symbolCodeMilli.symbol());
BtcFixedFormat symbolCodeMicro = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(6).
symbol("B\u20e6").code("XBT").build();
assertEquals("µXBT", symbolCodeMicro.code());
assertEquals("µB⃦", symbolCodeMicro.symbol());
BtcFixedFormat symbolCodeDeka = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-1).
symbol("B\u20e6").code("XBT").build();
assertEquals("daXBT", symbolCodeDeka.code());
assertEquals("daB⃦", symbolCodeDeka.symbol());
BtcFixedFormat symbolCodeHecto = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-2).
symbol("B\u20e6").code("XBT").build();
assertEquals("hXBT", symbolCodeHecto.code());
assertEquals("hB⃦", symbolCodeHecto.symbol());
BtcFixedFormat symbolCodeKilo = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-3).
symbol("B\u20e6").code("XBT").build();
assertEquals("kXBT", symbolCodeKilo.code());
assertEquals("kB⃦", symbolCodeKilo.symbol());
BtcFixedFormat symbolCodeMega = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-6).
symbol("B\u20e6").code("XBT").build();
assertEquals("MXBT", symbolCodeMega.code());
assertEquals("MB⃦", symbolCodeMega.symbol());
}
/* copied from CoinFormatTest.java and modified */
@Test
public void parse() throws Exception {
BtcFormat coin = BtcFormat.getCoinInstance(Locale.US);
assertEquals(Coin.COIN, coin.parseObject("1"));
assertEquals(Coin.COIN, coin.parseObject("1."));
assertEquals(Coin.COIN, coin.parseObject("1.0"));
assertEquals(Coin.COIN, BtcFormat.getCoinInstance(Locale.GERMANY).parseObject("1,0"));
assertEquals(Coin.COIN, coin.parseObject("01.0000000000"));
// TODO work with express positive sign
// assertEquals(Coin.COIN, coin.parseObject("+1.0"));
assertEquals(Coin.COIN.negate(), coin.parseObject("-1"));
assertEquals(Coin.COIN.negate(), coin.parseObject("-1.0"));
assertEquals(Coin.CENT, coin.parseObject(".01"));
BtcFormat milli = BtcFormat.getMilliInstance(Locale.US);
assertEquals(Coin.MILLICOIN, milli.parseObject("1"));
assertEquals(Coin.MILLICOIN, milli.parseObject("1.0"));
assertEquals(Coin.MILLICOIN, milli.parseObject("01.0000000000"));
// TODO work with express positive sign
//assertEquals(Coin.MILLICOIN, milli.parseObject("+1.0"));
assertEquals(Coin.MILLICOIN.negate(), milli.parseObject("-1"));
assertEquals(Coin.MILLICOIN.negate(), milli.parseObject("-1.0"));
BtcFormat micro = BtcFormat.getMicroInstance(Locale.US);
assertEquals(Coin.MICROCOIN, micro.parseObject("1"));
assertEquals(Coin.MICROCOIN, micro.parseObject("1.0"));
assertEquals(Coin.MICROCOIN, micro.parseObject("01.0000000000"));
// TODO work with express positive sign
// assertEquals(Coin.MICROCOIN, micro.parseObject("+1.0"));
assertEquals(Coin.MICROCOIN.negate(), micro.parseObject("-1"));
assertEquals(Coin.MICROCOIN.negate(), micro.parseObject("-1.0"));
}
/* Copied (and modified) from CoinFormatTest.java */
@Test
public void btcRounding() {
BtcFormat coinFormat = BtcFormat.getCoinInstance(Locale.US);
assertEquals("0", BtcFormat.getCoinInstance(Locale.US, 0).format(ZERO));
assertEquals("0", coinFormat.format(ZERO, 0));
assertEquals("0.00", BtcFormat.getCoinInstance(Locale.US, 2).format(ZERO));
assertEquals("0.00", coinFormat.format(ZERO, 2));
assertEquals("1", BtcFormat.getCoinInstance(Locale.US, 0).format(COIN));
assertEquals("1", coinFormat.format(COIN, 0));
assertEquals("1.0", BtcFormat.getCoinInstance(Locale.US, 1).format(COIN));
assertEquals("1.0", coinFormat.format(COIN, 1));
assertEquals("1.00", BtcFormat.getCoinInstance(Locale.US, 2, 2).format(COIN));
assertEquals("1.00", coinFormat.format(COIN, 2, 2));
assertEquals("1.00", BtcFormat.getCoinInstance(Locale.US, 2, 2, 2).format(COIN));
assertEquals("1.00", coinFormat.format(COIN, 2, 2, 2));
assertEquals("1.00", BtcFormat.getCoinInstance(Locale.US, 2, 2, 2, 2).format(COIN));
assertEquals("1.00", coinFormat.format(COIN, 2, 2, 2, 2));
assertEquals("1.000", BtcFormat.getCoinInstance(Locale.US, 3).format(COIN));
assertEquals("1.000", coinFormat.format(COIN, 3));
assertEquals("1.0000", BtcFormat.getCoinInstance(US, 4).format(COIN));
assertEquals("1.0000", coinFormat.format(COIN, 4));
final Coin justNot = COIN.subtract(SATOSHI);
assertEquals("1", BtcFormat.getCoinInstance(US, 0).format(justNot));
assertEquals("1", coinFormat.format(justNot, 0));
assertEquals("1.0", BtcFormat.getCoinInstance(US, 1).format(justNot));
assertEquals("1.0", coinFormat.format(justNot, 1));
final Coin justNotUnder = Coin.valueOf(99995000);
assertEquals("1.00", BtcFormat.getCoinInstance(US, 2, 2).format(justNot));
assertEquals("1.00", coinFormat.format(justNot, 2, 2));
assertEquals("1.00", BtcFormat.getCoinInstance(US, 2, 2).format(justNotUnder));
assertEquals("1.00", coinFormat.format(justNotUnder, 2, 2));
assertEquals("1.00", BtcFormat.getCoinInstance(US, 2, 2, 2).format(justNot));
assertEquals("1.00", coinFormat.format(justNot, 2, 2, 2));
assertEquals("0.999950", BtcFormat.getCoinInstance(US, 2, 2, 2).format(justNotUnder));
assertEquals("0.999950", coinFormat.format(justNotUnder, 2, 2, 2));
assertEquals("0.99999999", BtcFormat.getCoinInstance(US, 2, 2, 2, 2).format(justNot));
assertEquals("0.99999999", coinFormat.format(justNot, 2, 2, 2, 2));
assertEquals("0.99999999", BtcFormat.getCoinInstance(US, 2, REPEATING_DOUBLETS).format(justNot));
assertEquals("0.99999999", coinFormat.format(justNot, 2, REPEATING_DOUBLETS));
assertEquals("0.999950", BtcFormat.getCoinInstance(US, 2, 2, 2, 2).format(justNotUnder));
assertEquals("0.999950", coinFormat.format(justNotUnder, 2, 2, 2, 2));
assertEquals("0.999950", BtcFormat.getCoinInstance(US, 2, REPEATING_DOUBLETS).format(justNotUnder));
assertEquals("0.999950", coinFormat.format(justNotUnder, 2, REPEATING_DOUBLETS));
assertEquals("1.000", BtcFormat.getCoinInstance(US, 3).format(justNot));
assertEquals("1.000", coinFormat.format(justNot, 3));
assertEquals("1.0000", BtcFormat.getCoinInstance(US, 4).format(justNot));
assertEquals("1.0000", coinFormat.format(justNot, 4));
final Coin slightlyMore = COIN.add(SATOSHI);
assertEquals("1", BtcFormat.getCoinInstance(US, 0).format(slightlyMore));
assertEquals("1", coinFormat.format(slightlyMore, 0));
assertEquals("1.0", BtcFormat.getCoinInstance(US, 1).format(slightlyMore));
assertEquals("1.0", coinFormat.format(slightlyMore, 1));
assertEquals("1.00", BtcFormat.getCoinInstance(US, 2, 2).format(slightlyMore));
assertEquals("1.00", coinFormat.format(slightlyMore, 2, 2));
assertEquals("1.00", BtcFormat.getCoinInstance(US, 2, 2, 2).format(slightlyMore));
assertEquals("1.00", coinFormat.format(slightlyMore, 2, 2, 2));
assertEquals("1.00000001", BtcFormat.getCoinInstance(US, 2, 2, 2, 2).format(slightlyMore));
assertEquals("1.00000001", coinFormat.format(slightlyMore, 2, 2, 2, 2));
assertEquals("1.00000001", BtcFormat.getCoinInstance(US, 2, REPEATING_DOUBLETS).format(slightlyMore));
assertEquals("1.00000001", coinFormat.format(slightlyMore, 2, REPEATING_DOUBLETS));
assertEquals("1.000", BtcFormat.getCoinInstance(US, 3).format(slightlyMore));
assertEquals("1.000", coinFormat.format(slightlyMore, 3));
assertEquals("1.0000", BtcFormat.getCoinInstance(US, 4).format(slightlyMore));
assertEquals("1.0000", coinFormat.format(slightlyMore, 4));
final Coin pivot = COIN.add(SATOSHI.multiply(5));
assertEquals("1.00000005", BtcFormat.getCoinInstance(US, 8).format(pivot));
assertEquals("1.00000005", coinFormat.format(pivot, 8));
assertEquals("1.00000005", BtcFormat.getCoinInstance(US, 7, 1).format(pivot));
assertEquals("1.00000005", coinFormat.format(pivot, 7, 1));
assertEquals("1.0000001", BtcFormat.getCoinInstance(US, 7).format(pivot));
assertEquals("1.0000001", coinFormat.format(pivot, 7));
final Coin value = Coin.valueOf(1122334455667788l);
assertEquals("11,223,345", BtcFormat.getCoinInstance(US, 0).format(value));
assertEquals("11,223,345", coinFormat.format(value, 0));
assertEquals("11,223,344.6", BtcFormat.getCoinInstance(US, 1).format(value));
assertEquals("11,223,344.6", coinFormat.format(value, 1));
assertEquals("11,223,344.5567", BtcFormat.getCoinInstance(US, 2, 2).format(value));
assertEquals("11,223,344.5567", coinFormat.format(value, 2, 2));
assertEquals("11,223,344.556678", BtcFormat.getCoinInstance(US, 2, 2, 2).format(value));
assertEquals("11,223,344.556678", coinFormat.format(value, 2, 2, 2));
assertEquals("11,223,344.55667788", BtcFormat.getCoinInstance(US, 2, 2, 2, 2).format(value));
assertEquals("11,223,344.55667788", coinFormat.format(value, 2, 2, 2, 2));
assertEquals("11,223,344.55667788", BtcFormat.getCoinInstance(US, 2, REPEATING_DOUBLETS).format(value));
assertEquals("11,223,344.55667788", coinFormat.format(value, 2, REPEATING_DOUBLETS));
assertEquals("11,223,344.557", BtcFormat.getCoinInstance(US, 3).format(value));
assertEquals("11,223,344.557", coinFormat.format(value, 3));
assertEquals("11,223,344.5567", BtcFormat.getCoinInstance(US, 4).format(value));
assertEquals("11,223,344.5567", coinFormat.format(value, 4));
BtcFormat megaFormat = BtcFormat.getInstance(-6, US);
assertEquals("21.00", megaFormat.format(MAX_MONEY));
assertEquals("21", megaFormat.format(MAX_MONEY, 0));
assertEquals("11.22334455667788", megaFormat.format(value, 0, REPEATING_DOUBLETS));
assertEquals("11.223344556677", megaFormat.format(Coin.valueOf(1122334455667700l), 0, REPEATING_DOUBLETS));
assertEquals("11.22334455667788", megaFormat.format(value, 0, REPEATING_TRIPLETS));
assertEquals("11.223344556677", megaFormat.format(Coin.valueOf(1122334455667700l), 0, REPEATING_TRIPLETS));
}
@Ignore("non-determinism between OpenJDK versions")
@Test
public void negativeTest() {
assertEquals("-1,00 BTC", BtcFormat.getInstance(FRANCE).format(COIN.multiply(-1)));
assertEquals("BTC -1,00", BtcFormat.getInstance(ITALY).format(COIN.multiply(-1)));
assertEquals("฿ -1,00", BtcFormat.getSymbolInstance(ITALY).format(COIN.multiply(-1)));
assertEquals("BTC -1.00", BtcFormat.getInstance(JAPAN).format(COIN.multiply(-1)));
assertEquals("฿-1.00", BtcFormat.getSymbolInstance(JAPAN).format(COIN.multiply(-1)));
assertEquals("(BTC 1.00)", BtcFormat.getInstance(US).format(COIN.multiply(-1)));
assertEquals("(฿1.00)", BtcFormat.getSymbolInstance(US).format(COIN.multiply(-1)));
// assertEquals("BTC -१.००", BtcFormat.getInstance(Locale.forLanguageTag("hi-IN")).format(COIN.multiply(-1)));
assertEquals("BTC -๑.๐๐", BtcFormat.getInstance(new Locale("th","TH","TH")).format(COIN.multiply(-1)));
assertEquals("Ƀ-๑.๐๐", BtcFormat.getSymbolInstance(new Locale("th","TH","TH")).format(COIN.multiply(-1)));
}
/* Warning: these tests assume the state of Locale data extant on the platform on which
* they were written: openjdk 7u21-2.3.9-5 */
@Test
public void equalityTest() throws Exception {
// First, autodenominator
assertEquals(BtcFormat.getInstance(), BtcFormat.getInstance());
assertEquals(BtcFormat.getInstance().hashCode(), BtcFormat.getInstance().hashCode());
assertNotEquals(BtcFormat.getCodeInstance(), BtcFormat.getSymbolInstance());
assertNotEquals(BtcFormat.getCodeInstance().hashCode(), BtcFormat.getSymbolInstance().hashCode());
assertEquals(BtcFormat.getSymbolInstance(5), BtcFormat.getSymbolInstance(5));
assertEquals(BtcFormat.getSymbolInstance(5).hashCode(), BtcFormat.getSymbolInstance(5).hashCode());
assertNotEquals(BtcFormat.getSymbolInstance(5), BtcFormat.getSymbolInstance(4));
assertNotEquals(BtcFormat.getSymbolInstance(5).hashCode(), BtcFormat.getSymbolInstance(4).hashCode());
/* The underlying formatter is mutable, and its currency code
* and symbol may be reset each time a number is
* formatted or parsed. Here we check to make sure that state is
* ignored when comparing for equality */
// when formatting
BtcAutoFormat a = (BtcAutoFormat)BtcFormat.getSymbolInstance(US);
BtcAutoFormat b = (BtcAutoFormat)BtcFormat.getSymbolInstance(US);
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
a.format(COIN.multiply(1000000));
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
b.format(COIN.divide(1000000));
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
// when parsing
a = (BtcAutoFormat)BtcFormat.getSymbolInstance(US);
b = (BtcAutoFormat)BtcFormat.getSymbolInstance(US);
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
a.parseObject("mBTC2");
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
b.parseObject("µ฿4.35");
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
// FRANCE and GERMANY have different pattterns
assertNotEquals(BtcFormat.getInstance(FRANCE).hashCode(), BtcFormat.getInstance(GERMANY).hashCode());
// TAIWAN and CHINA differ only in the Locale and Currency, i.e. the patterns and symbols are
// all the same (after setting the currency symbols to bitcoins)
assertNotEquals(BtcFormat.getInstance(TAIWAN), BtcFormat.getInstance(CHINA));
// but they hash the same because of the DecimalFormatSymbols.hashCode() implementation
assertEquals(BtcFormat.getSymbolInstance(4), BtcFormat.getSymbolInstance(4));
assertEquals(BtcFormat.getSymbolInstance(4).hashCode(), BtcFormat.getSymbolInstance(4).hashCode());
assertNotEquals(BtcFormat.getSymbolInstance(4), BtcFormat.getSymbolInstance(5));
assertNotEquals(BtcFormat.getSymbolInstance(4).hashCode(), BtcFormat.getSymbolInstance(5).hashCode());
// Fixed-denomination
assertEquals(BtcFormat.getCoinInstance(), BtcFormat.getCoinInstance());
assertEquals(BtcFormat.getCoinInstance().hashCode(), BtcFormat.getCoinInstance().hashCode());
assertEquals(BtcFormat.getMilliInstance(), BtcFormat.getMilliInstance());
assertEquals(BtcFormat.getMilliInstance().hashCode(), BtcFormat.getMilliInstance().hashCode());
assertEquals(BtcFormat.getMicroInstance(), BtcFormat.getMicroInstance());
assertEquals(BtcFormat.getMicroInstance().hashCode(), BtcFormat.getMicroInstance().hashCode());
assertEquals(BtcFormat.getInstance(-6), BtcFormat.getInstance(-6));
assertEquals(BtcFormat.getInstance(-6).hashCode(), BtcFormat.getInstance(-6).hashCode());
assertNotEquals(BtcFormat.getCoinInstance(), BtcFormat.getMilliInstance());
assertNotEquals(BtcFormat.getCoinInstance().hashCode(), BtcFormat.getMilliInstance().hashCode());
assertNotEquals(BtcFormat.getCoinInstance(), BtcFormat.getMicroInstance());
assertNotEquals(BtcFormat.getCoinInstance().hashCode(), BtcFormat.getMicroInstance().hashCode());
assertNotEquals(BtcFormat.getMilliInstance(), BtcFormat.getMicroInstance());
assertNotEquals(BtcFormat.getMilliInstance().hashCode(), BtcFormat.getMicroInstance().hashCode());
assertNotEquals(BtcFormat.getInstance(SMALLEST_UNIT_EXPONENT),
BtcFormat.getInstance(SMALLEST_UNIT_EXPONENT - 1));
assertNotEquals(BtcFormat.getInstance(SMALLEST_UNIT_EXPONENT).hashCode(),
BtcFormat.getInstance(SMALLEST_UNIT_EXPONENT - 1).hashCode());
assertNotEquals(BtcFormat.getCoinInstance(TAIWAN), BtcFormat.getCoinInstance(CHINA));
assertNotEquals(BtcFormat.getCoinInstance(2,3), BtcFormat.getCoinInstance(2,4));
assertNotEquals(BtcFormat.getCoinInstance(2,3).hashCode(), BtcFormat.getCoinInstance(2,4).hashCode());
assertNotEquals(BtcFormat.getCoinInstance(2,3), BtcFormat.getCoinInstance(2,3,3));
assertNotEquals(BtcFormat.getCoinInstance(2,3).hashCode(), BtcFormat.getCoinInstance(2,3,3).hashCode());
}
@Ignore("non-determinism between OpenJDK versions")
@Test
public void attributeTest() {
String codePat = BtcFormat.getCodeInstance(Locale.US).pattern();
assertTrue(codePat.contains("BTC") && ! codePat.contains("(^|[^฿])฿([^฿]|$)") && ! codePat.contains("(^|[^¤])¤([^¤]|$)"));
String symPat = BtcFormat.getSymbolInstance(Locale.US).pattern();
assertTrue(symPat.contains("฿") && !symPat.contains("BTC") && !symPat.contains("¤¤"));
assertEquals("BTC #,##0.00;(BTC #,##0.00)", BtcFormat.getCodeInstance(Locale.US).pattern());
assertEquals("฿#,##0.00;(฿#,##0.00)", BtcFormat.getSymbolInstance(Locale.US).pattern());
assertEquals('0', BtcFormat.getInstance(Locale.US).symbols().getZeroDigit());
// assertEquals('०', BtcFormat.getInstance(Locale.forLanguageTag("hi-IN")).symbols().getZeroDigit());
// TODO will this next line work with other JREs?
assertEquals('๐', BtcFormat.getInstance(new Locale("th","TH","TH")).symbols().getZeroDigit());
}
@Ignore("non-determinism between OpenJDK versions")
@Test
public void toStringTest() {
assertEquals("Auto-format ฿#,##0.00;(฿#,##0.00)", BtcFormat.getSymbolInstance(Locale.US).toString());
assertEquals("Auto-format ฿#,##0.0000;(฿#,##0.0000)", BtcFormat.getSymbolInstance(Locale.US, 4).toString());
assertEquals("Auto-format BTC #,##0.00;(BTC #,##0.00)", BtcFormat.getCodeInstance(Locale.US).toString());
assertEquals("Auto-format BTC #,##0.0000;(BTC #,##0.0000)", BtcFormat.getCodeInstance(Locale.US, 4).toString());
assertEquals("Coin-format #,##0.00", BtcFormat.getCoinInstance(Locale.US).toString());
assertEquals("Millicoin-format #,##0.00", BtcFormat.getMilliInstance(Locale.US).toString());
assertEquals("Microcoin-format #,##0.00", BtcFormat.getMicroInstance(Locale.US).toString());
assertEquals("Coin-format #,##0.000", BtcFormat.getCoinInstance(Locale.US,3).toString());
assertEquals("Coin-format #,##0.000(####)(#######)", BtcFormat.getCoinInstance(Locale.US,3,4,7).toString());
assertEquals("Kilocoin-format #,##0.000", BtcFormat.getInstance(-3,Locale.US,3).toString());
assertEquals("Kilocoin-format #,##0.000(####)(#######)", BtcFormat.getInstance(-3,Locale.US,3,4,7).toString());
assertEquals("Decicoin-format #,##0.000", BtcFormat.getInstance(1,Locale.US,3).toString());
assertEquals("Decicoin-format #,##0.000(####)(#######)", BtcFormat.getInstance(1,Locale.US,3,4,7).toString());
assertEquals("Dekacoin-format #,##0.000", BtcFormat.getInstance(-1,Locale.US,3).toString());
assertEquals("Dekacoin-format #,##0.000(####)(#######)", BtcFormat.getInstance(-1,Locale.US,3,4,7).toString());
assertEquals("Hectocoin-format #,##0.000", BtcFormat.getInstance(-2,Locale.US,3).toString());
assertEquals("Hectocoin-format #,##0.000(####)(#######)", BtcFormat.getInstance(-2,Locale.US,3,4,7).toString());
assertEquals("Megacoin-format #,##0.000", BtcFormat.getInstance(-6,Locale.US,3).toString());
assertEquals("Megacoin-format #,##0.000(####)(#######)", BtcFormat.getInstance(-6,Locale.US,3,4,7).toString());
assertEquals("Fixed (-4) format #,##0.000", BtcFormat.getInstance(-4,Locale.US,3).toString());
assertEquals("Fixed (-4) format #,##0.000(####)", BtcFormat.getInstance(-4,Locale.US,3,4).toString());
assertEquals("Fixed (-4) format #,##0.000(####)(#######)",
BtcFormat.getInstance(-4, Locale.US, 3, 4, 7).toString());
assertEquals("Auto-format ฿#,##0.00;(฿#,##0.00)",
BtcFormat.builder().style(SYMBOL).code("USD").locale(US).build().toString());
assertEquals("Auto-format #.##0,00 $",
BtcFormat.builder().style(SYMBOL).symbol("$").locale(GERMANY).build().toString());
assertEquals("Auto-format #.##0,0000 $",
BtcFormat.builder().style(SYMBOL).symbol("$").fractionDigits(4).locale(GERMANY).build().toString());
assertEquals("Auto-format BTC#,00฿;BTC-#,00฿",
BtcFormat.builder().style(SYMBOL).locale(GERMANY).pattern("¤¤#¤").build().toString());
assertEquals("Coin-format BTC#,00฿;BTC-#,00฿",
BtcFormat.builder().scale(0).locale(GERMANY).pattern("¤¤#¤").build().toString());
assertEquals("Millicoin-format BTC#.00฿;BTC-#.00฿",
BtcFormat.builder().scale(3).locale(US).pattern("¤¤#¤").build().toString());
}
@Test
public void patternDecimalPlaces() {
/* The pattern format provided by DecimalFormat includes specification of fractional digits,
* but we ignore that because we have alternative mechanism for specifying that.. */
BtcFormat f = BtcFormat.builder().locale(US).scale(3).pattern("¤¤ #.0").fractionDigits(3).build();
assertEquals("Millicoin-format BTC #.000;BTC -#.000", f.toString());
assertEquals("mBTC 1000.000", f.format(COIN));
}
@Ignore("non-determinism between OpenJDK versions")
@Test
public void builderTest() {
Locale locale;
if (Locale.getDefault().equals(GERMANY)) locale = FRANCE;
else locale = GERMANY;
assertEquals(BtcFormat.builder().build(), BtcFormat.getCoinInstance());
try {
BtcFormat.builder().scale(0).style(CODE);
fail("Invoking both scale() and style() on a Builder should raise exception");
} catch (IllegalStateException e) {}
try {
BtcFormat.builder().style(CODE).scale(0);
fail("Invoking both style() and scale() on a Builder should raise exception");
} catch (IllegalStateException e) {}
BtcFormat built = BtcFormat.builder().style(BtcAutoFormat.Style.CODE).fractionDigits(4).build();
assertEquals(built, BtcFormat.getCodeInstance(4));
built = BtcFormat.builder().style(BtcAutoFormat.Style.SYMBOL).fractionDigits(4).build();
assertEquals(built, BtcFormat.getSymbolInstance(4));
built = BtcFormat.builder().scale(0).build();
assertEquals(built, BtcFormat.getCoinInstance());
built = BtcFormat.builder().scale(3).build();
assertEquals(built, BtcFormat.getMilliInstance());
built = BtcFormat.builder().scale(6).build();
assertEquals(built, BtcFormat.getMicroInstance());
built = BtcFormat.builder().locale(locale).scale(0).build();
assertEquals(built, BtcFormat.getCoinInstance(locale));
built = BtcFormat.builder().locale(locale).scale(3).build();
assertEquals(built, BtcFormat.getMilliInstance(locale));
built = BtcFormat.builder().locale(locale).scale(6).build();
assertEquals(built, BtcFormat.getMicroInstance(locale));
built = BtcFormat.builder().minimumFractionDigits(3).scale(0).build();
assertEquals(built, BtcFormat.getCoinInstance(3));
built = BtcFormat.builder().minimumFractionDigits(3).scale(3).build();
assertEquals(built, BtcFormat.getMilliInstance(3));
built = BtcFormat.builder().minimumFractionDigits(3).scale(6).build();
assertEquals(built, BtcFormat.getMicroInstance(3));
built = BtcFormat.builder().fractionGroups(3,4).scale(0).build();
assertEquals(built, BtcFormat.getCoinInstance(2,3,4));
built = BtcFormat.builder().fractionGroups(3,4).scale(3).build();
assertEquals(built, BtcFormat.getMilliInstance(2,3,4));
built = BtcFormat.builder().fractionGroups(3,4).scale(6).build();
assertEquals(built, BtcFormat.getMicroInstance(2,3,4));
built = BtcFormat.builder().pattern("#,####.#").scale(6).locale(GERMANY).build();
assertEquals("100.0000,00", built.format(COIN));
built = BtcFormat.builder().pattern("#,####.#").scale(6).locale(GERMANY).build();
assertEquals("-100.0000,00", built.format(COIN.multiply(-1)));
built = BtcFormat.builder().localizedPattern("#.####,#").scale(6).locale(GERMANY).build();
assertEquals("100.0000,00", built.format(COIN));
built = BtcFormat.builder().pattern("¤#,####.#").style(CODE).locale(GERMANY).build();
assertEquals("฿-1,00", built.format(COIN.multiply(-1)));
built = BtcFormat.builder().pattern("¤¤ #,####.#").style(SYMBOL).locale(GERMANY).build();
assertEquals("BTC -1,00", built.format(COIN.multiply(-1)));
built = BtcFormat.builder().pattern("¤¤##,###.#").scale(3).locale(US).build();
assertEquals("mBTC1,000.00", built.format(COIN));
built = BtcFormat.builder().pattern("¤ ##,###.#").scale(3).locale(US).build();
assertEquals("₥฿ 1,000.00", built.format(COIN));
try {
BtcFormat.builder().pattern("¤¤##,###.#").scale(4).locale(US).build().format(COIN);
fail("Pattern with currency sign and non-standard denomination should raise exception");
} catch (IllegalStateException e) {}
try {
BtcFormat.builder().localizedPattern("¤¤##,###.#").scale(4).locale(US).build().format(COIN);
fail("Localized pattern with currency sign and non-standard denomination should raise exception");
} catch (IllegalStateException e) {}
built = BtcFormat.builder().style(SYMBOL).symbol("B\u20e6").locale(US).build();
assertEquals("B⃦1.00", built.format(COIN));
built = BtcFormat.builder().style(CODE).code("XBT").locale(US).build();
assertEquals("XBT 1.00", built.format(COIN));
built = BtcFormat.builder().style(SYMBOL).symbol("$").locale(GERMANY).build();
assertEquals("1,00 $", built.format(COIN));
// Setting the currency code on a DecimalFormatSymbols object can affect the currency symbol.
built = BtcFormat.builder().style(SYMBOL).code("USD").locale(US).build();
assertEquals("฿1.00", built.format(COIN));
built = BtcFormat.builder().style(SYMBOL).symbol("B\u20e6").locale(US).build();
assertEquals("₥B⃦1.00", built.format(COIN.divide(1000)));
built = BtcFormat.builder().style(CODE).code("XBT").locale(US).build();
assertEquals("mXBT 1.00", built.format(COIN.divide(1000)));
built = BtcFormat.builder().style(SYMBOL).symbol("B\u20e6").locale(US).build();
assertEquals("µB⃦1.00", built.format(valueOf(100)));
built = BtcFormat.builder().style(CODE).code("XBT").locale(US).build();
assertEquals("µXBT 1.00", built.format(valueOf(100)));
/* The prefix of a pattern can have number symbols in quotes.
* Make sure our custom negative-subpattern creator handles this. */
built = BtcFormat.builder().pattern("'#'¤#0").scale(0).locale(US).build();
assertEquals("#฿-1.00", built.format(COIN.multiply(-1)));
built = BtcFormat.builder().pattern("'#0'¤#0").scale(0).locale(US).build();
assertEquals("#0฿-1.00", built.format(COIN.multiply(-1)));
// this is an escaped quote between two hash marks in one set of quotes, not
// two adjacent quote-enclosed hash-marks:
built = BtcFormat.builder().pattern("'#''#'¤#0").scale(0).locale(US).build();
assertEquals("#'#฿-1.00", built.format(COIN.multiply(-1)));
built = BtcFormat.builder().pattern("'#0''#'¤#0").scale(0).locale(US).build();
assertEquals("#0'#฿-1.00", built.format(COIN.multiply(-1)));
built = BtcFormat.builder().pattern("'#0#'¤#0").scale(0).locale(US).build();
assertEquals("#0#฿-1.00", built.format(COIN.multiply(-1)));
built = BtcFormat.builder().pattern("'#0'E'#'¤#0").scale(0).locale(US).build();
assertEquals("#0E#฿-1.00", built.format(COIN.multiply(-1)));
built = BtcFormat.builder().pattern("E'#0''#'¤#0").scale(0).locale(US).build();
assertEquals("E#0'#฿-1.00", built.format(COIN.multiply(-1)));
built = BtcFormat.builder().pattern("E'#0#'¤#0").scale(0).locale(US).build();
assertEquals("E#0#฿-1.00", built.format(COIN.multiply(-1)));
built = BtcFormat.builder().pattern("E'#0''''#'¤#0").scale(0).locale(US).build();
assertEquals("E#0''#฿-1.00", built.format(COIN.multiply(-1)));
built = BtcFormat.builder().pattern("''#0").scale(0).locale(US).build();
assertEquals("'-1.00", built.format(COIN.multiply(-1)));
// immutability check for fixed-denomination formatters, w/ & w/o custom pattern
BtcFormat a = BtcFormat.builder().scale(3).build();
BtcFormat b = BtcFormat.builder().scale(3).build();
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
a.format(COIN.multiply(1000000));
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
b.format(COIN.divide(1000000));
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
a = BtcFormat.builder().scale(3).pattern("¤#.#").build();
b = BtcFormat.builder().scale(3).pattern("¤#.#").build();
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
a.format(COIN.multiply(1000000));
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
b.format(COIN.divide(1000000));
assertEquals(a, b);
assertEquals(a.hashCode(), b.hashCode());
}
}
| 90,545
| 59.043767
| 430
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/script/ScriptChunkSizeTest.java
|
/*
* Copyright 2019 Matthew Leon Grinshpun
*
* 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.
*/
package org.bitcoinj.script;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import static org.bitcoinj.script.ScriptOpCodes.OP_NOP;
import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA1;
import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA2;
import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA4;
import static org.junit.Assert.assertEquals;
/**
* ScriptChunk.size() determines the size of a serialized ScriptChunk without actually performing serialization.
* This parameterized test is meant to exhaustively prove that the method does what it promises.
*/
@RunWith(value = Parameterized.class)
public class ScriptChunkSizeTest {
private static final Random RANDOM = new Random(42);
@Parameterized.Parameter
public ScriptChunk scriptChunk;
@Parameterized.Parameters
public static Collection<ScriptChunk> data() {
ArrayList<ScriptChunk> opcodes = new ArrayList<>(0xff);
for (int op = OP_NOP; op < 0xff + 1; op++)
opcodes.add(new ScriptChunk(op, null));
ArrayList<ScriptChunk> smallData = new ArrayList<>(OP_PUSHDATA1);
for (int op = 1; op < OP_PUSHDATA1; op++)
smallData.add(new ScriptChunk(op, randomBytes(op)));
ArrayList<ScriptChunk> pushData1 = new ArrayList<>(0xff);
for (int i = 0; i < 0xff + 1; i++)
pushData1.add(new ScriptChunk(OP_PUSHDATA1, randomBytes(i)));
ArrayList<ScriptChunk> pushData2 = new ArrayList<>(Script.MAX_SCRIPT_ELEMENT_SIZE + 1);
for (int i = 0; i < Script.MAX_SCRIPT_ELEMENT_SIZE + 1; i++)
pushData2.add(new ScriptChunk(OP_PUSHDATA2, randomBytes(i)));
ArrayList<ScriptChunk> pushData4 = new ArrayList<>(Script.MAX_SCRIPT_ELEMENT_SIZE + 1);
for (int i = 0; i < Script.MAX_SCRIPT_ELEMENT_SIZE + 1; i++)
pushData4.add(new ScriptChunk(OP_PUSHDATA4, randomBytes(i)));
List<ScriptChunk> temp = new ArrayList<>();
temp.addAll(opcodes);
temp.addAll(smallData);
temp.addAll(pushData1);
temp.addAll(pushData2);
temp.addAll(pushData4);
return Collections.unmodifiableList(temp);
}
private static byte[] randomBytes(int size) {
byte[] bytes = new byte[size];
RANDOM.nextBytes(bytes);
return bytes;
}
@Test
public void testSize() {
assertEquals(scriptChunk.toByteArray().length, scriptChunk.size());
}
}
| 3,218
| 35.168539
| 112
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/script/ScriptBuilderTest.java
|
/*
* Copyright 2018 Nicola Atzei
*
* 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.
*/
package org.bitcoinj.script;
import org.junit.Test;
import static org.bitcoinj.script.ScriptOpCodes.OP_FALSE;
import static org.bitcoinj.script.ScriptOpCodes.OP_TRUE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ScriptBuilderTest {
@Test
public void testNumber() {
for (int i = -100; i <= 100; i++) {
Script s = new ScriptBuilder().number(i).build();
for (ScriptChunk ch : s.chunks()) {
assertTrue(Integer.toString(i), ch.isShortestPossiblePushData());
}
}
}
@Test
public void numberBuilderZero() {
// Test encoding of zero, which should result in an opcode
final ScriptBuilder builder = new ScriptBuilder();
// 0 should encode directly to 0
builder.number(0);
assertArrayEquals(new byte[] {
0x00 // Pushed data
}, builder.build().program());
}
@Test
public void numberBuilderPositiveOpCode() {
final ScriptBuilder builder = new ScriptBuilder();
builder.number(5);
assertArrayEquals(new byte[] {
0x55 // Pushed data
}, builder.build().program());
}
@Test
public void numberBuilderBigNum() {
ScriptBuilder builder = new ScriptBuilder();
// 21066 should take up three bytes including the length byte
// at the start
builder.number(0x524a);
assertArrayEquals(new byte[] {
0x02, // Length of the pushed data
0x4a, 0x52 // Pushed data
}, builder.build().program());
// Test the trimming code ignores zeroes in the middle
builder = new ScriptBuilder();
builder.number(0x110011);
assertEquals(4, builder.build().program().length);
// Check encoding of a value where signed/unsigned encoding differs
// because the most significant byte is 0x80, and therefore a
// sign byte has to be added to the end for the signed encoding.
builder = new ScriptBuilder();
builder.number(0x8000);
assertArrayEquals(new byte[] {
0x03, // Length of the pushed data
0x00, (byte) 0x80, 0x00 // Pushed data
}, builder.build().program());
}
@Test
public void numberBuilderNegative() {
// Check encoding of a negative value
final ScriptBuilder builder = new ScriptBuilder();
builder.number(-5);
assertArrayEquals(new byte[] {
0x01, // Length of the pushed data
((byte) 133) // Pushed data
}, builder.build().program());
}
@Test
public void numberBuilder16() {
ScriptBuilder builder = new ScriptBuilder();
// Numbers greater than 16 must be encoded with PUSHDATA
builder.number(15).number(16).number(17);
builder.number(0, 17).number(1, 16).number(2, 15);
Script script = builder.build();
assertEquals("PUSHDATA(1)[11] 16 15 15 16 PUSHDATA(1)[11]", script.toString());
}
@Test
public void testOpTrue() {
byte[] expected = new byte[] { OP_TRUE };
byte[] s = new ScriptBuilder().opTrue().build().program();
assertArrayEquals(expected, s);
}
@Test
public void testOpFalse() {
byte[] expected = new byte[] { OP_FALSE };
byte[] s = new ScriptBuilder().opFalse().build().program();
assertArrayEquals(expected, s);
}
}
| 4,166
| 32.604839
| 87
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/script/ScriptPatternTest.java
|
/*
* Copyright 2017 John L. Jegutanis
* Copyright 2018 Andreas Schildbach
* Copyright 2019 Tim Strasser
*
* 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.
*/
package org.bitcoinj.script;
import com.google.common.collect.Lists;
import org.bitcoinj.base.internal.ByteUtils;
import org.bitcoinj.crypto.DumpedPrivateKey;
import org.bitcoinj.crypto.ECKey;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.bitcoinj.base.BitcoinNetwork.MAINNET;
import static org.bitcoinj.script.ScriptOpCodes.OP_CHECKMULTISIG;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ScriptPatternTest {
private List<ECKey> keys = Lists.newArrayList(new ECKey(), new ECKey(), new ECKey());
@Test
public void testCreateP2PKHOutputScript() {
assertTrue(ScriptPattern.isP2PKH(
ScriptBuilder.createP2PKHOutputScript(keys.get(0))
));
}
@Test
public void testCreateP2SHOutputScript() {
assertTrue(ScriptPattern.isP2SH(
ScriptBuilder.createP2SHOutputScript(2, keys)
));
}
@Test
public void testCreateP2PKOutputScript() {
assertTrue(ScriptPattern.isP2PK(
ScriptBuilder.createP2PKOutputScript(keys.get(0))
));
}
@Test
public void testCreateP2WPKHOutputScript() {
assertTrue(ScriptPattern.isP2WPKH(
ScriptBuilder.createP2WPKHOutputScript(keys.get(0))
));
}
@Test
public void testCreateP2WSHOutputScript() {
assertTrue(ScriptPattern.isP2WSH(
ScriptBuilder.createP2WSHOutputScript(new ScriptBuilder().build())
));
}
@Test
public void testCreateMultiSigOutputScript() {
assertTrue(ScriptPattern.isSentToMultisig(
ScriptBuilder.createMultiSigOutputScript(2, keys)
));
}
@Test
public void testIsSentToMultisigFailure() {
// at the time this test was written, the following script would result in throwing
// put a non OP_N opcode first and second-to-last positions
Script evil = new ScriptBuilder()
.op(0xff)
.op(0xff)
.op(0xff)
.op(OP_CHECKMULTISIG)
.build();
assertFalse(ScriptPattern.isSentToMultisig(evil));
}
@Test
public void testCreateOpReturnScript() {
assertTrue(ScriptPattern.isOpReturn(
ScriptBuilder.createOpReturnScript(new byte[10])
));
}
@Test
public void p2shScriptHashFromKeys() {
// import some keys from this example: https://gist.github.com/gavinandresen/3966071
ECKey key1 = DumpedPrivateKey.fromBase58(MAINNET, "5JaTXbAUmfPYZFRwrYaALK48fN6sFJp4rHqq2QSXs8ucfpE4yQU").getKey();
key1 = ECKey.fromPrivate(key1.getPrivKeyBytes());
ECKey key2 = DumpedPrivateKey.fromBase58(MAINNET, "5Jb7fCeh1Wtm4yBBg3q3XbT6B525i17kVhy3vMC9AqfR6FH2qGk").getKey();
key2 = ECKey.fromPrivate(key2.getPrivKeyBytes());
ECKey key3 = DumpedPrivateKey.fromBase58(MAINNET, "5JFjmGo5Fww9p8gvx48qBYDJNAzR9pmH5S389axMtDyPT8ddqmw").getKey();
key3 = ECKey.fromPrivate(key3.getPrivKeyBytes());
List<ECKey> keys = Arrays.asList(key1, key2, key3);
Script p2shScript = ScriptBuilder.createP2SHOutputScript(2, keys);
byte[] p2shScriptHash = ScriptPattern.extractHashFromP2SH(p2shScript);
assertEquals("defdb71910720a2c854529019189228b4245eddd", ByteUtils.formatHex(p2shScriptHash));
}
}
| 4,117
| 34.5
| 122
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/script/ScriptTest.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
* Copyright 2017 Thomas König
*
* 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.
*/
package org.bitcoinj.script;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.internal.ByteUtils;
import org.bitcoinj.base.Address;
import org.bitcoinj.base.Coin;
import org.bitcoinj.crypto.DumpedPrivateKey;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.base.LegacyAddress;
import org.bitcoinj.core.MessageSerializer;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.ProtocolException;
import org.bitcoinj.base.SegwitAddress;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.Transaction.SigHash;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutPoint;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.core.VerificationException;
import org.bitcoinj.crypto.TransactionSignature;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.script.Script.VerifyFlag;
import org.hamcrest.core.IsNot;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.bitcoinj.core.Transaction.SERIALIZE_TRANSACTION_NO_WITNESS;
import static org.bitcoinj.script.ScriptOpCodes.OP_0;
import static org.bitcoinj.script.ScriptOpCodes.OP_INVALIDOPCODE;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class ScriptTest {
// From tx 05e04c26c12fe408a3c1b71aa7996403f6acad1045252b1c62e055496f4d2cb1 on the testnet.
private static final String sigProg = "47304402202b4da291cc39faf8433911988f9f49fc5c995812ca2f94db61468839c228c3e90220628bff3ff32ec95825092fa051cba28558a981fcf59ce184b14f2e215e69106701410414b38f4be3bb9fa0f4f32b74af07152b2f2f630bc02122a491137b6c523e46f18a0d5034418966f93dfc37cc3739ef7b2007213a302b7fba161557f4ad644a1c";
private static final String pubkeyProg = "76a91433e81a941e64cda12c6a299ed322ddbdd03f8d0e88ac";
private static final NetworkParameters TESTNET = TestNet3Params.get();
private static final NetworkParameters MAINNET = MainNetParams.get();
private static final Logger log = LoggerFactory.getLogger(ScriptTest.class);
@Test
public void testScriptSig() {
byte[] sigProgBytes = ByteUtils.parseHex(sigProg);
Script script = Script.parse(sigProgBytes);
assertEquals(
"PUSHDATA(71)[304402202b4da291cc39faf8433911988f9f49fc5c995812ca2f94db61468839c228c3e90220628bff3ff32ec95825092fa051cba28558a981fcf59ce184b14f2e215e69106701] PUSHDATA(65)[0414b38f4be3bb9fa0f4f32b74af07152b2f2f630bc02122a491137b6c523e46f18a0d5034418966f93dfc37cc3739ef7b2007213a302b7fba161557f4ad644a1c]",
script.toString());
}
@Test
public void testScriptPubKey() {
// Check we can extract the to address
byte[] pubkeyBytes = ByteUtils.parseHex(pubkeyProg);
Script pubkey = Script.parse(pubkeyBytes);
assertEquals("DUP HASH160 PUSHDATA(20)[33e81a941e64cda12c6a299ed322ddbdd03f8d0e] EQUALVERIFY CHECKSIG", pubkey.toString());
Address toAddr = LegacyAddress.fromPubKeyHash(BitcoinNetwork.TESTNET, ScriptPattern.extractHashFromP2PKH(pubkey));
assertEquals("mkFQohBpy2HDXrCwyMrYL5RtfrmeiuuPY2", toAddr.toString());
}
@Test
public void testMultiSig() {
List<ECKey> keys = Lists.newArrayList(new ECKey(), new ECKey(), new ECKey());
assertTrue(ScriptPattern.isSentToMultisig(ScriptBuilder.createMultiSigOutputScript(2, keys)));
Script script = ScriptBuilder.createMultiSigOutputScript(3, keys);
assertTrue(ScriptPattern.isSentToMultisig(script));
List<ECKey> pubkeys = new ArrayList<>(3);
for (ECKey key : keys) pubkeys.add(ECKey.fromPublicOnly(key));
assertEquals(script.getPubKeys(), pubkeys);
assertFalse(ScriptPattern.isSentToMultisig(ScriptBuilder.createP2PKOutputScript(new ECKey())));
try {
// Fail if we ask for more signatures than keys.
Script.createMultiSigOutputScript(4, keys);
fail();
} catch (Throwable e) {
// Expected.
}
try {
// Must have at least one signature required.
Script.createMultiSigOutputScript(0, keys);
} catch (Throwable e) {
// Expected.
}
// Actual execution is tested by the data driven tests.
}
@Test
public void testP2SHOutputScript() {
Address p2shAddress = LegacyAddress.fromBase58("35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU", BitcoinNetwork.MAINNET);
assertTrue(ScriptPattern.isP2SH(ScriptBuilder.createOutputScript(p2shAddress)));
}
@Test
public void testIp() {
byte[] bytes = ByteUtils.parseHex("41043e96222332ea7848323c08116dddafbfa917b8e37f0bdf63841628267148588a09a43540942d58d49717ad3fabfe14978cf4f0a8b84d2435dad16e9aa4d7f935ac");
Script s = Script.parse(bytes);
assertTrue(ScriptPattern.isP2PK(s));
}
@Test
public void testCreateMultiSigInputScript() {
// Setup transaction and signatures
ECKey key1 = DumpedPrivateKey.fromBase58(BitcoinNetwork.TESTNET, "cVLwRLTvz3BxDAWkvS3yzT9pUcTCup7kQnfT2smRjvmmm1wAP6QT").getKey();
ECKey key2 = DumpedPrivateKey.fromBase58(BitcoinNetwork.TESTNET, "cTine92s8GLpVqvebi8rYce3FrUYq78ZGQffBYCS1HmDPJdSTxUo").getKey();
ECKey key3 = DumpedPrivateKey.fromBase58(BitcoinNetwork.TESTNET, "cVHwXSPRZmL9adctwBwmn4oTZdZMbaCsR5XF6VznqMgcvt1FDDxg").getKey();
Script multisigScript = ScriptBuilder.createMultiSigOutputScript(2, Arrays.asList(key1, key2, key3));
byte[] bytes = ByteUtils.parseHex("01000000013df681ff83b43b6585fa32dd0e12b0b502e6481e04ee52ff0fdaf55a16a4ef61000000006b483045022100a84acca7906c13c5895a1314c165d33621cdcf8696145080895cbf301119b7cf0220730ff511106aa0e0a8570ff00ee57d7a6f24e30f592a10cae1deffac9e13b990012102b8d567bcd6328fd48a429f9cf4b315b859a58fd28c5088ef3cb1d98125fc4e8dffffffff02364f1c00000000001976a91439a02793b418de8ec748dd75382656453dc99bcb88ac40420f000000000017a9145780b80be32e117f675d6e0ada13ba799bf248e98700000000");
Transaction transaction = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(bytes));
TransactionOutput output = transaction.getOutput(1);
Transaction spendTx = new Transaction();
Address address = LegacyAddress.fromBase58("n3CFiCmBXVt5d3HXKQ15EFZyhPz4yj5F3H", BitcoinNetwork.TESTNET);
Script outputScript = ScriptBuilder.createOutputScript(address);
spendTx.addOutput(output.getValue(), outputScript);
spendTx.addInput(output);
Sha256Hash sighash = spendTx.hashForSignature(0, multisigScript, SigHash.ALL, false);
ECKey.ECDSASignature party1Signature = key1.sign(sighash);
ECKey.ECDSASignature party2Signature = key2.sign(sighash);
TransactionSignature party1TransactionSignature = new TransactionSignature(party1Signature, SigHash.ALL, false);
TransactionSignature party2TransactionSignature = new TransactionSignature(party2Signature, SigHash.ALL, false);
// Create p2sh multisig input script
Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(Arrays.asList(party1TransactionSignature, party2TransactionSignature), multisigScript);
// Assert that the input script contains 4 chunks
assertTrue(inputScript.chunks().size() == 4);
// Assert that the input script created contains the original multisig
// script as the last chunk
ScriptChunk scriptChunk = inputScript.chunks().get(inputScript.chunks().size() - 1);
assertArrayEquals(scriptChunk.data, multisigScript.program());
// Create regular multisig input script
inputScript = ScriptBuilder.createMultiSigInputScript(Arrays.asList(party1TransactionSignature, party2TransactionSignature));
// Assert that the input script only contains 3 chunks
assertTrue(inputScript.chunks().size() == 3);
// Assert that the input script created does not end with the original
// multisig script
scriptChunk = inputScript.chunks().get(inputScript.chunks().size() - 1);
assertThat(scriptChunk.data, IsNot.not(equalTo(multisigScript.program())));
}
@Test
public void createAndUpdateEmptyInputScript() {
TransactionSignature dummySig = TransactionSignature.dummy();
ECKey key = new ECKey();
// P2PK
Script inputScript = ScriptBuilder.createInputScript(dummySig);
assertThat(inputScript.chunks().get(0).data, equalTo(dummySig.encodeToBitcoin()));
inputScript = ScriptBuilder.createInputScript(null);
assertThat(inputScript.chunks().get(0).opcode, equalTo(OP_0));
// P2PKH
inputScript = ScriptBuilder.createInputScript(dummySig, key);
assertThat(inputScript.chunks().get(0).data, equalTo(dummySig.encodeToBitcoin()));
inputScript = ScriptBuilder.createInputScript(null, key);
assertThat(inputScript.chunks().get(0).opcode, equalTo(OP_0));
assertThat(inputScript.chunks().get(1).data, equalTo(key.getPubKey()));
// P2SH
ECKey key2 = new ECKey();
Script multisigScript = ScriptBuilder.createMultiSigOutputScript(2, Arrays.asList(key, key2));
inputScript = ScriptBuilder.createP2SHMultiSigInputScript(Arrays.asList(dummySig, dummySig), multisigScript);
assertThat(inputScript.chunks().get(0).opcode, equalTo(OP_0));
assertThat(inputScript.chunks().get(1).data, equalTo(dummySig.encodeToBitcoin()));
assertThat(inputScript.chunks().get(2).data, equalTo(dummySig.encodeToBitcoin()));
assertThat(inputScript.chunks().get(3).data, equalTo(multisigScript.program()));
inputScript = ScriptBuilder.createP2SHMultiSigInputScript(null, multisigScript);
assertThat(inputScript.chunks().get(0).opcode, equalTo(OP_0));
assertThat(inputScript.chunks().get(1).opcode, equalTo(OP_0));
assertThat(inputScript.chunks().get(2).opcode, equalTo(OP_0));
assertThat(inputScript.chunks().get(3).data, equalTo(multisigScript.program()));
inputScript = ScriptBuilder.updateScriptWithSignature(inputScript, dummySig.encodeToBitcoin(), 0, 1, 1);
assertThat(inputScript.chunks().get(0).opcode, equalTo(OP_0));
assertThat(inputScript.chunks().get(1).data, equalTo(dummySig.encodeToBitcoin()));
assertThat(inputScript.chunks().get(2).opcode, equalTo(OP_0));
assertThat(inputScript.chunks().get(3).data, equalTo(multisigScript.program()));
inputScript = ScriptBuilder.updateScriptWithSignature(inputScript, dummySig.encodeToBitcoin(), 1, 1, 1);
assertThat(inputScript.chunks().get(0).opcode, equalTo(OP_0));
assertThat(inputScript.chunks().get(1).data, equalTo(dummySig.encodeToBitcoin()));
assertThat(inputScript.chunks().get(2).data, equalTo(dummySig.encodeToBitcoin()));
assertThat(inputScript.chunks().get(3).data, equalTo(multisigScript.program()));
// updating scriptSig with no missing signatures
try {
ScriptBuilder.updateScriptWithSignature(inputScript, dummySig.encodeToBitcoin(), 1, 1, 1);
fail("Exception expected");
} catch (Exception e) {
assertEquals(IllegalArgumentException.class, e.getClass());
}
}
@Test
public void testOp0() {
// Check that OP_0 doesn't NPE and pushes an empty stack frame.
Transaction tx = new Transaction();
tx.addInput(new TransactionInput(tx, new byte[0], TransactionOutPoint.UNCONNECTED));
Script script = new ScriptBuilder().smallNum(0).build();
LinkedList<byte[]> stack = new LinkedList<>();
Script.executeScript(tx, 0, script, stack, Script.ALL_VERIFY_FLAGS);
assertEquals("OP_0 push length", 0, stack.get(0).length);
}
private Script parseScriptString(String string) throws IOException {
String[] words = string.split("[ \\t\\n]");
ByteArrayOutputStream out = new ByteArrayOutputStream();
for(String w : words) {
if (w.equals(""))
continue;
if (w.matches("^-?[0-9]*$")) {
// Number
long val = Long.parseLong(w);
if (val >= -1 && val <= 16)
out.write(Script.encodeToOpN((int)val));
else
Script.writeBytes(out, ByteUtils.reverseBytes(ByteUtils.encodeMPI(BigInteger.valueOf(val), false)));
} else if (w.matches("^0x[0-9a-fA-F]*$")) {
// Raw hex data, inserted NOT pushed onto stack:
out.write(ByteUtils.parseHex(w.substring(2).toLowerCase()));
} else if (w.length() >= 2 && w.startsWith("'") && w.endsWith("'")) {
// Single-quoted string, pushed as data. NOTE: this is poor-man's
// parsing, spaces/tabs/newlines in single-quoted strings won't work.
Script.writeBytes(out, w.substring(1, w.length() - 1).getBytes(StandardCharsets.UTF_8));
} else if (ScriptOpCodes.getOpCode(w) != OP_INVALIDOPCODE) {
// opcode, e.g. OP_ADD or OP_1:
out.write(ScriptOpCodes.getOpCode(w));
} else if (w.startsWith("OP_") && ScriptOpCodes.getOpCode(w.substring(3)) != OP_INVALIDOPCODE) {
// opcode, e.g. OP_ADD or OP_1:
out.write(ScriptOpCodes.getOpCode(w.substring(3)));
} else {
throw new RuntimeException("Invalid word: '" + w + "'");
}
}
return Script.parse(out.toByteArray());
}
private Set<VerifyFlag> parseVerifyFlags(String str) {
Set<VerifyFlag> flags = EnumSet.noneOf(VerifyFlag.class);
if (!"NONE".equals(str)) {
for (String flag : str.split(",")) {
try {
flags.add(VerifyFlag.valueOf(flag));
} catch (IllegalArgumentException x) {
log.debug("Cannot handle verify flag {} -- ignored.", flag);
}
}
}
return flags;
}
@Test
public void dataDrivenScripts() throws Exception {
JsonNode json = new ObjectMapper()
.readTree(new InputStreamReader(getClass().getResourceAsStream("script_tests.json"), StandardCharsets.UTF_8));
for (JsonNode test : json) {
if (test.size() == 1)
continue; // skip comment
Set<VerifyFlag> verifyFlags = parseVerifyFlags(test.get(2).asText());
ScriptError expectedError = ScriptError.fromMnemonic(test.get(3).asText());
try {
Script scriptSig = parseScriptString(test.get(0).asText());
Script scriptPubKey = parseScriptString(test.get(1).asText());
Transaction txCredit = buildCreditingTransaction(scriptPubKey);
Transaction txSpend = buildSpendingTransaction(txCredit, scriptSig);
scriptSig.correctlySpends(txSpend, 0, null, null, scriptPubKey, verifyFlags);
if (!expectedError.equals(ScriptError.SCRIPT_ERR_OK))
fail(test + " is expected to fail");
} catch (ScriptException e) {
if (!e.getError().equals(expectedError)) {
System.err.println(test);
e.printStackTrace();
System.err.flush();
throw e;
}
}
}
}
private Map<TransactionOutPoint, Script> parseScriptPubKeys(JsonNode inputs) throws IOException {
Map<TransactionOutPoint, Script> scriptPubKeys = new HashMap<>();
for (JsonNode input : inputs) {
String hash = input.get(0).asText();
long index = input.get(1).asLong();
if (index == -1)
index = ByteUtils.MAX_UNSIGNED_INTEGER;
String script = input.get(2).asText();
Sha256Hash sha256Hash = Sha256Hash.wrap(ByteUtils.parseHex(hash));
scriptPubKeys.put(new TransactionOutPoint(index, sha256Hash), parseScriptString(script));
}
return scriptPubKeys;
}
private Transaction buildCreditingTransaction(Script scriptPubKey) {
Transaction tx = new Transaction();
tx.setVersion(1);
tx.setLockTime(0);
TransactionInput txInput = new TransactionInput(null,
new ScriptBuilder().number(0).number(0).build().program(), TransactionOutPoint.UNCONNECTED);
txInput.setSequenceNumber(TransactionInput.NO_SEQUENCE);
tx.addInput(txInput);
TransactionOutput txOutput = new TransactionOutput(tx, Coin.ZERO, scriptPubKey.program());
tx.addOutput(txOutput);
return tx;
}
private Transaction buildSpendingTransaction(Transaction creditingTransaction, Script scriptSig) {
Transaction tx = new Transaction();
tx.setVersion(1);
tx.setLockTime(0);
TransactionInput txInput = new TransactionInput(creditingTransaction, scriptSig.program(),
TransactionOutPoint.UNCONNECTED);
txInput.setSequenceNumber(TransactionInput.NO_SEQUENCE);
tx.addInput(txInput);
TransactionOutput txOutput = new TransactionOutput(tx, creditingTransaction.getOutput(0).getValue(),
Script.parse(new byte[] {}).program());
tx.addOutput(txOutput);
return tx;
}
@Test
public void dataDrivenValidTransactions() throws Exception {
JsonNode json = new ObjectMapper().readTree(new InputStreamReader(getClass().getResourceAsStream(
"tx_valid.json"), StandardCharsets.UTF_8));
for (JsonNode test : json) {
if (test.isArray() && test.size() == 1 && test.get(0).isTextual())
continue; // This is a comment.
Transaction transaction = null;
try {
Map<TransactionOutPoint, Script> scriptPubKeys = parseScriptPubKeys(test.get(0));
transaction = TESTNET.getDefaultSerializer().makeTransaction(ByteBuffer.wrap(ByteUtils.parseHex(test.get(1).asText().toLowerCase())));
Transaction.verify(TESTNET.network(), transaction);
Set<VerifyFlag> verifyFlags = parseVerifyFlags(test.get(2).asText());
for (int i = 0; i < transaction.getInputs().size(); i++) {
TransactionInput input = transaction.getInput(i);
assertTrue(scriptPubKeys.containsKey(input.getOutpoint()));
input.getScriptSig().correctlySpends(transaction, i, null, null,
scriptPubKeys.get(input.getOutpoint()), verifyFlags);
}
} catch (Exception e) {
System.err.println(test);
if (transaction != null)
System.err.println(transaction);
throw e;
}
}
}
@Test
public void dataDrivenInvalidTransactions() throws Exception {
JsonNode json = new ObjectMapper().readTree(new InputStreamReader(getClass().getResourceAsStream(
"tx_invalid.json"), StandardCharsets.UTF_8));
for (JsonNode test : json) {
if (test.isArray() && test.size() == 1 && test.get(0).isTextual())
continue; // This is a comment.
Map<TransactionOutPoint, Script> scriptPubKeys = parseScriptPubKeys(test.get(0));
byte[] txBytes = ByteUtils.parseHex(test.get(1).asText().toLowerCase());
MessageSerializer serializer = TESTNET.getDefaultSerializer();
Transaction transaction;
try {
transaction = serializer.makeTransaction(ByteBuffer.wrap(txBytes));
} catch (ProtocolException ignore) {
// Try to parse as a no-witness transaction because some vectors are 0-input, 1-output txs that fail
// to correctly parse as witness transactions.
int protoVersionNoWitness = serializer.getProtocolVersion() | SERIALIZE_TRANSACTION_NO_WITNESS;
transaction = serializer.withProtocolVersion(protoVersionNoWitness).makeTransaction(ByteBuffer.wrap(txBytes));
}
Set<VerifyFlag> verifyFlags = parseVerifyFlags(test.get(2).asText());
boolean valid = true;
try {
Transaction.verify(TESTNET.network(), transaction);
} catch (VerificationException e) {
valid = false;
}
// Bitcoin Core checks this case in CheckTransaction, but we leave it to
// later where we will see an attempt to double-spend, so we explicitly check here
HashSet<TransactionOutPoint> set = new HashSet<>();
for (TransactionInput input : transaction.getInputs()) {
if (set.contains(input.getOutpoint()))
valid = false;
set.add(input.getOutpoint());
}
for (int i = 0; i < transaction.getInputs().size() && valid; i++) {
TransactionInput input = transaction.getInput(i);
assertTrue(scriptPubKeys.containsKey(input.getOutpoint()));
try {
input.getScriptSig().correctlySpends(transaction, i, null, null,
scriptPubKeys.get(input.getOutpoint()), verifyFlags);
} catch (VerificationException e) {
valid = false;
}
}
if (valid) {
System.out.println(test);
fail();
}
}
}
@Test
public void getToAddress() {
// P2PK
ECKey toKey = new ECKey();
Address toAddress = toKey.toAddress(ScriptType.P2PKH, BitcoinNetwork.TESTNET);
assertEquals(toAddress, ScriptBuilder.createP2PKOutputScript(toKey).getToAddress(BitcoinNetwork.TESTNET, true));
// pay to pubkey hash
assertEquals(toAddress, ScriptBuilder.createOutputScript(toAddress).getToAddress(BitcoinNetwork.TESTNET));
// pay to script hash
Script p2shScript = ScriptBuilder.createP2SHOutputScript(new byte[20]);
Address scriptAddress = LegacyAddress.fromScriptHash(BitcoinNetwork.TESTNET,
ScriptPattern.extractHashFromP2SH(p2shScript));
assertEquals(scriptAddress, p2shScript.getToAddress(BitcoinNetwork.TESTNET));
// P2WPKH
toAddress = toKey.toAddress(ScriptType.P2WPKH, BitcoinNetwork.TESTNET);
assertEquals(toAddress, ScriptBuilder.createOutputScript(toAddress).getToAddress(BitcoinNetwork.TESTNET));
// P2WSH
Script p2wshScript = ScriptBuilder.createP2WSHOutputScript(new byte[32]);
scriptAddress = SegwitAddress.fromHash(BitcoinNetwork.TESTNET, ScriptPattern.extractHashFromP2WH(p2wshScript));
assertEquals(scriptAddress, p2wshScript.getToAddress(BitcoinNetwork.TESTNET));
// P2TR
toAddress = SegwitAddress.fromProgram(BitcoinNetwork.TESTNET, 1, new byte[32]);
assertEquals(toAddress, ScriptBuilder.createOutputScript(toAddress).getToAddress(BitcoinNetwork.TESTNET));
}
@Test(expected = ScriptException.class)
public void getToAddressNoPubKey() {
ScriptBuilder.createP2PKOutputScript(new ECKey()).getToAddress(BitcoinNetwork.TESTNET, false);
}
}
| 24,896
| 48.993976
| 494
|
java
|
bitcoinj
|
bitcoinj-master/core/src/test/java/org/bitcoinj/script/ScriptChunkTest.java
|
/*
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.script;
import com.google.common.primitives.Bytes;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.Test;
import java.util.Random;
import static org.bitcoinj.script.ScriptOpCodes.OP_0;
import static org.bitcoinj.script.ScriptOpCodes.OP_IF;
import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA1;
import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA2;
import static org.bitcoinj.script.ScriptOpCodes.OP_PUSHDATA4;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ScriptChunkTest {
private static final Random RANDOM = new Random(42);
@Test
public void equalsContract() {
EqualsVerifier.forClass(ScriptChunk.class)
.usingGetClass()
.verify();
}
@Test
public void testToStringOnInvalidScriptChunk() {
// see https://github.com/bitcoinj/bitcoinj/issues/1860
// In summary: toString() throws when given an invalid ScriptChunk.
// It should perhaps be impossible to even construct such a ScriptChunk, but
// until that is the case, toString() should not throw.
ScriptChunk pushWithoutData = new ScriptChunk(OP_PUSHDATA1, null);
// the chunk is invalid, but at least we can determine its opcode
assertEquals("PUSHDATA1", pushWithoutData.toString());
}
@Test
public void testShortestPossibleDataPush() {
assertTrue("empty push", new ScriptBuilder().data(new byte[0]).build().chunks().get(0)
.isShortestPossiblePushData());
for (byte i = -1; i < 127; i++)
assertTrue("push of single byte " + i, new ScriptBuilder().data(new byte[] { i }).build().chunks()
.get(0).isShortestPossiblePushData());
for (int len = 2; len < Script.MAX_SCRIPT_ELEMENT_SIZE; len++)
assertTrue("push of " + len + " bytes", new ScriptBuilder().data(new byte[len]).build().chunks().get(0)
.isShortestPossiblePushData());
// non-standard chunks
for (byte i = 1; i <= 16; i++)
assertFalse("push of smallnum " + i, new ScriptChunk(1, new byte[] { i }).isShortestPossiblePushData());
assertFalse("push of 75 bytes", new ScriptChunk(OP_PUSHDATA1, new byte[75]).isShortestPossiblePushData());
assertFalse("push of 255 bytes", new ScriptChunk(OP_PUSHDATA2, new byte[255]).isShortestPossiblePushData());
assertFalse("push of 65535 bytes", new ScriptChunk(OP_PUSHDATA4, new byte[65535]).isShortestPossiblePushData());
}
@Test
public void testToByteArray_opcode() {
byte[] expected = new byte[] { OP_IF };
byte[] actual = new ScriptChunk(OP_IF, null).toByteArray();
assertArrayEquals(expected, actual);
}
@Test
public void testToByteArray_smallNum() {
byte[] expected = new byte[] { OP_0 };
byte[] actual = new ScriptChunk(OP_0, null).toByteArray();
assertArrayEquals(expected, actual);
}
@Test
public void testToByteArray_lt_OP_PUSHDATA1() {
// < OP_PUSHDATA1
for (byte len = 1; len < OP_PUSHDATA1; len++) {
byte[] bytes = new byte[len];
RANDOM.nextBytes(bytes);
byte[] expected = Bytes.concat(new byte[] { len }, bytes);
byte[] actual = new ScriptChunk(len, bytes).toByteArray();
assertArrayEquals(expected, actual);
}
}
@Test
public void testToByteArray_OP_PUSHDATA1() {
// OP_PUSHDATA1
byte[] bytes = new byte[0xFF];
RANDOM.nextBytes(bytes);
byte[] expected = Bytes.concat(new byte[] { OP_PUSHDATA1, (byte) 0xFF }, bytes);
byte[] actual = new ScriptChunk(OP_PUSHDATA1, bytes).toByteArray();
assertArrayEquals(expected, actual);
}
@Test
public void testToByteArray_OP_PUSHDATA2() {
// OP_PUSHDATA2
byte[] bytes = new byte[0x0102];
RANDOM.nextBytes(bytes);
byte[] expected = Bytes.concat(new byte[] { OP_PUSHDATA2, 0x02, 0x01 }, bytes);
byte[] actual = new ScriptChunk(OP_PUSHDATA2, bytes).toByteArray();
assertArrayEquals(expected, actual);
}
@Test
public void testToByteArray_OP_PUSHDATA4() {
// OP_PUSHDATA4
byte[] bytes = new byte[0x0102];
RANDOM.nextBytes(bytes);
byte[] expected = Bytes.concat(new byte[] { OP_PUSHDATA4, 0x02, 0x01, 0x00, 0x00 }, bytes);
byte[] actual = new ScriptChunk(OP_PUSHDATA4, bytes).toByteArray();
assertArrayEquals(expected, actual);
}
}
| 5,279
| 38.111111
| 120
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoin/NativeSecp256k1Util.java
|
/*
* Copyright 2014-2016 the libsecp256k1 contributors
*
* 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.
*/
package org.bitcoin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Assertion utilities for {@link NativeSecp256k1}
* @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2267
*/
@Deprecated
public class NativeSecp256k1Util {
private static final Logger log = LoggerFactory.getLogger(NativeSecp256k1Util.class);
/**
* Compare two integers and throw {@link AssertFailException} if not equal
*
* @param val first int
* @param val2 second int
* @param message failure error message
* @throws AssertFailException when ints are not equal
*/
public static void assertEquals(int val, int val2, String message) throws AssertFailException {
if (val != val2)
throw new AssertFailException("FAIL: " + message);
}
/**
* Compare two booleans and throw {@link AssertFailException} if not equal
*
* @param val first boolean
* @param val2 second boolean
* @param message failure error message
* @throws AssertFailException when booleans are not equal
*/
public static void assertEquals(boolean val, boolean val2, String message) throws AssertFailException {
if (val != val2)
throw new AssertFailException("FAIL: " + message);
else
log.debug("PASS: " + message);
}
/**
* Compare two Strings and throw {@link AssertFailException} if not equal
*
* @param val first String
* @param val2 second String
* @param message failure error message
* @throws AssertFailException when Strings are not equal
*/
public static void assertEquals(String val, String val2, String message) throws AssertFailException {
if (!val.equals(val2))
throw new AssertFailException("FAIL: " + message);
else
log.debug("PASS: " + message);
}
/**
* Assertion failure exception
*/
public static class AssertFailException extends Exception {
/**
* @param message The failure message
*/
public AssertFailException(String message) {
super(message);
}
}
}
| 2,774
| 31.267442
| 107
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoin/Secp256k1Context.java
|
/*
* Copyright 2014-2016 the libsecp256k1 contributors
*
* 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.
*/
package org.bitcoin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class holds the context reference used in native methods to handle ECDSA operations.
* @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2267
*/
@Deprecated
public class Secp256k1Context {
private static final boolean enabled; // true if the library is loaded
private static final long context; // ref to pointer to context obj
private static final Logger log = LoggerFactory.getLogger(Secp256k1Context.class);
static { // static initializer
boolean isEnabled = true;
long contextRef = -1;
try {
System.loadLibrary("secp256k1");
contextRef = secp256k1_init_context();
} catch (UnsatisfiedLinkError | SecurityException e) {
log.debug(e.toString());
isEnabled = false;
}
enabled = isEnabled;
context = contextRef;
}
/**
* @return true if enabled
*/
public static boolean isEnabled() {
return enabled;
}
/**
* @return context reference
*/
public static long getContext() {
if (!enabled)
return -1; // sanity check
return context;
}
private static native long secp256k1_init_context();
}
| 1,920
| 28.106061
| 92
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoin/NativeSecp256k1.java
|
/*
* Copyright 2013 Google Inc.
* Copyright 2014-2016 the libsecp256k1 contributors
*
* 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.
*/
package org.bitcoin;
import java.math.BigInteger;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static org.bitcoin.NativeSecp256k1Util.AssertFailException;
import static org.bitcoin.NativeSecp256k1Util.assertEquals;
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
/**
* <p>This class holds native methods to handle ECDSA verification.</p>
*
* <p>You can find an example library that can be used for this at https://github.com/bitcoin/secp256k1</p>
*
* <p>To build secp256k1 for use with bitcoinj, run
* `./configure --enable-jni --enable-experimental --enable-module-schnorr --enable-module-ecdh`
* and `make` then copy `.libs/libsecp256k1.so` to your system library path
* or point the JVM to the folder containing it with -Djava.library.path
* </p>
* @deprecated See https://github.com/bitcoinj/bitcoinj/issues/2267
*/
@Deprecated
public class NativeSecp256k1 {
private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private static final Lock r = rwl.readLock();
private static final Lock w = rwl.writeLock();
private static ThreadLocal<ByteBuffer> nativeECDSABuffer = new ThreadLocal<>();
/**
* Verifies the given secp256k1 signature in native code. Calling when enabled == false is undefined (probably
* library not loaded)
*
* @param data The data which was signed, must be exactly 32 bytes
* @param signature The signature
* @param pub The public key which did the signing
* @return true if correct signature
* @throws AssertFailException never thrown?
*/
public static boolean verify(byte[] data, byte[] signature, byte[] pub) throws AssertFailException {
checkArgument(data.length == 32 && signature.length <= 520 && pub.length <= 520);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < 520) {
byteBuff = ByteBuffer.allocateDirect(520);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
((Buffer) byteBuff).rewind();
byteBuff.put(data);
byteBuff.put(signature);
byteBuff.put(pub);
r.lock();
try {
return secp256k1_ecdsa_verify(byteBuff, Secp256k1Context.getContext(), signature.length, pub.length) == 1;
} finally {
r.unlock();
}
}
/**
* libsecp256k1 Create an ECDSA signature.
*
* @param data Message hash, 32 bytes
* @param sec Secret key, 32 bytes
* @return sig byte array of signature
* @throws AssertFailException on bad signature length
*/
public static byte[] sign(byte[] data, byte[] sec) throws AssertFailException {
checkArgument(data.length == 32 && sec.length <= 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < 32 + 32) {
byteBuff = ByteBuffer.allocateDirect(32 + 32);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
((Buffer) byteBuff).rewind();
byteBuff.put(data);
byteBuff.put(sec);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_ecdsa_sign(byteBuff, Secp256k1Context.getContext());
} finally {
r.unlock();
}
byte[] sigArr = retByteArray[0];
int sigLen = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(sigArr.length, sigLen, "Got bad signature length.");
return retVal == 0 ? new byte[0] : sigArr;
}
/**
* libsecp256k1 Seckey Verify - returns 1 if valid, 0 if invalid
*
* @param seckey ECDSA Secret key, 32 bytes
* @return true if valid, false if invalid
*/
public static boolean secKeyVerify(byte[] seckey) {
checkArgument(seckey.length == 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < seckey.length) {
byteBuff = ByteBuffer.allocateDirect(seckey.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
((Buffer) byteBuff).rewind();
byteBuff.put(seckey);
r.lock();
try {
return secp256k1_ec_seckey_verify(byteBuff, Secp256k1Context.getContext()) == 1;
} finally {
r.unlock();
}
}
/**
* libsecp256k1 Compute Pubkey - computes public key from secret key
*
* @param seckey ECDSA Secret key, 32 bytes
* @return pubkey ECDSA Public key, 33 or 65 bytes
* @throws AssertFailException if bad pubkey length
*/
// TODO add a 'compressed' arg
public static byte[] computePubkey(byte[] seckey) throws AssertFailException {
checkArgument(seckey.length == 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < seckey.length) {
byteBuff = ByteBuffer.allocateDirect(seckey.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
((Buffer) byteBuff).rewind();
byteBuff.put(seckey);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_ec_pubkey_create(byteBuff, Secp256k1Context.getContext());
} finally {
r.unlock();
}
byte[] pubArr = retByteArray[0];
int pubLen = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");
return retVal == 0 ? new byte[0] : pubArr;
}
/**
* libsecp256k1 Cleanup - This destroys the secp256k1 context object This should be called at the end of the program
* for proper cleanup of the context.
*/
public static synchronized void cleanup() {
w.lock();
try {
secp256k1_destroy_context(Secp256k1Context.getContext());
} finally {
w.unlock();
}
}
/**
* Clone context
*
* @return context reference
*/
public static long cloneContext() {
r.lock();
try {
return secp256k1_ctx_clone(Secp256k1Context.getContext());
} finally {
r.unlock();
}
}
/**
* libsecp256k1 PrivKey Tweak-Mul - Tweak privkey by multiplying to it
*
* @param tweak some bytes to tweak with
* @param privkey 32-byte seckey
* @return The tweaked private key
* @throws AssertFailException assertion failure
*/
public static byte[] privKeyTweakMul(byte[] privkey, byte[] tweak) throws AssertFailException {
checkArgument(privkey.length == 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) {
byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
((Buffer) byteBuff).rewind();
byteBuff.put(privkey);
byteBuff.put(tweak);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_privkey_tweak_mul(byteBuff, Secp256k1Context.getContext());
} finally {
r.unlock();
}
byte[] privArr = retByteArray[0];
int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(privArr.length, privLen, "Got bad pubkey length.");
assertEquals(retVal, 1, "Failed return value check.");
return privArr;
}
/**
* libsecp256k1 PrivKey Tweak-Add - Tweak privkey by adding to it
*
* @param tweak some bytes to tweak with
* @param privkey 32-byte seckey
* @return The tweaked private key
* @throws AssertFailException assertion failure
*/
public static byte[] privKeyTweakAdd(byte[] privkey, byte[] tweak) throws AssertFailException {
checkArgument(privkey.length == 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) {
byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
((Buffer) byteBuff).rewind();
byteBuff.put(privkey);
byteBuff.put(tweak);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_privkey_tweak_add(byteBuff, Secp256k1Context.getContext());
} finally {
r.unlock();
}
byte[] privArr = retByteArray[0];
int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(privArr.length, privLen, "Got bad pubkey length.");
assertEquals(retVal, 1, "Failed return value check.");
return privArr;
}
/**
* libsecp256k1 PubKey Tweak-Add - Tweak pubkey by adding to it
*
* @param tweak some bytes to tweak with
* @param pubkey 32-byte seckey
* @return The tweaked private key
* @throws AssertFailException assertion failure
*/
public static byte[] pubKeyTweakAdd(byte[] pubkey, byte[] tweak) throws AssertFailException {
checkArgument(pubkey.length == 33 || pubkey.length == 65);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) {
byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
((Buffer) byteBuff).rewind();
byteBuff.put(pubkey);
byteBuff.put(tweak);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_pubkey_tweak_add(byteBuff, Secp256k1Context.getContext(), pubkey.length);
} finally {
r.unlock();
}
byte[] pubArr = retByteArray[0];
int pubLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");
assertEquals(retVal, 1, "Failed return value check.");
return pubArr;
}
/**
* libsecp256k1 PubKey Tweak-Mul - Tweak pubkey by multiplying to it
*
* @param tweak some bytes to tweak with
* @param pubkey 32-byte seckey
* @return The tweaked private key
* @throws AssertFailException assertion failure
*/
public static byte[] pubKeyTweakMul(byte[] pubkey, byte[] tweak) throws AssertFailException {
checkArgument(pubkey.length == 33 || pubkey.length == 65);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) {
byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
((Buffer) byteBuff).rewind();
byteBuff.put(pubkey);
byteBuff.put(tweak);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_pubkey_tweak_mul(byteBuff, Secp256k1Context.getContext(), pubkey.length);
} finally {
r.unlock();
}
byte[] pubArr = retByteArray[0];
int pubLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");
assertEquals(retVal, 1, "Failed return value check.");
return pubArr;
}
/**
* libsecp256k1 create ECDH secret - constant time ECDH calculation
*
* @param seckey byte array of secret key used in exponentiation
* @param pubkey byte array of public key used in exponentiation
* @return the secret
* @throws AssertFailException assertion failure
*/
public static byte[] createECDHSecret(byte[] seckey, byte[] pubkey) throws AssertFailException {
checkArgument(seckey.length <= 32 && pubkey.length <= 65);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < 32 + pubkey.length) {
byteBuff = ByteBuffer.allocateDirect(32 + pubkey.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
((Buffer) byteBuff).rewind();
byteBuff.put(seckey);
byteBuff.put(pubkey);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_ecdh(byteBuff, Secp256k1Context.getContext(), pubkey.length);
} finally {
r.unlock();
}
byte[] resArr = retByteArray[0];
int retVal = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();
assertEquals(resArr.length, 32, "Got bad result length.");
assertEquals(retVal, 1, "Failed return value check.");
return resArr;
}
/**
* libsecp256k1 randomize - updates the context randomization
*
* @param seed 32-byte random seed
* @return true if successful, false otherwise
* @throws AssertFailException never thrown?
*/
public static synchronized boolean randomize(byte[] seed) throws AssertFailException {
checkArgument(seed.length == 32 || seed == null);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < seed.length) {
byteBuff = ByteBuffer.allocateDirect(seed.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
((Buffer) byteBuff).rewind();
byteBuff.put(seed);
w.lock();
try {
return secp256k1_context_randomize(byteBuff, Secp256k1Context.getContext()) == 1;
} finally {
w.unlock();
}
}
/**
* @param data data to sign
* @param sec secret key
* @return Signature or byte[0]
* @throws AssertFailException assertion failure
*/
public static byte[] schnorrSign(byte[] data, byte[] sec) throws AssertFailException {
checkArgument(data.length == 32 && sec.length <= 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null) {
byteBuff = ByteBuffer.allocateDirect(32 + 32);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
((Buffer) byteBuff).rewind();
byteBuff.put(data);
byteBuff.put(sec);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_schnorr_sign(byteBuff, Secp256k1Context.getContext());
} finally {
r.unlock();
}
byte[] sigArr = retByteArray[0];
int retVal = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();
assertEquals(sigArr.length, 64, "Got bad signature length.");
return retVal == 0 ? new byte[0] : sigArr;
}
private static native long secp256k1_ctx_clone(long context);
private static native int secp256k1_context_randomize(ByteBuffer byteBuff, long context);
private static native byte[][] secp256k1_privkey_tweak_add(ByteBuffer byteBuff, long context);
private static native byte[][] secp256k1_privkey_tweak_mul(ByteBuffer byteBuff, long context);
private static native byte[][] secp256k1_pubkey_tweak_add(ByteBuffer byteBuff, long context, int pubLen);
private static native byte[][] secp256k1_pubkey_tweak_mul(ByteBuffer byteBuff, long context, int pubLen);
private static native void secp256k1_destroy_context(long context);
private static native int secp256k1_ecdsa_verify(ByteBuffer byteBuff, long context, int sigLen, int pubLen);
private static native byte[][] secp256k1_ecdsa_sign(ByteBuffer byteBuff, long context);
private static native int secp256k1_ec_seckey_verify(ByteBuffer byteBuff, long context);
private static native byte[][] secp256k1_ec_pubkey_create(ByteBuffer byteBuff, long context);
private static native byte[][] secp256k1_ec_pubkey_parse(ByteBuffer byteBuff, long context, int inputLen);
private static native byte[][] secp256k1_schnorr_sign(ByteBuffer byteBuff, long context);
private static native byte[][] secp256k1_ecdh(ByteBuffer byteBuff, long context, int inputLen);
}
| 18,056
| 34.685771
| 120
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoin/protocols/payments/Protos.java
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: paymentrequest.proto
package org.bitcoin.protocols.payments;
public final class Protos {
private Protos() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public interface OutputOrBuilder extends
// @@protoc_insertion_point(interface_extends:payments.Output)
com.google.protobuf.MessageLiteOrBuilder {
/**
* <pre>
* amount is integer-number-of-satoshis
* </pre>
*
* <code>optional uint64 amount = 1 [default = 0];</code>
* @return Whether the amount field is set.
*/
boolean hasAmount();
/**
* <pre>
* amount is integer-number-of-satoshis
* </pre>
*
* <code>optional uint64 amount = 1 [default = 0];</code>
* @return The amount.
*/
long getAmount();
/**
* <pre>
* usually one of the standard Script forms
* </pre>
*
* <code>required bytes script = 2;</code>
* @return Whether the script field is set.
*/
boolean hasScript();
/**
* <pre>
* usually one of the standard Script forms
* </pre>
*
* <code>required bytes script = 2;</code>
* @return The script.
*/
com.google.protobuf.ByteString getScript();
}
/**
* <pre>
* Generalized form of "send payment to this/these bitcoin addresses"
* </pre>
*
* Protobuf type {@code payments.Output}
*/
public static final class Output extends
com.google.protobuf.GeneratedMessageLite<
Output, Output.Builder> implements
// @@protoc_insertion_point(message_implements:payments.Output)
OutputOrBuilder {
private Output() {
script_ = com.google.protobuf.ByteString.EMPTY;
}
private int bitField0_;
public static final int AMOUNT_FIELD_NUMBER = 1;
private long amount_;
/**
* <pre>
* amount is integer-number-of-satoshis
* </pre>
*
* <code>optional uint64 amount = 1 [default = 0];</code>
* @return Whether the amount field is set.
*/
@java.lang.Override
public boolean hasAmount() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* amount is integer-number-of-satoshis
* </pre>
*
* <code>optional uint64 amount = 1 [default = 0];</code>
* @return The amount.
*/
@java.lang.Override
public long getAmount() {
return amount_;
}
/**
* <pre>
* amount is integer-number-of-satoshis
* </pre>
*
* <code>optional uint64 amount = 1 [default = 0];</code>
* @param value The amount to set.
*/
private void setAmount(long value) {
bitField0_ |= 0x00000001;
amount_ = value;
}
/**
* <pre>
* amount is integer-number-of-satoshis
* </pre>
*
* <code>optional uint64 amount = 1 [default = 0];</code>
*/
private void clearAmount() {
bitField0_ = (bitField0_ & ~0x00000001);
amount_ = 0L;
}
public static final int SCRIPT_FIELD_NUMBER = 2;
private com.google.protobuf.ByteString script_;
/**
* <pre>
* usually one of the standard Script forms
* </pre>
*
* <code>required bytes script = 2;</code>
* @return Whether the script field is set.
*/
@java.lang.Override
public boolean hasScript() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* usually one of the standard Script forms
* </pre>
*
* <code>required bytes script = 2;</code>
* @return The script.
*/
@java.lang.Override
public com.google.protobuf.ByteString getScript() {
return script_;
}
/**
* <pre>
* usually one of the standard Script forms
* </pre>
*
* <code>required bytes script = 2;</code>
* @param value The script to set.
*/
private void setScript(com.google.protobuf.ByteString value) {
java.lang.Class<?> valueClass = value.getClass();
bitField0_ |= 0x00000002;
script_ = value;
}
/**
* <pre>
* usually one of the standard Script forms
* </pre>
*
* <code>required bytes script = 2;</code>
*/
private void clearScript() {
bitField0_ = (bitField0_ & ~0x00000002);
script_ = getDefaultInstance().getScript();
}
public static org.bitcoin.protocols.payments.Protos.Output parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.Output parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.Output parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.Output parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.Output parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.Output parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.Output parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.Output parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.Output parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.Output parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.Output parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.Output parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static Builder newBuilder() {
return (Builder) DEFAULT_INSTANCE.createBuilder();
}
public static Builder newBuilder(org.bitcoin.protocols.payments.Protos.Output prototype) {
return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);
}
/**
* <pre>
* Generalized form of "send payment to this/these bitcoin addresses"
* </pre>
*
* Protobuf type {@code payments.Output}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageLite.Builder<
org.bitcoin.protocols.payments.Protos.Output, Builder> implements
// @@protoc_insertion_point(builder_implements:payments.Output)
org.bitcoin.protocols.payments.Protos.OutputOrBuilder {
// Construct using org.bitcoin.protocols.payments.Protos.Output.newBuilder()
private Builder() {
super(DEFAULT_INSTANCE);
}
/**
* <pre>
* amount is integer-number-of-satoshis
* </pre>
*
* <code>optional uint64 amount = 1 [default = 0];</code>
* @return Whether the amount field is set.
*/
@java.lang.Override
public boolean hasAmount() {
return instance.hasAmount();
}
/**
* <pre>
* amount is integer-number-of-satoshis
* </pre>
*
* <code>optional uint64 amount = 1 [default = 0];</code>
* @return The amount.
*/
@java.lang.Override
public long getAmount() {
return instance.getAmount();
}
/**
* <pre>
* amount is integer-number-of-satoshis
* </pre>
*
* <code>optional uint64 amount = 1 [default = 0];</code>
* @param value The amount to set.
* @return This builder for chaining.
*/
public Builder setAmount(long value) {
copyOnWrite();
instance.setAmount(value);
return this;
}
/**
* <pre>
* amount is integer-number-of-satoshis
* </pre>
*
* <code>optional uint64 amount = 1 [default = 0];</code>
* @return This builder for chaining.
*/
public Builder clearAmount() {
copyOnWrite();
instance.clearAmount();
return this;
}
/**
* <pre>
* usually one of the standard Script forms
* </pre>
*
* <code>required bytes script = 2;</code>
* @return Whether the script field is set.
*/
@java.lang.Override
public boolean hasScript() {
return instance.hasScript();
}
/**
* <pre>
* usually one of the standard Script forms
* </pre>
*
* <code>required bytes script = 2;</code>
* @return The script.
*/
@java.lang.Override
public com.google.protobuf.ByteString getScript() {
return instance.getScript();
}
/**
* <pre>
* usually one of the standard Script forms
* </pre>
*
* <code>required bytes script = 2;</code>
* @param value The script to set.
* @return This builder for chaining.
*/
public Builder setScript(com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setScript(value);
return this;
}
/**
* <pre>
* usually one of the standard Script forms
* </pre>
*
* <code>required bytes script = 2;</code>
* @return This builder for chaining.
*/
public Builder clearScript() {
copyOnWrite();
instance.clearScript();
return this;
}
// @@protoc_insertion_point(builder_scope:payments.Output)
}
private byte memoizedIsInitialized = 2;
@java.lang.Override
@java.lang.SuppressWarnings({"unchecked", "fallthrough"})
protected final java.lang.Object dynamicMethod(
com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,
java.lang.Object arg0, java.lang.Object arg1) {
switch (method) {
case NEW_MUTABLE_INSTANCE: {
return new org.bitcoin.protocols.payments.Protos.Output();
}
case NEW_BUILDER: {
return new Builder();
}
case BUILD_MESSAGE_INFO: {
java.lang.Object[] objects = new java.lang.Object[] {
"bitField0_",
"amount_",
"script_",
};
java.lang.String info =
"\u0001\u0002\u0000\u0001\u0001\u0002\u0002\u0000\u0000\u0001\u0001\u1003\u0000\u0002" +
"\u150a\u0001";
return newMessageInfo(DEFAULT_INSTANCE, info, objects);
}
// fall through
case GET_DEFAULT_INSTANCE: {
return DEFAULT_INSTANCE;
}
case GET_PARSER: {
com.google.protobuf.Parser<org.bitcoin.protocols.payments.Protos.Output> parser = PARSER;
if (parser == null) {
synchronized (org.bitcoin.protocols.payments.Protos.Output.class) {
parser = PARSER;
if (parser == null) {
parser =
new DefaultInstanceBasedParser<org.bitcoin.protocols.payments.Protos.Output>(
DEFAULT_INSTANCE);
PARSER = parser;
}
}
}
return parser;
}
case GET_MEMOIZED_IS_INITIALIZED: {
return memoizedIsInitialized;
}
case SET_MEMOIZED_IS_INITIALIZED: {
memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1);
return null;
}
}
throw new UnsupportedOperationException();
}
// @@protoc_insertion_point(class_scope:payments.Output)
private static final org.bitcoin.protocols.payments.Protos.Output DEFAULT_INSTANCE;
static {
Output defaultInstance = new Output();
// New instances are implicitly immutable so no need to make
// immutable.
DEFAULT_INSTANCE = defaultInstance;
com.google.protobuf.GeneratedMessageLite.registerDefaultInstance(
Output.class, defaultInstance);
}
public static org.bitcoin.protocols.payments.Protos.Output getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static volatile com.google.protobuf.Parser<Output> PARSER;
public static com.google.protobuf.Parser<Output> parser() {
return DEFAULT_INSTANCE.getParserForType();
}
}
public interface PaymentDetailsOrBuilder extends
// @@protoc_insertion_point(interface_extends:payments.PaymentDetails)
com.google.protobuf.MessageLiteOrBuilder {
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @return Whether the network field is set.
*/
boolean hasNetwork();
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @return The network.
*/
java.lang.String getNetwork();
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @return The bytes for network.
*/
com.google.protobuf.ByteString
getNetworkBytes();
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
java.util.List<org.bitcoin.protocols.payments.Protos.Output>
getOutputsList();
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
org.bitcoin.protocols.payments.Protos.Output getOutputs(int index);
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
int getOutputsCount();
/**
* <pre>
* Timestamp; when payment request created
* </pre>
*
* <code>required uint64 time = 3;</code>
* @return Whether the time field is set.
*/
boolean hasTime();
/**
* <pre>
* Timestamp; when payment request created
* </pre>
*
* <code>required uint64 time = 3;</code>
* @return The time.
*/
long getTime();
/**
* <pre>
* Timestamp; when this request should be considered invalid
* </pre>
*
* <code>optional uint64 expires = 4;</code>
* @return Whether the expires field is set.
*/
boolean hasExpires();
/**
* <pre>
* Timestamp; when this request should be considered invalid
* </pre>
*
* <code>optional uint64 expires = 4;</code>
* @return The expires.
*/
long getExpires();
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @return Whether the memo field is set.
*/
boolean hasMemo();
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @return The memo.
*/
java.lang.String getMemo();
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @return The bytes for memo.
*/
com.google.protobuf.ByteString
getMemoBytes();
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @return Whether the paymentUrl field is set.
*/
boolean hasPaymentUrl();
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @return The paymentUrl.
*/
java.lang.String getPaymentUrl();
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @return The bytes for paymentUrl.
*/
com.google.protobuf.ByteString
getPaymentUrlBytes();
/**
* <pre>
* Arbitrary data to include in the Payment message
* </pre>
*
* <code>optional bytes merchant_data = 7;</code>
* @return Whether the merchantData field is set.
*/
boolean hasMerchantData();
/**
* <pre>
* Arbitrary data to include in the Payment message
* </pre>
*
* <code>optional bytes merchant_data = 7;</code>
* @return The merchantData.
*/
com.google.protobuf.ByteString getMerchantData();
}
/**
* Protobuf type {@code payments.PaymentDetails}
*/
public static final class PaymentDetails extends
com.google.protobuf.GeneratedMessageLite<
PaymentDetails, PaymentDetails.Builder> implements
// @@protoc_insertion_point(message_implements:payments.PaymentDetails)
PaymentDetailsOrBuilder {
private PaymentDetails() {
network_ = "main";
outputs_ = emptyProtobufList();
memo_ = "";
paymentUrl_ = "";
merchantData_ = com.google.protobuf.ByteString.EMPTY;
}
private int bitField0_;
public static final int NETWORK_FIELD_NUMBER = 1;
private java.lang.String network_;
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @return Whether the network field is set.
*/
@java.lang.Override
public boolean hasNetwork() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @return The network.
*/
@java.lang.Override
public java.lang.String getNetwork() {
return network_;
}
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @return The bytes for network.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getNetworkBytes() {
return com.google.protobuf.ByteString.copyFromUtf8(network_);
}
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @param value The network to set.
*/
private void setNetwork(
java.lang.String value) {
java.lang.Class<?> valueClass = value.getClass();
bitField0_ |= 0x00000001;
network_ = value;
}
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
*/
private void clearNetwork() {
bitField0_ = (bitField0_ & ~0x00000001);
network_ = getDefaultInstance().getNetwork();
}
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @param value The bytes for network to set.
*/
private void setNetworkBytes(
com.google.protobuf.ByteString value) {
network_ = value.toStringUtf8();
bitField0_ |= 0x00000001;
}
public static final int OUTPUTS_FIELD_NUMBER = 2;
private com.google.protobuf.Internal.ProtobufList<org.bitcoin.protocols.payments.Protos.Output> outputs_;
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
@java.lang.Override
public java.util.List<org.bitcoin.protocols.payments.Protos.Output> getOutputsList() {
return outputs_;
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
public java.util.List<? extends org.bitcoin.protocols.payments.Protos.OutputOrBuilder>
getOutputsOrBuilderList() {
return outputs_;
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
@java.lang.Override
public int getOutputsCount() {
return outputs_.size();
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
@java.lang.Override
public org.bitcoin.protocols.payments.Protos.Output getOutputs(int index) {
return outputs_.get(index);
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
public org.bitcoin.protocols.payments.Protos.OutputOrBuilder getOutputsOrBuilder(
int index) {
return outputs_.get(index);
}
private void ensureOutputsIsMutable() {
com.google.protobuf.Internal.ProtobufList<org.bitcoin.protocols.payments.Protos.Output> tmp = outputs_;
if (!tmp.isModifiable()) {
outputs_ =
com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp);
}
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
private void setOutputs(
int index, org.bitcoin.protocols.payments.Protos.Output value) {
value.getClass();
ensureOutputsIsMutable();
outputs_.set(index, value);
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
private void addOutputs(org.bitcoin.protocols.payments.Protos.Output value) {
value.getClass();
ensureOutputsIsMutable();
outputs_.add(value);
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
private void addOutputs(
int index, org.bitcoin.protocols.payments.Protos.Output value) {
value.getClass();
ensureOutputsIsMutable();
outputs_.add(index, value);
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
private void addAllOutputs(
java.lang.Iterable<? extends org.bitcoin.protocols.payments.Protos.Output> values) {
ensureOutputsIsMutable();
com.google.protobuf.AbstractMessageLite.addAll(
values, outputs_);
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
private void clearOutputs() {
outputs_ = emptyProtobufList();
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
private void removeOutputs(int index) {
ensureOutputsIsMutable();
outputs_.remove(index);
}
public static final int TIME_FIELD_NUMBER = 3;
private long time_;
/**
* <pre>
* Timestamp; when payment request created
* </pre>
*
* <code>required uint64 time = 3;</code>
* @return Whether the time field is set.
*/
@java.lang.Override
public boolean hasTime() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Timestamp; when payment request created
* </pre>
*
* <code>required uint64 time = 3;</code>
* @return The time.
*/
@java.lang.Override
public long getTime() {
return time_;
}
/**
* <pre>
* Timestamp; when payment request created
* </pre>
*
* <code>required uint64 time = 3;</code>
* @param value The time to set.
*/
private void setTime(long value) {
bitField0_ |= 0x00000002;
time_ = value;
}
/**
* <pre>
* Timestamp; when payment request created
* </pre>
*
* <code>required uint64 time = 3;</code>
*/
private void clearTime() {
bitField0_ = (bitField0_ & ~0x00000002);
time_ = 0L;
}
public static final int EXPIRES_FIELD_NUMBER = 4;
private long expires_;
/**
* <pre>
* Timestamp; when this request should be considered invalid
* </pre>
*
* <code>optional uint64 expires = 4;</code>
* @return Whether the expires field is set.
*/
@java.lang.Override
public boolean hasExpires() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* Timestamp; when this request should be considered invalid
* </pre>
*
* <code>optional uint64 expires = 4;</code>
* @return The expires.
*/
@java.lang.Override
public long getExpires() {
return expires_;
}
/**
* <pre>
* Timestamp; when this request should be considered invalid
* </pre>
*
* <code>optional uint64 expires = 4;</code>
* @param value The expires to set.
*/
private void setExpires(long value) {
bitField0_ |= 0x00000004;
expires_ = value;
}
/**
* <pre>
* Timestamp; when this request should be considered invalid
* </pre>
*
* <code>optional uint64 expires = 4;</code>
*/
private void clearExpires() {
bitField0_ = (bitField0_ & ~0x00000004);
expires_ = 0L;
}
public static final int MEMO_FIELD_NUMBER = 5;
private java.lang.String memo_;
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @return Whether the memo field is set.
*/
@java.lang.Override
public boolean hasMemo() {
return ((bitField0_ & 0x00000008) != 0);
}
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @return The memo.
*/
@java.lang.Override
public java.lang.String getMemo() {
return memo_;
}
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @return The bytes for memo.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getMemoBytes() {
return com.google.protobuf.ByteString.copyFromUtf8(memo_);
}
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @param value The memo to set.
*/
private void setMemo(
java.lang.String value) {
java.lang.Class<?> valueClass = value.getClass();
bitField0_ |= 0x00000008;
memo_ = value;
}
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
*/
private void clearMemo() {
bitField0_ = (bitField0_ & ~0x00000008);
memo_ = getDefaultInstance().getMemo();
}
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @param value The bytes for memo to set.
*/
private void setMemoBytes(
com.google.protobuf.ByteString value) {
memo_ = value.toStringUtf8();
bitField0_ |= 0x00000008;
}
public static final int PAYMENT_URL_FIELD_NUMBER = 6;
private java.lang.String paymentUrl_;
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @return Whether the paymentUrl field is set.
*/
@java.lang.Override
public boolean hasPaymentUrl() {
return ((bitField0_ & 0x00000010) != 0);
}
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @return The paymentUrl.
*/
@java.lang.Override
public java.lang.String getPaymentUrl() {
return paymentUrl_;
}
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @return The bytes for paymentUrl.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getPaymentUrlBytes() {
return com.google.protobuf.ByteString.copyFromUtf8(paymentUrl_);
}
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @param value The paymentUrl to set.
*/
private void setPaymentUrl(
java.lang.String value) {
java.lang.Class<?> valueClass = value.getClass();
bitField0_ |= 0x00000010;
paymentUrl_ = value;
}
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
*/
private void clearPaymentUrl() {
bitField0_ = (bitField0_ & ~0x00000010);
paymentUrl_ = getDefaultInstance().getPaymentUrl();
}
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @param value The bytes for paymentUrl to set.
*/
private void setPaymentUrlBytes(
com.google.protobuf.ByteString value) {
paymentUrl_ = value.toStringUtf8();
bitField0_ |= 0x00000010;
}
public static final int MERCHANT_DATA_FIELD_NUMBER = 7;
private com.google.protobuf.ByteString merchantData_;
/**
* <pre>
* Arbitrary data to include in the Payment message
* </pre>
*
* <code>optional bytes merchant_data = 7;</code>
* @return Whether the merchantData field is set.
*/
@java.lang.Override
public boolean hasMerchantData() {
return ((bitField0_ & 0x00000020) != 0);
}
/**
* <pre>
* Arbitrary data to include in the Payment message
* </pre>
*
* <code>optional bytes merchant_data = 7;</code>
* @return The merchantData.
*/
@java.lang.Override
public com.google.protobuf.ByteString getMerchantData() {
return merchantData_;
}
/**
* <pre>
* Arbitrary data to include in the Payment message
* </pre>
*
* <code>optional bytes merchant_data = 7;</code>
* @param value The merchantData to set.
*/
private void setMerchantData(com.google.protobuf.ByteString value) {
java.lang.Class<?> valueClass = value.getClass();
bitField0_ |= 0x00000020;
merchantData_ = value;
}
/**
* <pre>
* Arbitrary data to include in the Payment message
* </pre>
*
* <code>optional bytes merchant_data = 7;</code>
*/
private void clearMerchantData() {
bitField0_ = (bitField0_ & ~0x00000020);
merchantData_ = getDefaultInstance().getMerchantData();
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static Builder newBuilder() {
return (Builder) DEFAULT_INSTANCE.createBuilder();
}
public static Builder newBuilder(org.bitcoin.protocols.payments.Protos.PaymentDetails prototype) {
return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);
}
/**
* Protobuf type {@code payments.PaymentDetails}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageLite.Builder<
org.bitcoin.protocols.payments.Protos.PaymentDetails, Builder> implements
// @@protoc_insertion_point(builder_implements:payments.PaymentDetails)
org.bitcoin.protocols.payments.Protos.PaymentDetailsOrBuilder {
// Construct using org.bitcoin.protocols.payments.Protos.PaymentDetails.newBuilder()
private Builder() {
super(DEFAULT_INSTANCE);
}
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @return Whether the network field is set.
*/
@java.lang.Override
public boolean hasNetwork() {
return instance.hasNetwork();
}
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @return The network.
*/
@java.lang.Override
public java.lang.String getNetwork() {
return instance.getNetwork();
}
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @return The bytes for network.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getNetworkBytes() {
return instance.getNetworkBytes();
}
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @param value The network to set.
* @return This builder for chaining.
*/
public Builder setNetwork(
java.lang.String value) {
copyOnWrite();
instance.setNetwork(value);
return this;
}
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @return This builder for chaining.
*/
public Builder clearNetwork() {
copyOnWrite();
instance.clearNetwork();
return this;
}
/**
* <pre>
* "main" or "test"
* </pre>
*
* <code>optional string network = 1 [default = "main"];</code>
* @param value The bytes for network to set.
* @return This builder for chaining.
*/
public Builder setNetworkBytes(
com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setNetworkBytes(value);
return this;
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
@java.lang.Override
public java.util.List<org.bitcoin.protocols.payments.Protos.Output> getOutputsList() {
return java.util.Collections.unmodifiableList(
instance.getOutputsList());
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
@java.lang.Override
public int getOutputsCount() {
return instance.getOutputsCount();
}/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
@java.lang.Override
public org.bitcoin.protocols.payments.Protos.Output getOutputs(int index) {
return instance.getOutputs(index);
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
public Builder setOutputs(
int index, org.bitcoin.protocols.payments.Protos.Output value) {
copyOnWrite();
instance.setOutputs(index, value);
return this;
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
public Builder setOutputs(
int index, org.bitcoin.protocols.payments.Protos.Output.Builder builderForValue) {
copyOnWrite();
instance.setOutputs(index,
builderForValue.build());
return this;
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
public Builder addOutputs(org.bitcoin.protocols.payments.Protos.Output value) {
copyOnWrite();
instance.addOutputs(value);
return this;
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
public Builder addOutputs(
int index, org.bitcoin.protocols.payments.Protos.Output value) {
copyOnWrite();
instance.addOutputs(index, value);
return this;
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
public Builder addOutputs(
org.bitcoin.protocols.payments.Protos.Output.Builder builderForValue) {
copyOnWrite();
instance.addOutputs(builderForValue.build());
return this;
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
public Builder addOutputs(
int index, org.bitcoin.protocols.payments.Protos.Output.Builder builderForValue) {
copyOnWrite();
instance.addOutputs(index,
builderForValue.build());
return this;
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
public Builder addAllOutputs(
java.lang.Iterable<? extends org.bitcoin.protocols.payments.Protos.Output> values) {
copyOnWrite();
instance.addAllOutputs(values);
return this;
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
public Builder clearOutputs() {
copyOnWrite();
instance.clearOutputs();
return this;
}
/**
* <pre>
* Where payment should be sent
* </pre>
*
* <code>repeated .payments.Output outputs = 2;</code>
*/
public Builder removeOutputs(int index) {
copyOnWrite();
instance.removeOutputs(index);
return this;
}
/**
* <pre>
* Timestamp; when payment request created
* </pre>
*
* <code>required uint64 time = 3;</code>
* @return Whether the time field is set.
*/
@java.lang.Override
public boolean hasTime() {
return instance.hasTime();
}
/**
* <pre>
* Timestamp; when payment request created
* </pre>
*
* <code>required uint64 time = 3;</code>
* @return The time.
*/
@java.lang.Override
public long getTime() {
return instance.getTime();
}
/**
* <pre>
* Timestamp; when payment request created
* </pre>
*
* <code>required uint64 time = 3;</code>
* @param value The time to set.
* @return This builder for chaining.
*/
public Builder setTime(long value) {
copyOnWrite();
instance.setTime(value);
return this;
}
/**
* <pre>
* Timestamp; when payment request created
* </pre>
*
* <code>required uint64 time = 3;</code>
* @return This builder for chaining.
*/
public Builder clearTime() {
copyOnWrite();
instance.clearTime();
return this;
}
/**
* <pre>
* Timestamp; when this request should be considered invalid
* </pre>
*
* <code>optional uint64 expires = 4;</code>
* @return Whether the expires field is set.
*/
@java.lang.Override
public boolean hasExpires() {
return instance.hasExpires();
}
/**
* <pre>
* Timestamp; when this request should be considered invalid
* </pre>
*
* <code>optional uint64 expires = 4;</code>
* @return The expires.
*/
@java.lang.Override
public long getExpires() {
return instance.getExpires();
}
/**
* <pre>
* Timestamp; when this request should be considered invalid
* </pre>
*
* <code>optional uint64 expires = 4;</code>
* @param value The expires to set.
* @return This builder for chaining.
*/
public Builder setExpires(long value) {
copyOnWrite();
instance.setExpires(value);
return this;
}
/**
* <pre>
* Timestamp; when this request should be considered invalid
* </pre>
*
* <code>optional uint64 expires = 4;</code>
* @return This builder for chaining.
*/
public Builder clearExpires() {
copyOnWrite();
instance.clearExpires();
return this;
}
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @return Whether the memo field is set.
*/
@java.lang.Override
public boolean hasMemo() {
return instance.hasMemo();
}
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @return The memo.
*/
@java.lang.Override
public java.lang.String getMemo() {
return instance.getMemo();
}
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @return The bytes for memo.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getMemoBytes() {
return instance.getMemoBytes();
}
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @param value The memo to set.
* @return This builder for chaining.
*/
public Builder setMemo(
java.lang.String value) {
copyOnWrite();
instance.setMemo(value);
return this;
}
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @return This builder for chaining.
*/
public Builder clearMemo() {
copyOnWrite();
instance.clearMemo();
return this;
}
/**
* <pre>
* Human-readable description of request for the customer
* </pre>
*
* <code>optional string memo = 5;</code>
* @param value The bytes for memo to set.
* @return This builder for chaining.
*/
public Builder setMemoBytes(
com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setMemoBytes(value);
return this;
}
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @return Whether the paymentUrl field is set.
*/
@java.lang.Override
public boolean hasPaymentUrl() {
return instance.hasPaymentUrl();
}
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @return The paymentUrl.
*/
@java.lang.Override
public java.lang.String getPaymentUrl() {
return instance.getPaymentUrl();
}
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @return The bytes for paymentUrl.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getPaymentUrlBytes() {
return instance.getPaymentUrlBytes();
}
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @param value The paymentUrl to set.
* @return This builder for chaining.
*/
public Builder setPaymentUrl(
java.lang.String value) {
copyOnWrite();
instance.setPaymentUrl(value);
return this;
}
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @return This builder for chaining.
*/
public Builder clearPaymentUrl() {
copyOnWrite();
instance.clearPaymentUrl();
return this;
}
/**
* <pre>
* URL to send Payment and get PaymentACK
* </pre>
*
* <code>optional string payment_url = 6;</code>
* @param value The bytes for paymentUrl to set.
* @return This builder for chaining.
*/
public Builder setPaymentUrlBytes(
com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setPaymentUrlBytes(value);
return this;
}
/**
* <pre>
* Arbitrary data to include in the Payment message
* </pre>
*
* <code>optional bytes merchant_data = 7;</code>
* @return Whether the merchantData field is set.
*/
@java.lang.Override
public boolean hasMerchantData() {
return instance.hasMerchantData();
}
/**
* <pre>
* Arbitrary data to include in the Payment message
* </pre>
*
* <code>optional bytes merchant_data = 7;</code>
* @return The merchantData.
*/
@java.lang.Override
public com.google.protobuf.ByteString getMerchantData() {
return instance.getMerchantData();
}
/**
* <pre>
* Arbitrary data to include in the Payment message
* </pre>
*
* <code>optional bytes merchant_data = 7;</code>
* @param value The merchantData to set.
* @return This builder for chaining.
*/
public Builder setMerchantData(com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setMerchantData(value);
return this;
}
/**
* <pre>
* Arbitrary data to include in the Payment message
* </pre>
*
* <code>optional bytes merchant_data = 7;</code>
* @return This builder for chaining.
*/
public Builder clearMerchantData() {
copyOnWrite();
instance.clearMerchantData();
return this;
}
// @@protoc_insertion_point(builder_scope:payments.PaymentDetails)
}
private byte memoizedIsInitialized = 2;
@java.lang.Override
@java.lang.SuppressWarnings({"unchecked", "fallthrough"})
protected final java.lang.Object dynamicMethod(
com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,
java.lang.Object arg0, java.lang.Object arg1) {
switch (method) {
case NEW_MUTABLE_INSTANCE: {
return new org.bitcoin.protocols.payments.Protos.PaymentDetails();
}
case NEW_BUILDER: {
return new Builder();
}
case BUILD_MESSAGE_INFO: {
java.lang.Object[] objects = new java.lang.Object[] {
"bitField0_",
"network_",
"outputs_",
org.bitcoin.protocols.payments.Protos.Output.class,
"time_",
"expires_",
"memo_",
"paymentUrl_",
"merchantData_",
};
java.lang.String info =
"\u0001\u0007\u0000\u0001\u0001\u0007\u0007\u0000\u0001\u0002\u0001\u1008\u0000\u0002" +
"\u041b\u0003\u1503\u0001\u0004\u1003\u0002\u0005\u1008\u0003\u0006\u1008\u0004\u0007" +
"\u100a\u0005";
return newMessageInfo(DEFAULT_INSTANCE, info, objects);
}
// fall through
case GET_DEFAULT_INSTANCE: {
return DEFAULT_INSTANCE;
}
case GET_PARSER: {
com.google.protobuf.Parser<org.bitcoin.protocols.payments.Protos.PaymentDetails> parser = PARSER;
if (parser == null) {
synchronized (org.bitcoin.protocols.payments.Protos.PaymentDetails.class) {
parser = PARSER;
if (parser == null) {
parser =
new DefaultInstanceBasedParser<org.bitcoin.protocols.payments.Protos.PaymentDetails>(
DEFAULT_INSTANCE);
PARSER = parser;
}
}
}
return parser;
}
case GET_MEMOIZED_IS_INITIALIZED: {
return memoizedIsInitialized;
}
case SET_MEMOIZED_IS_INITIALIZED: {
memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1);
return null;
}
}
throw new UnsupportedOperationException();
}
// @@protoc_insertion_point(class_scope:payments.PaymentDetails)
private static final org.bitcoin.protocols.payments.Protos.PaymentDetails DEFAULT_INSTANCE;
static {
PaymentDetails defaultInstance = new PaymentDetails();
// New instances are implicitly immutable so no need to make
// immutable.
DEFAULT_INSTANCE = defaultInstance;
com.google.protobuf.GeneratedMessageLite.registerDefaultInstance(
PaymentDetails.class, defaultInstance);
}
public static org.bitcoin.protocols.payments.Protos.PaymentDetails getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static volatile com.google.protobuf.Parser<PaymentDetails> PARSER;
public static com.google.protobuf.Parser<PaymentDetails> parser() {
return DEFAULT_INSTANCE.getParserForType();
}
}
public interface PaymentRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:payments.PaymentRequest)
com.google.protobuf.MessageLiteOrBuilder {
/**
* <code>optional uint32 payment_details_version = 1 [default = 1];</code>
* @return Whether the paymentDetailsVersion field is set.
*/
boolean hasPaymentDetailsVersion();
/**
* <code>optional uint32 payment_details_version = 1 [default = 1];</code>
* @return The paymentDetailsVersion.
*/
int getPaymentDetailsVersion();
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @return Whether the pkiType field is set.
*/
boolean hasPkiType();
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @return The pkiType.
*/
java.lang.String getPkiType();
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @return The bytes for pkiType.
*/
com.google.protobuf.ByteString
getPkiTypeBytes();
/**
* <pre>
* depends on pki_type
* </pre>
*
* <code>optional bytes pki_data = 3;</code>
* @return Whether the pkiData field is set.
*/
boolean hasPkiData();
/**
* <pre>
* depends on pki_type
* </pre>
*
* <code>optional bytes pki_data = 3;</code>
* @return The pkiData.
*/
com.google.protobuf.ByteString getPkiData();
/**
* <pre>
* PaymentDetails
* </pre>
*
* <code>required bytes serialized_payment_details = 4;</code>
* @return Whether the serializedPaymentDetails field is set.
*/
boolean hasSerializedPaymentDetails();
/**
* <pre>
* PaymentDetails
* </pre>
*
* <code>required bytes serialized_payment_details = 4;</code>
* @return The serializedPaymentDetails.
*/
com.google.protobuf.ByteString getSerializedPaymentDetails();
/**
* <pre>
* pki-dependent signature
* </pre>
*
* <code>optional bytes signature = 5;</code>
* @return Whether the signature field is set.
*/
boolean hasSignature();
/**
* <pre>
* pki-dependent signature
* </pre>
*
* <code>optional bytes signature = 5;</code>
* @return The signature.
*/
com.google.protobuf.ByteString getSignature();
}
/**
* Protobuf type {@code payments.PaymentRequest}
*/
public static final class PaymentRequest extends
com.google.protobuf.GeneratedMessageLite<
PaymentRequest, PaymentRequest.Builder> implements
// @@protoc_insertion_point(message_implements:payments.PaymentRequest)
PaymentRequestOrBuilder {
private PaymentRequest() {
paymentDetailsVersion_ = 1;
pkiType_ = "none";
pkiData_ = com.google.protobuf.ByteString.EMPTY;
serializedPaymentDetails_ = com.google.protobuf.ByteString.EMPTY;
signature_ = com.google.protobuf.ByteString.EMPTY;
}
private int bitField0_;
public static final int PAYMENT_DETAILS_VERSION_FIELD_NUMBER = 1;
private int paymentDetailsVersion_;
/**
* <code>optional uint32 payment_details_version = 1 [default = 1];</code>
* @return Whether the paymentDetailsVersion field is set.
*/
@java.lang.Override
public boolean hasPaymentDetailsVersion() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <code>optional uint32 payment_details_version = 1 [default = 1];</code>
* @return The paymentDetailsVersion.
*/
@java.lang.Override
public int getPaymentDetailsVersion() {
return paymentDetailsVersion_;
}
/**
* <code>optional uint32 payment_details_version = 1 [default = 1];</code>
* @param value The paymentDetailsVersion to set.
*/
private void setPaymentDetailsVersion(int value) {
bitField0_ |= 0x00000001;
paymentDetailsVersion_ = value;
}
/**
* <code>optional uint32 payment_details_version = 1 [default = 1];</code>
*/
private void clearPaymentDetailsVersion() {
bitField0_ = (bitField0_ & ~0x00000001);
paymentDetailsVersion_ = 1;
}
public static final int PKI_TYPE_FIELD_NUMBER = 2;
private java.lang.String pkiType_;
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @return Whether the pkiType field is set.
*/
@java.lang.Override
public boolean hasPkiType() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @return The pkiType.
*/
@java.lang.Override
public java.lang.String getPkiType() {
return pkiType_;
}
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @return The bytes for pkiType.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getPkiTypeBytes() {
return com.google.protobuf.ByteString.copyFromUtf8(pkiType_);
}
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @param value The pkiType to set.
*/
private void setPkiType(
java.lang.String value) {
java.lang.Class<?> valueClass = value.getClass();
bitField0_ |= 0x00000002;
pkiType_ = value;
}
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
*/
private void clearPkiType() {
bitField0_ = (bitField0_ & ~0x00000002);
pkiType_ = getDefaultInstance().getPkiType();
}
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @param value The bytes for pkiType to set.
*/
private void setPkiTypeBytes(
com.google.protobuf.ByteString value) {
pkiType_ = value.toStringUtf8();
bitField0_ |= 0x00000002;
}
public static final int PKI_DATA_FIELD_NUMBER = 3;
private com.google.protobuf.ByteString pkiData_;
/**
* <pre>
* depends on pki_type
* </pre>
*
* <code>optional bytes pki_data = 3;</code>
* @return Whether the pkiData field is set.
*/
@java.lang.Override
public boolean hasPkiData() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* depends on pki_type
* </pre>
*
* <code>optional bytes pki_data = 3;</code>
* @return The pkiData.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPkiData() {
return pkiData_;
}
/**
* <pre>
* depends on pki_type
* </pre>
*
* <code>optional bytes pki_data = 3;</code>
* @param value The pkiData to set.
*/
private void setPkiData(com.google.protobuf.ByteString value) {
java.lang.Class<?> valueClass = value.getClass();
bitField0_ |= 0x00000004;
pkiData_ = value;
}
/**
* <pre>
* depends on pki_type
* </pre>
*
* <code>optional bytes pki_data = 3;</code>
*/
private void clearPkiData() {
bitField0_ = (bitField0_ & ~0x00000004);
pkiData_ = getDefaultInstance().getPkiData();
}
public static final int SERIALIZED_PAYMENT_DETAILS_FIELD_NUMBER = 4;
private com.google.protobuf.ByteString serializedPaymentDetails_;
/**
* <pre>
* PaymentDetails
* </pre>
*
* <code>required bytes serialized_payment_details = 4;</code>
* @return Whether the serializedPaymentDetails field is set.
*/
@java.lang.Override
public boolean hasSerializedPaymentDetails() {
return ((bitField0_ & 0x00000008) != 0);
}
/**
* <pre>
* PaymentDetails
* </pre>
*
* <code>required bytes serialized_payment_details = 4;</code>
* @return The serializedPaymentDetails.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSerializedPaymentDetails() {
return serializedPaymentDetails_;
}
/**
* <pre>
* PaymentDetails
* </pre>
*
* <code>required bytes serialized_payment_details = 4;</code>
* @param value The serializedPaymentDetails to set.
*/
private void setSerializedPaymentDetails(com.google.protobuf.ByteString value) {
java.lang.Class<?> valueClass = value.getClass();
bitField0_ |= 0x00000008;
serializedPaymentDetails_ = value;
}
/**
* <pre>
* PaymentDetails
* </pre>
*
* <code>required bytes serialized_payment_details = 4;</code>
*/
private void clearSerializedPaymentDetails() {
bitField0_ = (bitField0_ & ~0x00000008);
serializedPaymentDetails_ = getDefaultInstance().getSerializedPaymentDetails();
}
public static final int SIGNATURE_FIELD_NUMBER = 5;
private com.google.protobuf.ByteString signature_;
/**
* <pre>
* pki-dependent signature
* </pre>
*
* <code>optional bytes signature = 5;</code>
* @return Whether the signature field is set.
*/
@java.lang.Override
public boolean hasSignature() {
return ((bitField0_ & 0x00000010) != 0);
}
/**
* <pre>
* pki-dependent signature
* </pre>
*
* <code>optional bytes signature = 5;</code>
* @return The signature.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSignature() {
return signature_;
}
/**
* <pre>
* pki-dependent signature
* </pre>
*
* <code>optional bytes signature = 5;</code>
* @param value The signature to set.
*/
private void setSignature(com.google.protobuf.ByteString value) {
java.lang.Class<?> valueClass = value.getClass();
bitField0_ |= 0x00000010;
signature_ = value;
}
/**
* <pre>
* pki-dependent signature
* </pre>
*
* <code>optional bytes signature = 5;</code>
*/
private void clearSignature() {
bitField0_ = (bitField0_ & ~0x00000010);
signature_ = getDefaultInstance().getSignature();
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static Builder newBuilder() {
return (Builder) DEFAULT_INSTANCE.createBuilder();
}
public static Builder newBuilder(org.bitcoin.protocols.payments.Protos.PaymentRequest prototype) {
return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);
}
/**
* Protobuf type {@code payments.PaymentRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageLite.Builder<
org.bitcoin.protocols.payments.Protos.PaymentRequest, Builder> implements
// @@protoc_insertion_point(builder_implements:payments.PaymentRequest)
org.bitcoin.protocols.payments.Protos.PaymentRequestOrBuilder {
// Construct using org.bitcoin.protocols.payments.Protos.PaymentRequest.newBuilder()
private Builder() {
super(DEFAULT_INSTANCE);
}
/**
* <code>optional uint32 payment_details_version = 1 [default = 1];</code>
* @return Whether the paymentDetailsVersion field is set.
*/
@java.lang.Override
public boolean hasPaymentDetailsVersion() {
return instance.hasPaymentDetailsVersion();
}
/**
* <code>optional uint32 payment_details_version = 1 [default = 1];</code>
* @return The paymentDetailsVersion.
*/
@java.lang.Override
public int getPaymentDetailsVersion() {
return instance.getPaymentDetailsVersion();
}
/**
* <code>optional uint32 payment_details_version = 1 [default = 1];</code>
* @param value The paymentDetailsVersion to set.
* @return This builder for chaining.
*/
public Builder setPaymentDetailsVersion(int value) {
copyOnWrite();
instance.setPaymentDetailsVersion(value);
return this;
}
/**
* <code>optional uint32 payment_details_version = 1 [default = 1];</code>
* @return This builder for chaining.
*/
public Builder clearPaymentDetailsVersion() {
copyOnWrite();
instance.clearPaymentDetailsVersion();
return this;
}
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @return Whether the pkiType field is set.
*/
@java.lang.Override
public boolean hasPkiType() {
return instance.hasPkiType();
}
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @return The pkiType.
*/
@java.lang.Override
public java.lang.String getPkiType() {
return instance.getPkiType();
}
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @return The bytes for pkiType.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getPkiTypeBytes() {
return instance.getPkiTypeBytes();
}
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @param value The pkiType to set.
* @return This builder for chaining.
*/
public Builder setPkiType(
java.lang.String value) {
copyOnWrite();
instance.setPkiType(value);
return this;
}
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @return This builder for chaining.
*/
public Builder clearPkiType() {
copyOnWrite();
instance.clearPkiType();
return this;
}
/**
* <pre>
* none / x509+sha256 / x509+sha1
* </pre>
*
* <code>optional string pki_type = 2 [default = "none"];</code>
* @param value The bytes for pkiType to set.
* @return This builder for chaining.
*/
public Builder setPkiTypeBytes(
com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setPkiTypeBytes(value);
return this;
}
/**
* <pre>
* depends on pki_type
* </pre>
*
* <code>optional bytes pki_data = 3;</code>
* @return Whether the pkiData field is set.
*/
@java.lang.Override
public boolean hasPkiData() {
return instance.hasPkiData();
}
/**
* <pre>
* depends on pki_type
* </pre>
*
* <code>optional bytes pki_data = 3;</code>
* @return The pkiData.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPkiData() {
return instance.getPkiData();
}
/**
* <pre>
* depends on pki_type
* </pre>
*
* <code>optional bytes pki_data = 3;</code>
* @param value The pkiData to set.
* @return This builder for chaining.
*/
public Builder setPkiData(com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setPkiData(value);
return this;
}
/**
* <pre>
* depends on pki_type
* </pre>
*
* <code>optional bytes pki_data = 3;</code>
* @return This builder for chaining.
*/
public Builder clearPkiData() {
copyOnWrite();
instance.clearPkiData();
return this;
}
/**
* <pre>
* PaymentDetails
* </pre>
*
* <code>required bytes serialized_payment_details = 4;</code>
* @return Whether the serializedPaymentDetails field is set.
*/
@java.lang.Override
public boolean hasSerializedPaymentDetails() {
return instance.hasSerializedPaymentDetails();
}
/**
* <pre>
* PaymentDetails
* </pre>
*
* <code>required bytes serialized_payment_details = 4;</code>
* @return The serializedPaymentDetails.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSerializedPaymentDetails() {
return instance.getSerializedPaymentDetails();
}
/**
* <pre>
* PaymentDetails
* </pre>
*
* <code>required bytes serialized_payment_details = 4;</code>
* @param value The serializedPaymentDetails to set.
* @return This builder for chaining.
*/
public Builder setSerializedPaymentDetails(com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setSerializedPaymentDetails(value);
return this;
}
/**
* <pre>
* PaymentDetails
* </pre>
*
* <code>required bytes serialized_payment_details = 4;</code>
* @return This builder for chaining.
*/
public Builder clearSerializedPaymentDetails() {
copyOnWrite();
instance.clearSerializedPaymentDetails();
return this;
}
/**
* <pre>
* pki-dependent signature
* </pre>
*
* <code>optional bytes signature = 5;</code>
* @return Whether the signature field is set.
*/
@java.lang.Override
public boolean hasSignature() {
return instance.hasSignature();
}
/**
* <pre>
* pki-dependent signature
* </pre>
*
* <code>optional bytes signature = 5;</code>
* @return The signature.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSignature() {
return instance.getSignature();
}
/**
* <pre>
* pki-dependent signature
* </pre>
*
* <code>optional bytes signature = 5;</code>
* @param value The signature to set.
* @return This builder for chaining.
*/
public Builder setSignature(com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setSignature(value);
return this;
}
/**
* <pre>
* pki-dependent signature
* </pre>
*
* <code>optional bytes signature = 5;</code>
* @return This builder for chaining.
*/
public Builder clearSignature() {
copyOnWrite();
instance.clearSignature();
return this;
}
// @@protoc_insertion_point(builder_scope:payments.PaymentRequest)
}
private byte memoizedIsInitialized = 2;
@java.lang.Override
@java.lang.SuppressWarnings({"unchecked", "fallthrough"})
protected final java.lang.Object dynamicMethod(
com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,
java.lang.Object arg0, java.lang.Object arg1) {
switch (method) {
case NEW_MUTABLE_INSTANCE: {
return new org.bitcoin.protocols.payments.Protos.PaymentRequest();
}
case NEW_BUILDER: {
return new Builder();
}
case BUILD_MESSAGE_INFO: {
java.lang.Object[] objects = new java.lang.Object[] {
"bitField0_",
"paymentDetailsVersion_",
"pkiType_",
"pkiData_",
"serializedPaymentDetails_",
"signature_",
};
java.lang.String info =
"\u0001\u0005\u0000\u0001\u0001\u0005\u0005\u0000\u0000\u0001\u0001\u100b\u0000\u0002" +
"\u1008\u0001\u0003\u100a\u0002\u0004\u150a\u0003\u0005\u100a\u0004";
return newMessageInfo(DEFAULT_INSTANCE, info, objects);
}
// fall through
case GET_DEFAULT_INSTANCE: {
return DEFAULT_INSTANCE;
}
case GET_PARSER: {
com.google.protobuf.Parser<org.bitcoin.protocols.payments.Protos.PaymentRequest> parser = PARSER;
if (parser == null) {
synchronized (org.bitcoin.protocols.payments.Protos.PaymentRequest.class) {
parser = PARSER;
if (parser == null) {
parser =
new DefaultInstanceBasedParser<org.bitcoin.protocols.payments.Protos.PaymentRequest>(
DEFAULT_INSTANCE);
PARSER = parser;
}
}
}
return parser;
}
case GET_MEMOIZED_IS_INITIALIZED: {
return memoizedIsInitialized;
}
case SET_MEMOIZED_IS_INITIALIZED: {
memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1);
return null;
}
}
throw new UnsupportedOperationException();
}
// @@protoc_insertion_point(class_scope:payments.PaymentRequest)
private static final org.bitcoin.protocols.payments.Protos.PaymentRequest DEFAULT_INSTANCE;
static {
PaymentRequest defaultInstance = new PaymentRequest();
// New instances are implicitly immutable so no need to make
// immutable.
DEFAULT_INSTANCE = defaultInstance;
com.google.protobuf.GeneratedMessageLite.registerDefaultInstance(
PaymentRequest.class, defaultInstance);
}
public static org.bitcoin.protocols.payments.Protos.PaymentRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static volatile com.google.protobuf.Parser<PaymentRequest> PARSER;
public static com.google.protobuf.Parser<PaymentRequest> parser() {
return DEFAULT_INSTANCE.getParserForType();
}
}
public interface X509CertificatesOrBuilder extends
// @@protoc_insertion_point(interface_extends:payments.X509Certificates)
com.google.protobuf.MessageLiteOrBuilder {
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @return A list containing the certificate.
*/
java.util.List<com.google.protobuf.ByteString> getCertificateList();
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @return The count of certificate.
*/
int getCertificateCount();
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @param index The index of the element to return.
* @return The certificate at the given index.
*/
com.google.protobuf.ByteString getCertificate(int index);
}
/**
* Protobuf type {@code payments.X509Certificates}
*/
public static final class X509Certificates extends
com.google.protobuf.GeneratedMessageLite<
X509Certificates, X509Certificates.Builder> implements
// @@protoc_insertion_point(message_implements:payments.X509Certificates)
X509CertificatesOrBuilder {
private X509Certificates() {
certificate_ = emptyProtobufList();
}
public static final int CERTIFICATE_FIELD_NUMBER = 1;
private com.google.protobuf.Internal.ProtobufList<com.google.protobuf.ByteString> certificate_;
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @return A list containing the certificate.
*/
@java.lang.Override
public java.util.List<com.google.protobuf.ByteString>
getCertificateList() {
return certificate_;
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @return The count of certificate.
*/
@java.lang.Override
public int getCertificateCount() {
return certificate_.size();
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @param index The index of the element to return.
* @return The certificate at the given index.
*/
@java.lang.Override
public com.google.protobuf.ByteString getCertificate(int index) {
return certificate_.get(index);
}
private void ensureCertificateIsMutable() {
com.google.protobuf.Internal.ProtobufList<com.google.protobuf.ByteString> tmp = certificate_;
if (!tmp.isModifiable()) {
certificate_ =
com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp);
}
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @param index The index to set the value at.
* @param value The certificate to set.
*/
private void setCertificate(
int index, com.google.protobuf.ByteString value) {
java.lang.Class<?> valueClass = value.getClass();
ensureCertificateIsMutable();
certificate_.set(index, value);
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @param value The certificate to add.
*/
private void addCertificate(com.google.protobuf.ByteString value) {
java.lang.Class<?> valueClass = value.getClass();
ensureCertificateIsMutable();
certificate_.add(value);
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @param values The certificate to add.
*/
private void addAllCertificate(
java.lang.Iterable<? extends com.google.protobuf.ByteString> values) {
ensureCertificateIsMutable();
com.google.protobuf.AbstractMessageLite.addAll(
values, certificate_);
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
*/
private void clearCertificate() {
certificate_ = emptyProtobufList();
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static Builder newBuilder() {
return (Builder) DEFAULT_INSTANCE.createBuilder();
}
public static Builder newBuilder(org.bitcoin.protocols.payments.Protos.X509Certificates prototype) {
return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);
}
/**
* Protobuf type {@code payments.X509Certificates}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageLite.Builder<
org.bitcoin.protocols.payments.Protos.X509Certificates, Builder> implements
// @@protoc_insertion_point(builder_implements:payments.X509Certificates)
org.bitcoin.protocols.payments.Protos.X509CertificatesOrBuilder {
// Construct using org.bitcoin.protocols.payments.Protos.X509Certificates.newBuilder()
private Builder() {
super(DEFAULT_INSTANCE);
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @return A list containing the certificate.
*/
@java.lang.Override
public java.util.List<com.google.protobuf.ByteString>
getCertificateList() {
return java.util.Collections.unmodifiableList(
instance.getCertificateList());
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @return The count of certificate.
*/
@java.lang.Override
public int getCertificateCount() {
return instance.getCertificateCount();
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @param index The index of the element to return.
* @return The certificate at the given index.
*/
@java.lang.Override
public com.google.protobuf.ByteString getCertificate(int index) {
return instance.getCertificate(index);
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @param value The certificate to set.
* @return This builder for chaining.
*/
public Builder setCertificate(
int index, com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setCertificate(index, value);
return this;
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @param value The certificate to add.
* @return This builder for chaining.
*/
public Builder addCertificate(com.google.protobuf.ByteString value) {
copyOnWrite();
instance.addCertificate(value);
return this;
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @param values The certificate to add.
* @return This builder for chaining.
*/
public Builder addAllCertificate(
java.lang.Iterable<? extends com.google.protobuf.ByteString> values) {
copyOnWrite();
instance.addAllCertificate(values);
return this;
}
/**
* <pre>
* DER-encoded X.509 certificate chain
* </pre>
*
* <code>repeated bytes certificate = 1;</code>
* @return This builder for chaining.
*/
public Builder clearCertificate() {
copyOnWrite();
instance.clearCertificate();
return this;
}
// @@protoc_insertion_point(builder_scope:payments.X509Certificates)
}
@java.lang.Override
@java.lang.SuppressWarnings({"unchecked", "fallthrough"})
protected final java.lang.Object dynamicMethod(
com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,
java.lang.Object arg0, java.lang.Object arg1) {
switch (method) {
case NEW_MUTABLE_INSTANCE: {
return new org.bitcoin.protocols.payments.Protos.X509Certificates();
}
case NEW_BUILDER: {
return new Builder();
}
case BUILD_MESSAGE_INFO: {
java.lang.Object[] objects = new java.lang.Object[] {
"certificate_",
};
java.lang.String info =
"\u0001\u0001\u0000\u0000\u0001\u0001\u0001\u0000\u0001\u0000\u0001\u001c";
return newMessageInfo(DEFAULT_INSTANCE, info, objects);
}
// fall through
case GET_DEFAULT_INSTANCE: {
return DEFAULT_INSTANCE;
}
case GET_PARSER: {
com.google.protobuf.Parser<org.bitcoin.protocols.payments.Protos.X509Certificates> parser = PARSER;
if (parser == null) {
synchronized (org.bitcoin.protocols.payments.Protos.X509Certificates.class) {
parser = PARSER;
if (parser == null) {
parser =
new DefaultInstanceBasedParser<org.bitcoin.protocols.payments.Protos.X509Certificates>(
DEFAULT_INSTANCE);
PARSER = parser;
}
}
}
return parser;
}
case GET_MEMOIZED_IS_INITIALIZED: {
return (byte) 1;
}
case SET_MEMOIZED_IS_INITIALIZED: {
return null;
}
}
throw new UnsupportedOperationException();
}
// @@protoc_insertion_point(class_scope:payments.X509Certificates)
private static final org.bitcoin.protocols.payments.Protos.X509Certificates DEFAULT_INSTANCE;
static {
X509Certificates defaultInstance = new X509Certificates();
// New instances are implicitly immutable so no need to make
// immutable.
DEFAULT_INSTANCE = defaultInstance;
com.google.protobuf.GeneratedMessageLite.registerDefaultInstance(
X509Certificates.class, defaultInstance);
}
public static org.bitcoin.protocols.payments.Protos.X509Certificates getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static volatile com.google.protobuf.Parser<X509Certificates> PARSER;
public static com.google.protobuf.Parser<X509Certificates> parser() {
return DEFAULT_INSTANCE.getParserForType();
}
}
public interface PaymentOrBuilder extends
// @@protoc_insertion_point(interface_extends:payments.Payment)
com.google.protobuf.MessageLiteOrBuilder {
/**
* <pre>
* From PaymentDetails.merchant_data
* </pre>
*
* <code>optional bytes merchant_data = 1;</code>
* @return Whether the merchantData field is set.
*/
boolean hasMerchantData();
/**
* <pre>
* From PaymentDetails.merchant_data
* </pre>
*
* <code>optional bytes merchant_data = 1;</code>
* @return The merchantData.
*/
com.google.protobuf.ByteString getMerchantData();
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @return A list containing the transactions.
*/
java.util.List<com.google.protobuf.ByteString> getTransactionsList();
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @return The count of transactions.
*/
int getTransactionsCount();
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @param index The index of the element to return.
* @return The transactions at the given index.
*/
com.google.protobuf.ByteString getTransactions(int index);
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
java.util.List<org.bitcoin.protocols.payments.Protos.Output>
getRefundToList();
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
org.bitcoin.protocols.payments.Protos.Output getRefundTo(int index);
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
int getRefundToCount();
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @return Whether the memo field is set.
*/
boolean hasMemo();
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @return The memo.
*/
java.lang.String getMemo();
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @return The bytes for memo.
*/
com.google.protobuf.ByteString
getMemoBytes();
}
/**
* Protobuf type {@code payments.Payment}
*/
public static final class Payment extends
com.google.protobuf.GeneratedMessageLite<
Payment, Payment.Builder> implements
// @@protoc_insertion_point(message_implements:payments.Payment)
PaymentOrBuilder {
private Payment() {
merchantData_ = com.google.protobuf.ByteString.EMPTY;
transactions_ = emptyProtobufList();
refundTo_ = emptyProtobufList();
memo_ = "";
}
private int bitField0_;
public static final int MERCHANT_DATA_FIELD_NUMBER = 1;
private com.google.protobuf.ByteString merchantData_;
/**
* <pre>
* From PaymentDetails.merchant_data
* </pre>
*
* <code>optional bytes merchant_data = 1;</code>
* @return Whether the merchantData field is set.
*/
@java.lang.Override
public boolean hasMerchantData() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* From PaymentDetails.merchant_data
* </pre>
*
* <code>optional bytes merchant_data = 1;</code>
* @return The merchantData.
*/
@java.lang.Override
public com.google.protobuf.ByteString getMerchantData() {
return merchantData_;
}
/**
* <pre>
* From PaymentDetails.merchant_data
* </pre>
*
* <code>optional bytes merchant_data = 1;</code>
* @param value The merchantData to set.
*/
private void setMerchantData(com.google.protobuf.ByteString value) {
java.lang.Class<?> valueClass = value.getClass();
bitField0_ |= 0x00000001;
merchantData_ = value;
}
/**
* <pre>
* From PaymentDetails.merchant_data
* </pre>
*
* <code>optional bytes merchant_data = 1;</code>
*/
private void clearMerchantData() {
bitField0_ = (bitField0_ & ~0x00000001);
merchantData_ = getDefaultInstance().getMerchantData();
}
public static final int TRANSACTIONS_FIELD_NUMBER = 2;
private com.google.protobuf.Internal.ProtobufList<com.google.protobuf.ByteString> transactions_;
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @return A list containing the transactions.
*/
@java.lang.Override
public java.util.List<com.google.protobuf.ByteString>
getTransactionsList() {
return transactions_;
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @return The count of transactions.
*/
@java.lang.Override
public int getTransactionsCount() {
return transactions_.size();
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @param index The index of the element to return.
* @return The transactions at the given index.
*/
@java.lang.Override
public com.google.protobuf.ByteString getTransactions(int index) {
return transactions_.get(index);
}
private void ensureTransactionsIsMutable() {
com.google.protobuf.Internal.ProtobufList<com.google.protobuf.ByteString> tmp = transactions_;
if (!tmp.isModifiable()) {
transactions_ =
com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp);
}
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @param index The index to set the value at.
* @param value The transactions to set.
*/
private void setTransactions(
int index, com.google.protobuf.ByteString value) {
java.lang.Class<?> valueClass = value.getClass();
ensureTransactionsIsMutable();
transactions_.set(index, value);
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @param value The transactions to add.
*/
private void addTransactions(com.google.protobuf.ByteString value) {
java.lang.Class<?> valueClass = value.getClass();
ensureTransactionsIsMutable();
transactions_.add(value);
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @param values The transactions to add.
*/
private void addAllTransactions(
java.lang.Iterable<? extends com.google.protobuf.ByteString> values) {
ensureTransactionsIsMutable();
com.google.protobuf.AbstractMessageLite.addAll(
values, transactions_);
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
*/
private void clearTransactions() {
transactions_ = emptyProtobufList();
}
public static final int REFUND_TO_FIELD_NUMBER = 3;
private com.google.protobuf.Internal.ProtobufList<org.bitcoin.protocols.payments.Protos.Output> refundTo_;
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
@java.lang.Override
public java.util.List<org.bitcoin.protocols.payments.Protos.Output> getRefundToList() {
return refundTo_;
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
public java.util.List<? extends org.bitcoin.protocols.payments.Protos.OutputOrBuilder>
getRefundToOrBuilderList() {
return refundTo_;
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
@java.lang.Override
public int getRefundToCount() {
return refundTo_.size();
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
@java.lang.Override
public org.bitcoin.protocols.payments.Protos.Output getRefundTo(int index) {
return refundTo_.get(index);
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
public org.bitcoin.protocols.payments.Protos.OutputOrBuilder getRefundToOrBuilder(
int index) {
return refundTo_.get(index);
}
private void ensureRefundToIsMutable() {
com.google.protobuf.Internal.ProtobufList<org.bitcoin.protocols.payments.Protos.Output> tmp = refundTo_;
if (!tmp.isModifiable()) {
refundTo_ =
com.google.protobuf.GeneratedMessageLite.mutableCopy(tmp);
}
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
private void setRefundTo(
int index, org.bitcoin.protocols.payments.Protos.Output value) {
value.getClass();
ensureRefundToIsMutable();
refundTo_.set(index, value);
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
private void addRefundTo(org.bitcoin.protocols.payments.Protos.Output value) {
value.getClass();
ensureRefundToIsMutable();
refundTo_.add(value);
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
private void addRefundTo(
int index, org.bitcoin.protocols.payments.Protos.Output value) {
value.getClass();
ensureRefundToIsMutable();
refundTo_.add(index, value);
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
private void addAllRefundTo(
java.lang.Iterable<? extends org.bitcoin.protocols.payments.Protos.Output> values) {
ensureRefundToIsMutable();
com.google.protobuf.AbstractMessageLite.addAll(
values, refundTo_);
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
private void clearRefundTo() {
refundTo_ = emptyProtobufList();
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
private void removeRefundTo(int index) {
ensureRefundToIsMutable();
refundTo_.remove(index);
}
public static final int MEMO_FIELD_NUMBER = 4;
private java.lang.String memo_;
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @return Whether the memo field is set.
*/
@java.lang.Override
public boolean hasMemo() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @return The memo.
*/
@java.lang.Override
public java.lang.String getMemo() {
return memo_;
}
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @return The bytes for memo.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getMemoBytes() {
return com.google.protobuf.ByteString.copyFromUtf8(memo_);
}
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @param value The memo to set.
*/
private void setMemo(
java.lang.String value) {
java.lang.Class<?> valueClass = value.getClass();
bitField0_ |= 0x00000002;
memo_ = value;
}
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
*/
private void clearMemo() {
bitField0_ = (bitField0_ & ~0x00000002);
memo_ = getDefaultInstance().getMemo();
}
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @param value The bytes for memo to set.
*/
private void setMemoBytes(
com.google.protobuf.ByteString value) {
memo_ = value.toStringUtf8();
bitField0_ |= 0x00000002;
}
public static org.bitcoin.protocols.payments.Protos.Payment parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.Payment parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.Payment parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.Payment parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.Payment parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.Payment parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.Payment parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.Payment parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.Payment parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.Payment parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.Payment parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.Payment parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static Builder newBuilder() {
return (Builder) DEFAULT_INSTANCE.createBuilder();
}
public static Builder newBuilder(org.bitcoin.protocols.payments.Protos.Payment prototype) {
return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);
}
/**
* Protobuf type {@code payments.Payment}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageLite.Builder<
org.bitcoin.protocols.payments.Protos.Payment, Builder> implements
// @@protoc_insertion_point(builder_implements:payments.Payment)
org.bitcoin.protocols.payments.Protos.PaymentOrBuilder {
// Construct using org.bitcoin.protocols.payments.Protos.Payment.newBuilder()
private Builder() {
super(DEFAULT_INSTANCE);
}
/**
* <pre>
* From PaymentDetails.merchant_data
* </pre>
*
* <code>optional bytes merchant_data = 1;</code>
* @return Whether the merchantData field is set.
*/
@java.lang.Override
public boolean hasMerchantData() {
return instance.hasMerchantData();
}
/**
* <pre>
* From PaymentDetails.merchant_data
* </pre>
*
* <code>optional bytes merchant_data = 1;</code>
* @return The merchantData.
*/
@java.lang.Override
public com.google.protobuf.ByteString getMerchantData() {
return instance.getMerchantData();
}
/**
* <pre>
* From PaymentDetails.merchant_data
* </pre>
*
* <code>optional bytes merchant_data = 1;</code>
* @param value The merchantData to set.
* @return This builder for chaining.
*/
public Builder setMerchantData(com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setMerchantData(value);
return this;
}
/**
* <pre>
* From PaymentDetails.merchant_data
* </pre>
*
* <code>optional bytes merchant_data = 1;</code>
* @return This builder for chaining.
*/
public Builder clearMerchantData() {
copyOnWrite();
instance.clearMerchantData();
return this;
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @return A list containing the transactions.
*/
@java.lang.Override
public java.util.List<com.google.protobuf.ByteString>
getTransactionsList() {
return java.util.Collections.unmodifiableList(
instance.getTransactionsList());
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @return The count of transactions.
*/
@java.lang.Override
public int getTransactionsCount() {
return instance.getTransactionsCount();
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @param index The index of the element to return.
* @return The transactions at the given index.
*/
@java.lang.Override
public com.google.protobuf.ByteString getTransactions(int index) {
return instance.getTransactions(index);
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @param value The transactions to set.
* @return This builder for chaining.
*/
public Builder setTransactions(
int index, com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setTransactions(index, value);
return this;
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @param value The transactions to add.
* @return This builder for chaining.
*/
public Builder addTransactions(com.google.protobuf.ByteString value) {
copyOnWrite();
instance.addTransactions(value);
return this;
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @param values The transactions to add.
* @return This builder for chaining.
*/
public Builder addAllTransactions(
java.lang.Iterable<? extends com.google.protobuf.ByteString> values) {
copyOnWrite();
instance.addAllTransactions(values);
return this;
}
/**
* <pre>
* Signed transactions that satisfy PaymentDetails.outputs
* </pre>
*
* <code>repeated bytes transactions = 2;</code>
* @return This builder for chaining.
*/
public Builder clearTransactions() {
copyOnWrite();
instance.clearTransactions();
return this;
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
@java.lang.Override
public java.util.List<org.bitcoin.protocols.payments.Protos.Output> getRefundToList() {
return java.util.Collections.unmodifiableList(
instance.getRefundToList());
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
@java.lang.Override
public int getRefundToCount() {
return instance.getRefundToCount();
}/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
@java.lang.Override
public org.bitcoin.protocols.payments.Protos.Output getRefundTo(int index) {
return instance.getRefundTo(index);
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
public Builder setRefundTo(
int index, org.bitcoin.protocols.payments.Protos.Output value) {
copyOnWrite();
instance.setRefundTo(index, value);
return this;
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
public Builder setRefundTo(
int index, org.bitcoin.protocols.payments.Protos.Output.Builder builderForValue) {
copyOnWrite();
instance.setRefundTo(index,
builderForValue.build());
return this;
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
public Builder addRefundTo(org.bitcoin.protocols.payments.Protos.Output value) {
copyOnWrite();
instance.addRefundTo(value);
return this;
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
public Builder addRefundTo(
int index, org.bitcoin.protocols.payments.Protos.Output value) {
copyOnWrite();
instance.addRefundTo(index, value);
return this;
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
public Builder addRefundTo(
org.bitcoin.protocols.payments.Protos.Output.Builder builderForValue) {
copyOnWrite();
instance.addRefundTo(builderForValue.build());
return this;
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
public Builder addRefundTo(
int index, org.bitcoin.protocols.payments.Protos.Output.Builder builderForValue) {
copyOnWrite();
instance.addRefundTo(index,
builderForValue.build());
return this;
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
public Builder addAllRefundTo(
java.lang.Iterable<? extends org.bitcoin.protocols.payments.Protos.Output> values) {
copyOnWrite();
instance.addAllRefundTo(values);
return this;
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
public Builder clearRefundTo() {
copyOnWrite();
instance.clearRefundTo();
return this;
}
/**
* <pre>
* Where to send refunds, if a refund is necessary
* </pre>
*
* <code>repeated .payments.Output refund_to = 3;</code>
*/
public Builder removeRefundTo(int index) {
copyOnWrite();
instance.removeRefundTo(index);
return this;
}
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @return Whether the memo field is set.
*/
@java.lang.Override
public boolean hasMemo() {
return instance.hasMemo();
}
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @return The memo.
*/
@java.lang.Override
public java.lang.String getMemo() {
return instance.getMemo();
}
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @return The bytes for memo.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getMemoBytes() {
return instance.getMemoBytes();
}
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @param value The memo to set.
* @return This builder for chaining.
*/
public Builder setMemo(
java.lang.String value) {
copyOnWrite();
instance.setMemo(value);
return this;
}
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @return This builder for chaining.
*/
public Builder clearMemo() {
copyOnWrite();
instance.clearMemo();
return this;
}
/**
* <pre>
* Human-readable message for the merchant
* </pre>
*
* <code>optional string memo = 4;</code>
* @param value The bytes for memo to set.
* @return This builder for chaining.
*/
public Builder setMemoBytes(
com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setMemoBytes(value);
return this;
}
// @@protoc_insertion_point(builder_scope:payments.Payment)
}
private byte memoizedIsInitialized = 2;
@java.lang.Override
@java.lang.SuppressWarnings({"unchecked", "fallthrough"})
protected final java.lang.Object dynamicMethod(
com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,
java.lang.Object arg0, java.lang.Object arg1) {
switch (method) {
case NEW_MUTABLE_INSTANCE: {
return new org.bitcoin.protocols.payments.Protos.Payment();
}
case NEW_BUILDER: {
return new Builder();
}
case BUILD_MESSAGE_INFO: {
java.lang.Object[] objects = new java.lang.Object[] {
"bitField0_",
"merchantData_",
"transactions_",
"refundTo_",
org.bitcoin.protocols.payments.Protos.Output.class,
"memo_",
};
java.lang.String info =
"\u0001\u0004\u0000\u0001\u0001\u0004\u0004\u0000\u0002\u0001\u0001\u100a\u0000\u0002" +
"\u001c\u0003\u041b\u0004\u1008\u0001";
return newMessageInfo(DEFAULT_INSTANCE, info, objects);
}
// fall through
case GET_DEFAULT_INSTANCE: {
return DEFAULT_INSTANCE;
}
case GET_PARSER: {
com.google.protobuf.Parser<org.bitcoin.protocols.payments.Protos.Payment> parser = PARSER;
if (parser == null) {
synchronized (org.bitcoin.protocols.payments.Protos.Payment.class) {
parser = PARSER;
if (parser == null) {
parser =
new DefaultInstanceBasedParser<org.bitcoin.protocols.payments.Protos.Payment>(
DEFAULT_INSTANCE);
PARSER = parser;
}
}
}
return parser;
}
case GET_MEMOIZED_IS_INITIALIZED: {
return memoizedIsInitialized;
}
case SET_MEMOIZED_IS_INITIALIZED: {
memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1);
return null;
}
}
throw new UnsupportedOperationException();
}
// @@protoc_insertion_point(class_scope:payments.Payment)
private static final org.bitcoin.protocols.payments.Protos.Payment DEFAULT_INSTANCE;
static {
Payment defaultInstance = new Payment();
// New instances are implicitly immutable so no need to make
// immutable.
DEFAULT_INSTANCE = defaultInstance;
com.google.protobuf.GeneratedMessageLite.registerDefaultInstance(
Payment.class, defaultInstance);
}
public static org.bitcoin.protocols.payments.Protos.Payment getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static volatile com.google.protobuf.Parser<Payment> PARSER;
public static com.google.protobuf.Parser<Payment> parser() {
return DEFAULT_INSTANCE.getParserForType();
}
}
public interface PaymentACKOrBuilder extends
// @@protoc_insertion_point(interface_extends:payments.PaymentACK)
com.google.protobuf.MessageLiteOrBuilder {
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
* @return Whether the payment field is set.
*/
boolean hasPayment();
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
* @return The payment.
*/
org.bitcoin.protocols.payments.Protos.Payment getPayment();
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @return Whether the memo field is set.
*/
boolean hasMemo();
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @return The memo.
*/
java.lang.String getMemo();
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @return The bytes for memo.
*/
com.google.protobuf.ByteString
getMemoBytes();
}
/**
* Protobuf type {@code payments.PaymentACK}
*/
public static final class PaymentACK extends
com.google.protobuf.GeneratedMessageLite<
PaymentACK, PaymentACK.Builder> implements
// @@protoc_insertion_point(message_implements:payments.PaymentACK)
PaymentACKOrBuilder {
private PaymentACK() {
memo_ = "";
}
private int bitField0_;
public static final int PAYMENT_FIELD_NUMBER = 1;
private org.bitcoin.protocols.payments.Protos.Payment payment_;
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
*/
@java.lang.Override
public boolean hasPayment() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
*/
@java.lang.Override
public org.bitcoin.protocols.payments.Protos.Payment getPayment() {
return payment_ == null ? org.bitcoin.protocols.payments.Protos.Payment.getDefaultInstance() : payment_;
}
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
*/
private void setPayment(org.bitcoin.protocols.payments.Protos.Payment value) {
value.getClass();
payment_ = value;
bitField0_ |= 0x00000001;
}
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
*/
@java.lang.SuppressWarnings({"ReferenceEquality"})
private void mergePayment(org.bitcoin.protocols.payments.Protos.Payment value) {
value.getClass();
if (payment_ != null &&
payment_ != org.bitcoin.protocols.payments.Protos.Payment.getDefaultInstance()) {
payment_ =
org.bitcoin.protocols.payments.Protos.Payment.newBuilder(payment_).mergeFrom(value).buildPartial();
} else {
payment_ = value;
}
bitField0_ |= 0x00000001;
}
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
*/
private void clearPayment() { payment_ = null;
bitField0_ = (bitField0_ & ~0x00000001);
}
public static final int MEMO_FIELD_NUMBER = 2;
private java.lang.String memo_;
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @return Whether the memo field is set.
*/
@java.lang.Override
public boolean hasMemo() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @return The memo.
*/
@java.lang.Override
public java.lang.String getMemo() {
return memo_;
}
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @return The bytes for memo.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getMemoBytes() {
return com.google.protobuf.ByteString.copyFromUtf8(memo_);
}
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @param value The memo to set.
*/
private void setMemo(
java.lang.String value) {
java.lang.Class<?> valueClass = value.getClass();
bitField0_ |= 0x00000002;
memo_ = value;
}
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
*/
private void clearMemo() {
bitField0_ = (bitField0_ & ~0x00000002);
memo_ = getDefaultInstance().getMemo();
}
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @param value The bytes for memo to set.
*/
private void setMemoBytes(
com.google.protobuf.ByteString value) {
memo_ = value.toStringUtf8();
bitField0_ |= 0x00000002;
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data);
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, data, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return parseDelimitedFrom(DEFAULT_INSTANCE, input, extensionRegistry);
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input);
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageLite.parseFrom(
DEFAULT_INSTANCE, input, extensionRegistry);
}
public static Builder newBuilder() {
return (Builder) DEFAULT_INSTANCE.createBuilder();
}
public static Builder newBuilder(org.bitcoin.protocols.payments.Protos.PaymentACK prototype) {
return (Builder) DEFAULT_INSTANCE.createBuilder(prototype);
}
/**
* Protobuf type {@code payments.PaymentACK}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageLite.Builder<
org.bitcoin.protocols.payments.Protos.PaymentACK, Builder> implements
// @@protoc_insertion_point(builder_implements:payments.PaymentACK)
org.bitcoin.protocols.payments.Protos.PaymentACKOrBuilder {
// Construct using org.bitcoin.protocols.payments.Protos.PaymentACK.newBuilder()
private Builder() {
super(DEFAULT_INSTANCE);
}
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
*/
@java.lang.Override
public boolean hasPayment() {
return instance.hasPayment();
}
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
*/
@java.lang.Override
public org.bitcoin.protocols.payments.Protos.Payment getPayment() {
return instance.getPayment();
}
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
*/
public Builder setPayment(org.bitcoin.protocols.payments.Protos.Payment value) {
copyOnWrite();
instance.setPayment(value);
return this;
}
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
*/
public Builder setPayment(
org.bitcoin.protocols.payments.Protos.Payment.Builder builderForValue) {
copyOnWrite();
instance.setPayment(builderForValue.build());
return this;
}
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
*/
public Builder mergePayment(org.bitcoin.protocols.payments.Protos.Payment value) {
copyOnWrite();
instance.mergePayment(value);
return this;
}
/**
* <pre>
* Payment message that triggered this ACK
* </pre>
*
* <code>required .payments.Payment payment = 1;</code>
*/
public Builder clearPayment() { copyOnWrite();
instance.clearPayment();
return this;
}
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @return Whether the memo field is set.
*/
@java.lang.Override
public boolean hasMemo() {
return instance.hasMemo();
}
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @return The memo.
*/
@java.lang.Override
public java.lang.String getMemo() {
return instance.getMemo();
}
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @return The bytes for memo.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getMemoBytes() {
return instance.getMemoBytes();
}
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @param value The memo to set.
* @return This builder for chaining.
*/
public Builder setMemo(
java.lang.String value) {
copyOnWrite();
instance.setMemo(value);
return this;
}
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @return This builder for chaining.
*/
public Builder clearMemo() {
copyOnWrite();
instance.clearMemo();
return this;
}
/**
* <pre>
* human-readable message for customer
* </pre>
*
* <code>optional string memo = 2;</code>
* @param value The bytes for memo to set.
* @return This builder for chaining.
*/
public Builder setMemoBytes(
com.google.protobuf.ByteString value) {
copyOnWrite();
instance.setMemoBytes(value);
return this;
}
// @@protoc_insertion_point(builder_scope:payments.PaymentACK)
}
private byte memoizedIsInitialized = 2;
@java.lang.Override
@java.lang.SuppressWarnings({"unchecked", "fallthrough"})
protected final java.lang.Object dynamicMethod(
com.google.protobuf.GeneratedMessageLite.MethodToInvoke method,
java.lang.Object arg0, java.lang.Object arg1) {
switch (method) {
case NEW_MUTABLE_INSTANCE: {
return new org.bitcoin.protocols.payments.Protos.PaymentACK();
}
case NEW_BUILDER: {
return new Builder();
}
case BUILD_MESSAGE_INFO: {
java.lang.Object[] objects = new java.lang.Object[] {
"bitField0_",
"payment_",
"memo_",
};
java.lang.String info =
"\u0001\u0002\u0000\u0001\u0001\u0002\u0002\u0000\u0000\u0001\u0001\u1509\u0000\u0002" +
"\u1008\u0001";
return newMessageInfo(DEFAULT_INSTANCE, info, objects);
}
// fall through
case GET_DEFAULT_INSTANCE: {
return DEFAULT_INSTANCE;
}
case GET_PARSER: {
com.google.protobuf.Parser<org.bitcoin.protocols.payments.Protos.PaymentACK> parser = PARSER;
if (parser == null) {
synchronized (org.bitcoin.protocols.payments.Protos.PaymentACK.class) {
parser = PARSER;
if (parser == null) {
parser =
new DefaultInstanceBasedParser<org.bitcoin.protocols.payments.Protos.PaymentACK>(
DEFAULT_INSTANCE);
PARSER = parser;
}
}
}
return parser;
}
case GET_MEMOIZED_IS_INITIALIZED: {
return memoizedIsInitialized;
}
case SET_MEMOIZED_IS_INITIALIZED: {
memoizedIsInitialized = (byte) (arg0 == null ? 0 : 1);
return null;
}
}
throw new UnsupportedOperationException();
}
// @@protoc_insertion_point(class_scope:payments.PaymentACK)
private static final org.bitcoin.protocols.payments.Protos.PaymentACK DEFAULT_INSTANCE;
static {
PaymentACK defaultInstance = new PaymentACK();
// New instances are implicitly immutable so no need to make
// immutable.
DEFAULT_INSTANCE = defaultInstance;
com.google.protobuf.GeneratedMessageLite.registerDefaultInstance(
PaymentACK.class, defaultInstance);
}
public static org.bitcoin.protocols.payments.Protos.PaymentACK getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static volatile com.google.protobuf.Parser<PaymentACK> PARSER;
public static com.google.protobuf.Parser<PaymentACK> parser() {
return DEFAULT_INSTANCE.getParserForType();
}
}
static {
}
// @@protoc_insertion_point(outer_class_scope)
}
| 145,526
| 29.812407
| 118
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/signers/TransactionSigner.java
|
/*
* Copyright 2014 Kosta Korenkov
*
* 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.
*/
package org.bitcoinj.signers;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.script.Script;
import org.bitcoinj.wallet.KeyBag;
import org.bitcoinj.wallet.Wallet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>Implementations of this interface are intended to sign inputs of the given transaction. Given transaction may already
* be partially signed or somehow altered by other signers.</p>
* <p>To make use of the signer, you need to add it into the wallet by
* calling {@link Wallet#addTransactionSigner(TransactionSigner)}. Signer will be serialized
* along with the wallet data. In order for a wallet to recreate signer after deserialization, each signer
* should have no-args constructor</p>
*/
public interface TransactionSigner {
/**
* This class wraps transaction proposed to complete keeping a metadata that may be updated, used and effectively
* shared by transaction signers.
*/
class ProposedTransaction {
public final Transaction partialTx;
/**
* HD key paths used for each input to derive a signing key. It's useful for multisig inputs only.
* The keys used to create a single P2SH address have the same derivation path, so to use a correct key each signer
* has to know a derivation path of signing keys used by previous signers. For each input signers will use the
* same derivation path and we need to store only one key path per input. As TransactionInput is mutable, inputs
* are identified by their scriptPubKeys (keys in this map).
*/
public final Map<Script, List<ChildNumber>> keyPaths;
public ProposedTransaction(Transaction partialTx) {
this.partialTx = partialTx;
this.keyPaths = new HashMap<>();
}
}
class MissingSignatureException extends RuntimeException {
}
/**
* Returns true if this signer is ready to be used.
*/
boolean isReady();
/**
* Signs given transaction's inputs.
* Returns true if signer is compatible with given transaction (can do something meaningful with it).
* Otherwise this method returns false
*/
boolean signInputs(ProposedTransaction propTx, KeyBag keyBag);
}
| 2,911
| 36.333333
| 123
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/signers/package-info.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
/**
* Transaction signers know how to calculate signatures over transactions in different contexts, for example, using
* local private keys or fetching them from remote servers. The {@link org.bitcoinj.wallet.Wallet} class uses these
* when sending money.
*/
package org.bitcoinj.signers;
| 907
| 38.478261
| 115
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/signers/CustomTransactionSigner.java
|
/*
* Copyright 2014 Kosta Korenkov
* Copyright 2019 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.signers;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.TransactionSignature;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.ScriptException;
import org.bitcoinj.script.ScriptPattern;
import org.bitcoinj.wallet.KeyBag;
import org.bitcoinj.wallet.RedeemData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Objects;
/**
* <p>This signer may be used as a template for creating custom multisig transaction signers.</p>
* <p>
* Concrete implementations have to implement {@link #getSignature(Sha256Hash, List)}
* method returning a signature and a public key of the keypair used to created that signature.
* It's up to custom implementation where to locate signatures: it may be a network connection,
* some local API or something else.
* </p>
*/
public abstract class CustomTransactionSigner implements TransactionSigner {
private static final Logger log = LoggerFactory.getLogger(CustomTransactionSigner.class);
@Override
public boolean isReady() {
return true;
}
@Override
public boolean signInputs(ProposedTransaction propTx, KeyBag keyBag) {
Transaction tx = propTx.partialTx;
int numInputs = tx.getInputs().size();
for (int i = 0; i < numInputs; i++) {
TransactionInput txIn = tx.getInput(i);
TransactionOutput txOut = txIn.getConnectedOutput();
if (txOut == null) {
continue;
}
Script scriptPubKey = txOut.getScriptPubKey();
if (!ScriptPattern.isP2SH(scriptPubKey)) {
log.warn("CustomTransactionSigner works only with P2SH transactions");
return false;
}
Script inputScript = Objects.requireNonNull(txIn.getScriptSig());
try {
// We assume if its already signed, its hopefully got a SIGHASH type that will not invalidate when
// we sign missing pieces (to check this would require either assuming any signatures are signing
// standard output types or a way to get processed signatures out of script execution)
txIn.getScriptSig().correctlySpends(tx, i, txIn.getWitness(), txOut.getValue(), txOut.getScriptPubKey(),
Script.ALL_VERIFY_FLAGS);
log.warn("Input {} already correctly spends output, assuming SIGHASH type used will be safe and skipping signing.", i);
continue;
} catch (ScriptException e) {
// Expected.
}
RedeemData redeemData = txIn.getConnectedRedeemData(keyBag);
if (redeemData == null) {
log.warn("No redeem data found for input {}", i);
continue;
}
Sha256Hash sighash = tx.hashForSignature(i, redeemData.redeemScript, Transaction.SigHash.ALL, false);
SignatureAndKey sigKey = getSignature(sighash, propTx.keyPaths.get(scriptPubKey));
TransactionSignature txSig = new TransactionSignature(sigKey.sig, Transaction.SigHash.ALL, false);
int sigIndex = inputScript.getSigInsertionIndex(sighash, sigKey.pubKey);
inputScript = scriptPubKey.getScriptSigWithSignature(inputScript, txSig.encodeToBitcoin(), sigIndex);
txIn.setScriptSig(inputScript);
}
return true;
}
protected abstract SignatureAndKey getSignature(Sha256Hash sighash, List<ChildNumber> derivationPath);
public static class SignatureAndKey {
public final ECKey.ECDSASignature sig;
public final ECKey pubKey;
public SignatureAndKey(ECKey.ECDSASignature sig, ECKey pubKey) {
this.sig = sig;
this.pubKey = pubKey;
}
}
}
| 4,651
| 39.452174
| 135
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/signers/LocalTransactionSigner.java
|
/*
* Copyright 2014 Kosta Korenkov
* Copyright 2019 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.signers;
import org.bitcoinj.base.Coin;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionOutput;
import org.bitcoinj.core.TransactionWitness;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.crypto.TransactionSignature;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.Script.VerifyFlag;
import org.bitcoinj.script.ScriptBuilder;
import org.bitcoinj.script.ScriptException;
import org.bitcoinj.script.ScriptPattern;
import org.bitcoinj.wallet.KeyBag;
import org.bitcoinj.wallet.RedeemData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.EnumSet;
/**
* <p>{@link TransactionSigner} implementation for signing inputs using keys from provided {@link KeyBag}.</p>
* <p>This signer doesn't create input scripts for tx inputs. Instead it expects inputs to contain scripts with
* empty sigs and replaces one of the empty sigs with calculated signature.
* </p>
* <p>This signer is always implicitly added into every wallet and it is the first signer to be executed during tx
* completion. As the first signer to create a signature, it stores derivation path of the signing key in a given
* {@link TransactionSigner.ProposedTransaction} object that will be also passed then to the next signer in chain. This allows other
* signers to use correct signing key for P2SH inputs, because all the keys involved in a single P2SH address have
* the same derivation path.</p>
* <p>This signer always uses {@link Transaction.SigHash#ALL} signing mode.</p>
*/
public class LocalTransactionSigner implements TransactionSigner {
private static final Logger log = LoggerFactory.getLogger(LocalTransactionSigner.class);
/**
* Verify flags that are safe to use when testing if an input is already
* signed.
*/
private static final EnumSet<VerifyFlag> MINIMUM_VERIFY_FLAGS = EnumSet.of(VerifyFlag.P2SH,
VerifyFlag.NULLDUMMY);
@Override
public boolean isReady() {
return true;
}
@Override
public boolean signInputs(ProposedTransaction propTx, KeyBag keyBag) {
Transaction tx = propTx.partialTx;
int numInputs = tx.getInputs().size();
for (int i = 0; i < numInputs; i++) {
TransactionInput txIn = tx.getInput(i);
final TransactionOutput connectedOutput = txIn.getConnectedOutput();
if (connectedOutput == null) {
log.warn("Missing connected output, assuming input {} is already signed.", i);
continue;
}
Script scriptPubKey = connectedOutput.getScriptPubKey();
try {
// We assume if its already signed, its hopefully got a SIGHASH type that will not invalidate when
// we sign missing pieces (to check this would require either assuming any signatures are signing
// standard output types or a way to get processed signatures out of script execution)
txIn.getScriptSig().correctlySpends(tx, i, txIn.getWitness(), connectedOutput.getValue(),
connectedOutput.getScriptPubKey(), MINIMUM_VERIFY_FLAGS);
log.warn("Input {} already correctly spends output, assuming SIGHASH type used will be safe and skipping signing.", i);
continue;
} catch (ScriptException e) {
// Expected.
}
RedeemData redeemData = txIn.getConnectedRedeemData(keyBag);
// For P2SH inputs we need to share derivation path of the signing key with other signers, so that they
// use correct key to calculate their signatures.
// Married keys all have the same derivation path, so we can safely just take first one here.
ECKey pubKey = redeemData.keys.get(0);
if (pubKey instanceof DeterministicKey)
propTx.keyPaths.put(scriptPubKey, (((DeterministicKey) pubKey).getPath()));
// locate private key in redeem data. For P2PKH and P2PK inputs RedeemData will always contain
// only one key (with private bytes). For P2SH inputs RedeemData will contain multiple keys, one of which MAY
// have private bytes
ECKey key = redeemData.getFullKey();
if (key == null) {
log.warn("No local key found for input {}", i);
continue;
}
Script inputScript = txIn.getScriptSig();
// script here would be either a standard CHECKSIG program for P2PKH or P2PK inputs or
// a CHECKMULTISIG program for P2SH inputs
byte[] script = redeemData.redeemScript.program();
try {
if (ScriptPattern.isP2PK(scriptPubKey) || ScriptPattern.isP2PKH(scriptPubKey)
|| ScriptPattern.isP2SH(scriptPubKey)) {
TransactionSignature signature = tx.calculateSignature(i, key, script, Transaction.SigHash.ALL,
false);
// at this point we have incomplete inputScript with OP_0 in place of one or more signatures. We
// already have calculated the signature using the local key and now need to insert it in the
// correct place within inputScript. For P2PKH and P2PK script there is only one signature and it
// always goes first in an inputScript (sigIndex = 0). In P2SH input scripts we need to figure out
// our relative position relative to other signers. Since we don't have that information at this
// point, and since we always run first, we have to depend on the other signers rearranging the
// signatures as needed. Therefore, always place as first signature.
int sigIndex = 0;
inputScript = scriptPubKey.getScriptSigWithSignature(inputScript, signature.encodeToBitcoin(),
sigIndex);
txIn.setScriptSig(inputScript);
txIn.setWitness(null);
} else if (ScriptPattern.isP2WPKH(scriptPubKey)) {
Script scriptCode = ScriptBuilder.createP2PKHOutputScript(key);
Coin value = txIn.getValue();
TransactionSignature signature = tx.calculateWitnessSignature(i, key, scriptCode, value,
Transaction.SigHash.ALL, false);
txIn.setScriptSig(ScriptBuilder.createEmpty());
txIn.setWitness(TransactionWitness.redeemP2WPKH(signature, key));
} else {
throw new IllegalStateException(script.toString());
}
} catch (ECKey.KeyIsEncryptedException e) {
throw e;
} catch (ECKey.MissingPrivateKeyException e) {
log.warn("No private key in keypair for input {}", i);
}
}
return true;
}
}
| 7,716
| 49.437908
| 135
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/signers/MissingSigResolutionSigner.java
|
/*
* Copyright 2014 Kosta Korenkov
* Copyright 2019 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.signers;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.crypto.ECKey;
import org.bitcoinj.core.TransactionInput;
import org.bitcoinj.core.TransactionWitness;
import org.bitcoinj.crypto.TransactionSignature;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.ScriptChunk;
import org.bitcoinj.script.ScriptPattern;
import org.bitcoinj.wallet.KeyBag;
import org.bitcoinj.wallet.Wallet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This transaction signer resolves missing signatures in accordance with the given {@link Wallet.MissingSigsMode}.
* If missingSigsMode is USE_OP_ZERO this signer does nothing assuming missing signatures are already presented in
* scriptSigs as OP_0.
* In MissingSigsMode.THROW mode this signer will throw an exception. It would be MissingSignatureException
* for P2SH or MissingPrivateKeyException for other transaction types.
*/
public class MissingSigResolutionSigner implements TransactionSigner {
private static final Logger log = LoggerFactory.getLogger(MissingSigResolutionSigner.class);
private final Wallet.MissingSigsMode missingSigsMode;
public MissingSigResolutionSigner() {
this(Wallet.MissingSigsMode.USE_DUMMY_SIG);
}
public MissingSigResolutionSigner(Wallet.MissingSigsMode missingSigsMode) {
this.missingSigsMode = missingSigsMode;
}
@Override
public boolean isReady() {
return true;
}
@Override
public boolean signInputs(ProposedTransaction propTx, KeyBag keyBag) {
if (missingSigsMode == Wallet.MissingSigsMode.USE_OP_ZERO)
return true;
int numInputs = propTx.partialTx.getInputs().size();
byte[] dummySig = TransactionSignature.dummy().encodeToBitcoin();
for (int i = 0; i < numInputs; i++) {
TransactionInput txIn = propTx.partialTx.getInput(i);
if (txIn.getConnectedOutput() == null) {
log.warn("Missing connected output, assuming input {} is already signed.", i);
continue;
}
Script scriptPubKey = txIn.getConnectedOutput().getScriptPubKey();
Script inputScript = txIn.getScriptSig();
if (ScriptPattern.isP2SH(scriptPubKey) || ScriptPattern.isSentToMultisig(scriptPubKey)) {
int sigSuffixCount = ScriptPattern.isP2SH(scriptPubKey) ? 1 : 0;
// all chunks except the first one (OP_0) and the last (redeem script) are signatures
for (int j = 1; j < inputScript.chunks().size() - sigSuffixCount; j++) {
ScriptChunk scriptChunk = inputScript.chunks().get(j);
if (scriptChunk.equalsOpCode(0)) {
if (missingSigsMode == Wallet.MissingSigsMode.THROW) {
throw new MissingSignatureException();
} else if (missingSigsMode == Wallet.MissingSigsMode.USE_DUMMY_SIG) {
txIn.setScriptSig(scriptPubKey.getScriptSigWithSignature(inputScript, dummySig, j - 1));
}
}
}
} else if (ScriptPattern.isP2PK(scriptPubKey) || ScriptPattern.isP2PKH(scriptPubKey)) {
if (inputScript.chunks().get(0).equalsOpCode(0)) {
if (missingSigsMode == Wallet.MissingSigsMode.THROW) {
throw new ECKey.MissingPrivateKeyException();
} else if (missingSigsMode == Wallet.MissingSigsMode.USE_DUMMY_SIG) {
txIn.setScriptSig(scriptPubKey.getScriptSigWithSignature(inputScript, dummySig, 0));
}
}
} else if (ScriptPattern.isP2WPKH(scriptPubKey)) {
if (txIn.getWitness() == null || txIn.getWitness().equals(TransactionWitness.EMPTY)
|| txIn.getWitness().getPush(0).length == 0) {
if (missingSigsMode == Wallet.MissingSigsMode.THROW) {
throw new ECKey.MissingPrivateKeyException();
} else if (missingSigsMode == Wallet.MissingSigsMode.USE_DUMMY_SIG) {
ECKey key = keyBag.findKeyFromPubKeyHash(
ScriptPattern.extractHashFromP2WH(scriptPubKey), ScriptType.P2WPKH);
txIn.setWitness(TransactionWitness.redeemP2WPKH(TransactionSignature.dummy(), key));
}
}
} else {
throw new IllegalStateException("cannot handle: " + scriptPubKey);
}
}
return true;
}
}
| 5,268
| 45.628319
| 116
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/DeterministicHierarchy.java
|
/*
* Copyright 2013 Matija Mazi.
*
* 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.
*/
package org.bitcoinj.crypto;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
// TODO: This whole API feels a bit object heavy. Do we really need ChildNumber and so many maps, etc?
// TODO: Should we be representing this using an actual tree arrangement in memory instead of a bunch of hashmaps?
/**
* <p>A DeterministicHierarchy calculates and keeps a whole tree (hierarchy) of keys originating from a single
* root key. This implements part of the BIP 32 specification. A deterministic key tree is useful because
* Bitcoin's privacy system require new keys to be created for each transaction, but managing all these
* keys quickly becomes unwieldy. In particular it becomes hard to back up and distribute them. By having
* a way to derive random-looking but deterministic keys we can make wallet backup simpler and gain the
* ability to hand out {@link DeterministicKey}s to other people who can then create new addresses
* on the fly, without having to contact us.</p>
*
* <p>The hierarchy is started from a single root key, and a location in the tree is given by a path which
* is a list of {@link ChildNumber}s.</p>
*/
public class DeterministicHierarchy {
private final Map<HDPath, DeterministicKey> keys = new HashMap<>();
private final HDPath rootPath;
// Keep track of how many child keys each node has. This is kind of weak.
private final Map<HDPath, ChildNumber> lastChildNumbers = new HashMap<>();
public static final Instant BIP32_STANDARDISATION_TIME = Instant.ofEpochSecond(1369267200);
/**
* @deprecated Use {@link #BIP32_STANDARDISATION_TIME}
*/
@Deprecated
public static final int BIP32_STANDARDISATION_TIME_SECS = Math.toIntExact(BIP32_STANDARDISATION_TIME.getEpochSecond());
/**
* Constructs a new hierarchy rooted at the given key. Note that this does not have to be the top of the tree.
* You can construct a DeterministicHierarchy for a subtree of a larger tree that you may not own.
*/
public DeterministicHierarchy(DeterministicKey rootKey) {
putKey(rootKey);
rootPath = rootKey.getPath();
}
/**
* Inserts a key into the hierarchy. Used during deserialization: you normally don't need this. Keys must be
* inserted in order.
*/
public final void putKey(DeterministicKey key) {
HDPath path = key.getPath();
// Update our tracking of what the next child in each branch of the tree should be. Just assume that keys are
// inserted in order here.
final DeterministicKey parent = key.getParent();
if (parent != null)
lastChildNumbers.put(parent.getPath(), key.getChildNumber());
keys.put(path, key);
}
/**
* Inserts a list of keys into the hierarchy
* @param keys A list of keys to put in the hierarchy
*/
public final void putKeys(List<DeterministicKey> keys) {
keys.forEach(this::putKey);
}
/**
* Returns a key for the given path, optionally creating it.
*
* @param path the path to the key
* @param relativePath whether the path is relative to the root path
* @param create whether the key corresponding to path should be created (with any necessary ancestors) if it doesn't exist already
* @return next newly created key using the child derivation function
* @throws IllegalArgumentException if create is false and the path was not found.
*/
public DeterministicKey get(List<ChildNumber> path, boolean relativePath, boolean create) {
HDPath inputPath = HDPath.M(path);
HDPath absolutePath = relativePath
? rootPath.extend(path)
: inputPath;
if (!keys.containsKey(absolutePath)) {
if (!create)
throw new IllegalArgumentException(String.format(Locale.US, "No key found for %s path %s.",
relativePath ? "relative" : "absolute", inputPath.toString()));
checkArgument(absolutePath.size() > 0, () -> "can't derive the master key: nothing to derive from");
DeterministicKey parent = get(absolutePath.subList(0, absolutePath.size() - 1), false, true);
putKey(HDKeyDerivation.deriveChildKey(parent, absolutePath.get(absolutePath.size() - 1)));
}
return keys.get(absolutePath);
}
/**
* Extends the tree by calculating the next key that hangs off the given parent path. For example, if you pass a
* path of 1/2 here and there are already keys 1/2/1 and 1/2/2 then it will derive 1/2/3.
*
* @param parentPath the path to the parent
* @param relative whether the path is relative to the root path
* @param createParent whether the parent corresponding to path should be created (with any necessary ancestors) if it doesn't exist already
* @param privateDerivation whether to use private or public derivation
* @return next newly created key using the child derivation function
* @throws IllegalArgumentException if the parent doesn't exist and createParent is false.
*/
public DeterministicKey deriveNextChild(List<ChildNumber> parentPath, boolean relative, boolean createParent, boolean privateDerivation) {
DeterministicKey parent = get(parentPath, relative, createParent);
int nAttempts = 0;
while (nAttempts++ < HDKeyDerivation.MAX_CHILD_DERIVATION_ATTEMPTS) {
try {
ChildNumber createChildNumber = getNextChildNumberToDerive(parent.getPath(), privateDerivation);
return deriveChild(parent, createChildNumber);
} catch (HDDerivationException ignore) { }
}
throw new HDDerivationException("Maximum number of child derivation attempts reached, this is probably an indication of a bug.");
}
private ChildNumber getNextChildNumberToDerive(HDPath path, boolean privateDerivation) {
ChildNumber lastChildNumber = lastChildNumbers.get(path);
ChildNumber nextChildNumber = new ChildNumber(lastChildNumber != null ? lastChildNumber.num() + 1 : 0, privateDerivation);
lastChildNumbers.put(path, nextChildNumber);
return nextChildNumber;
}
public int getNumChildren(HDPath path) {
final ChildNumber cn = lastChildNumbers.get(path);
if (cn == null)
return 0;
else
return cn.num() + 1; // children start with zero based childnumbers
}
/**
* Extends the tree by calculating the requested child for the given path. For example, to get the key at position
* 1/2/3 you would pass 1/2 as the parent path and 3 as the child number.
*
* @param parentPath the path to the parent
* @param relative whether the path is relative to the root path
* @param createParent whether the parent corresponding to path should be created (with any necessary ancestors) if it doesn't exist already
* @return the requested key.
* @throws IllegalArgumentException if the parent doesn't exist and createParent is false.
*/
public DeterministicKey deriveChild(List<ChildNumber> parentPath, boolean relative, boolean createParent, ChildNumber createChildNumber) {
return deriveChild(get(parentPath, relative, createParent), createChildNumber);
}
private DeterministicKey deriveChild(DeterministicKey parent, ChildNumber createChildNumber) {
DeterministicKey childKey = HDKeyDerivation.deriveChildKey(parent, createChildNumber);
putKey(childKey);
return childKey;
}
/**
* Returns the root key that the {@link DeterministicHierarchy} was created with.
*/
public DeterministicKey getRootKey() {
return get(rootPath, false, false);
}
}
| 8,470
| 46.858757
| 144
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/HDPath.java
|
/*
* Copyright 2019 Michael Sean Gilligan.
*
* 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.
*/
package org.bitcoinj.crypto;
import org.bitcoinj.base.internal.StreamUtils;
import org.bitcoinj.base.internal.InternalUtils;
import javax.annotation.Nonnull;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* HD Key derivation path. {@code HDPath} can be used to represent a full path or a relative path.
* The {@code hasPrivateKey} {@code boolean} is used for rendering to {@code String}
* but (at present) not much else. It defaults to {@code false} which is the preferred setting for a relative path.
* <p>
* {@code HDPath} is immutable and uses the {@code Collections.UnmodifiableList} type internally.
* <p>
* It implements {@code java.util.List<ChildNumber>} to ease migration
* from the previous implementation. When an {@code HDPath} is returned you can treat it as a {@code List<ChildNumber>}
* where necessary in your code. Although it is recommended to use the {@code HDPath} type for clarity and for
* access to {@code HDPath}-specific functionality.
* <p>
* Note that it is possible for {@code HDPath} to be an empty list.
* <p>
* Take note of the overloaded factory methods {@link HDPath#M()} and {@link HDPath#m()}. These can be used to very
* concisely create HDPath objects (especially when statically imported.)
*/
public class HDPath extends AbstractList<ChildNumber> {
private static final char PREFIX_PRIVATE = 'm';
private static final char PREFIX_PUBLIC = 'M';
private static final char SEPARATOR = '/';
private static final InternalUtils.Splitter SEPARATOR_SPLITTER = s -> Stream.of(s.split("/"))
.map(String::trim)
.collect(Collectors.toList());
protected final boolean hasPrivateKey;
protected final List<ChildNumber> unmodifiableList;
/** Partial path with BIP44 purpose */
public static final HDPath BIP44_PARENT = m(ChildNumber.PURPOSE_BIP44);
/** Partial path with BIP84 purpose */
public static final HDPath BIP84_PARENT = m(ChildNumber.PURPOSE_BIP84);
/** Partial path with BIP86 purpose */
public static final HDPath BIP86_PARENT = m(ChildNumber.PURPOSE_BIP86);
/**
* Constructs a path for a public or private key. Should probably be a private constructor.
*
* @param hasPrivateKey Whether it is a path to a private key or not
* @param list List of children in the path
*/
public HDPath(boolean hasPrivateKey, List<ChildNumber> list) {
this.hasPrivateKey = hasPrivateKey;
this.unmodifiableList = Collections.unmodifiableList(list);
}
/**
* Constructs a path for a public key.
*
* @param list List of children in the path
* @deprecated Use {@link HDPath#M(List)} or {@link HDPath#m(List)} instead
*/
@Deprecated
public HDPath(List<ChildNumber> list) {
this(false, list);
}
/**
* Returns a path for a public or private key.
*
* @param hasPrivateKey Whether it is a path to a private key or not
* @param list List of children in the path
*/
private static HDPath of(boolean hasPrivateKey, List<ChildNumber> list) {
return new HDPath(hasPrivateKey, list);
}
/**
* Deserialize a list of integers into an HDPath (internal use only)
* @param integerList A list of integers (what we use in ProtoBuf for an HDPath)
* @return a deserialized HDPath (hasPrivateKey is false/unknown)
*/
public static HDPath deserialize(List<Integer> integerList) {
return integerList.stream()
.map(ChildNumber::new)
.collect(Collectors.collectingAndThen(Collectors.toList(), HDPath::M));
}
/**
* Returns a path for a public key.
*
* @param list List of children in the path
*/
public static HDPath M(List<ChildNumber> list) {
return HDPath.of(false, list);
}
/**
* Returns an empty path for a public key.
*/
public static HDPath M() {
return HDPath.M(Collections.emptyList());
}
/**
* Returns a path for a public key.
*
* @param childNumber Single child in path
*/
public static HDPath M(ChildNumber childNumber) {
return HDPath.M(Collections.singletonList(childNumber));
}
/**
* Returns a path for a public key.
*
* @param children Children in the path
*/
public static HDPath M(ChildNumber... children) {
return HDPath.M(Arrays.asList(children));
}
/**
* Returns a path for a private key.
*
* @param list List of children in the path
*/
public static HDPath m(List<ChildNumber> list) {
return HDPath.of(true, list);
}
/**
* Returns an empty path for a private key.
*/
public static HDPath m() {
return HDPath.m(Collections.emptyList());
}
/**
* Returns a path for a private key.
*
* @param childNumber Single child in path
*/
public static HDPath m(ChildNumber childNumber) {
return HDPath.m(Collections.singletonList(childNumber));
}
/**
* Returns a path for a private key.
*
* @param children Children in the path
*/
public static HDPath m(ChildNumber... children) {
return HDPath.m(Arrays.asList(children));
}
/**
* Create an HDPath from a path string. The path string is a human-friendly representation of the deterministic path. For example:
*
* "44H / 0H / 0H / 1 / 1"
*
* Where a letter "H" means hardened key. Spaces are ignored.
*/
public static HDPath parsePath(@Nonnull String path) {
List<String> parsedNodes = SEPARATOR_SPLITTER.splitToList(path);
boolean hasPrivateKey = false;
if (!parsedNodes.isEmpty()) {
final String firstNode = parsedNodes.get(0);
if (firstNode.equals(Character.toString(PREFIX_PRIVATE)))
hasPrivateKey = true;
if (hasPrivateKey || firstNode.equals(Character.toString(PREFIX_PUBLIC)))
parsedNodes.remove(0);
}
List<ChildNumber> nodes = new ArrayList<>(parsedNodes.size());
for (String n : parsedNodes) {
if (n.isEmpty()) continue;
boolean isHard = n.endsWith("H");
if (isHard) n = n.substring(0, n.length() - 1).trim();
int nodeNumber = Integer.parseInt(n);
nodes.add(new ChildNumber(nodeNumber, isHard));
}
return new HDPath(hasPrivateKey, nodes);
}
/**
* Is this a path to a private key?
*
* @return true if yes, false if no or a partial path
*/
public boolean hasPrivateKey() {
return hasPrivateKey;
}
/**
* Extend the path by appending additional ChildNumber objects.
*
* @param child1 the first child to append
* @param children zero or more additional children to append
* @return A new immutable path
*/
public HDPath extend(ChildNumber child1, ChildNumber... children) {
List<ChildNumber> mutable = new ArrayList<>(this.unmodifiableList); // Mutable copy
mutable.add(child1);
mutable.addAll(Arrays.asList(children));
return new HDPath(this.hasPrivateKey, mutable);
}
/**
* Extend the path by appending a relative path.
*
* @param path2 the relative path to append
* @return A new immutable path
*/
public HDPath extend(HDPath path2) {
List<ChildNumber> mutable = new ArrayList<>(this.unmodifiableList); // Mutable copy
mutable.addAll(path2);
return new HDPath(this.hasPrivateKey, mutable);
}
/**
* Extend the path by appending a relative path.
*
* @param path2 the relative path to append
* @return A new immutable path
*/
public HDPath extend(List<ChildNumber> path2) {
return this.extend(HDPath.M(path2));
}
/**
* Return a simple list of {@link ChildNumber}
* @return an unmodifiable list of {@code ChildNumber}
*/
public List<ChildNumber> list() {
return unmodifiableList;
}
/**
* Return the parent path.
* <p>
* Note that this method defines the parent of a root path as the empty path and the parent
* of the empty path as the empty path. This behavior is what one would expect
* of an unmodifiable, copy-on-modify list. If you need to check for edge cases, you can use
* {@link HDPath#isEmpty()} before or after using {@code HDPath#parent()}
* @return parent path (which can be empty -- see above)
*/
public HDPath parent() {
return unmodifiableList.size() > 1 ?
HDPath.of(hasPrivateKey, unmodifiableList.subList(0, unmodifiableList.size() - 1)) :
HDPath.of(hasPrivateKey, Collections.emptyList());
}
/**
* Return a list of all ancestors of this path
* @return unmodifiable list of ancestors
*/
public List<HDPath> ancestors() {
return ancestors(false);
}
/**
* Return a list of all ancestors of this path
* @param includeSelf true if include path for self
* @return unmodifiable list of ancestors
*/
public List<HDPath> ancestors(boolean includeSelf) {
int endExclusive = unmodifiableList.size() + (includeSelf ? 1 : 0);
return IntStream.range(1, endExclusive)
.mapToObj(i -> unmodifiableList.subList(0, i))
.map(l -> HDPath.of(hasPrivateKey, l))
.collect(StreamUtils.toUnmodifiableList());
}
@Override
public ChildNumber get(int index) {
return unmodifiableList.get(index);
}
@Override
public int size() {
return unmodifiableList.size();
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append(hasPrivateKey ? HDPath.PREFIX_PRIVATE : HDPath.PREFIX_PUBLIC);
for (ChildNumber segment : unmodifiableList) {
b.append(HDPath.SEPARATOR);
b.append(segment.toString());
}
return b.toString();
}
}
| 10,845
| 33.214511
| 134
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/TransactionSignature.java
|
/*
* Copyright 2013 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.
*/
package org.bitcoinj.crypto;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.Transaction.SigHash;
import org.bitcoinj.core.VerificationException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
/**
* A TransactionSignature wraps an {@link ECKey.ECDSASignature} and adds methods for handling
* the additional SIGHASH mode byte that is used.
*/
public class TransactionSignature extends ECKey.ECDSASignature {
/**
* A byte that controls which parts of a transaction are signed. This is exposed because signatures
* parsed off the wire may have sighash flags that aren't "normal" serializations of the enum values.
* Because Bitcoin Core works via bit testing, we must not lose the exact value when round-tripping
* otherwise we'll fail to verify signature hashes.
*/
public final int sighashFlags;
/** Constructs a signature with the given components and SIGHASH_ALL. */
public TransactionSignature(BigInteger r, BigInteger s) {
this(r, s, Transaction.SigHash.ALL.value);
}
/** Constructs a signature with the given components and raw sighash flag bytes (needed for rule compatibility). */
public TransactionSignature(BigInteger r, BigInteger s, int sighashFlags) {
super(r, s);
this.sighashFlags = sighashFlags;
}
/** Constructs a transaction signature based on the ECDSA signature. */
public TransactionSignature(ECKey.ECDSASignature signature, Transaction.SigHash mode, boolean anyoneCanPay) {
super(signature.r, signature.s);
sighashFlags = calcSigHashValue(mode, anyoneCanPay);
}
/**
* Returns a dummy invalid signature whose R/S values are set such that they will take up the same number of
* encoded bytes as a real signature. This can be useful when you want to fill out a transaction to be of the
* right size (e.g. for fee calculations) but don't have the requisite signing key yet and will fill out the
* real signature later.
*/
public static TransactionSignature dummy() {
BigInteger val = ECKey.HALF_CURVE_ORDER;
return new TransactionSignature(val, val);
}
/** Calculates the byte used in the protocol to represent the combination of mode and anyoneCanPay. */
public static int calcSigHashValue(Transaction.SigHash mode, boolean anyoneCanPay) {
checkArgument(SigHash.ALL == mode || SigHash.NONE == mode || SigHash.SINGLE == mode); // enforce compatibility since this code was made before the SigHash enum was updated
int sighashFlags = mode.value;
if (anyoneCanPay)
sighashFlags |= Transaction.SigHash.ANYONECANPAY.value;
return sighashFlags;
}
/**
* Returns true if the given signature is has canonical encoding, and will thus be accepted as standard by
* Bitcoin Core. DER and the SIGHASH encoding allow for quite some flexibility in how the same structures
* are encoded, and this can open up novel attacks in which a man in the middle takes a transaction and then
* changes its signature such that the transaction hash is different but it's still valid. This can confuse wallets
* and generally violates people's mental model of how Bitcoin should work, thus, non-canonical signatures are now
* not relayed by default.
*/
public static boolean isEncodingCanonical(byte[] signature) {
// See Bitcoin Core's IsCanonicalSignature, https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
// A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
// Where R and S are not negative (their first byte has its highest bit not set), and not
// excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
// in which case a single 0 byte is necessary and even required).
// Empty signatures, while not strictly DER encoded, are allowed.
if (signature.length == 0)
return true;
if (signature.length < 9 || signature.length > 73)
return false;
int hashType = (signature[signature.length-1] & 0xff) & ~Transaction.SigHash.ANYONECANPAY.value; // mask the byte to prevent sign-extension hurting us
if (hashType < Transaction.SigHash.ALL.value || hashType > Transaction.SigHash.SINGLE.value)
return false;
// "wrong type" "wrong length marker"
if ((signature[0] & 0xff) != 0x30 || (signature[1] & 0xff) != signature.length-3)
return false;
int lenR = signature[3] & 0xff;
if (5 + lenR >= signature.length || lenR == 0)
return false;
int lenS = signature[5+lenR] & 0xff;
if (lenR + lenS + 7 != signature.length || lenS == 0)
return false;
// R value type mismatch R value negative
if (signature[4-2] != 0x02 || (signature[4] & 0x80) == 0x80)
return false;
if (lenR > 1 && signature[4] == 0x00 && (signature[4+1] & 0x80) != 0x80)
return false; // R value excessively padded
// S value type mismatch S value negative
if (signature[6 + lenR - 2] != 0x02 || (signature[6 + lenR] & 0x80) == 0x80)
return false;
if (lenS > 1 && signature[6 + lenR] == 0x00 && (signature[6 + lenR + 1] & 0x80) != 0x80)
return false; // S value excessively padded
return true;
}
public boolean anyoneCanPay() {
return (sighashFlags & Transaction.SigHash.ANYONECANPAY.value) != 0;
}
public Transaction.SigHash sigHashMode() {
final int mode = sighashFlags & 0x1f;
if (mode == Transaction.SigHash.NONE.value)
return Transaction.SigHash.NONE;
else if (mode == Transaction.SigHash.SINGLE.value)
return Transaction.SigHash.SINGLE;
else
return Transaction.SigHash.ALL;
}
/**
* What we get back from the signer are the two components of a signature, r and s. To get a flat byte stream
* of the type used by Bitcoin we have to encode them using DER encoding, which is just a way to pack the two
* components into a structure, and then we append a byte to the end for the sighash flags.
*/
public byte[] encodeToBitcoin() {
try {
ByteArrayOutputStream bos = derByteStream();
bos.write(sighashFlags);
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
@Override
public ECKey.ECDSASignature toCanonicalised() {
return new TransactionSignature(super.toCanonicalised(), sigHashMode(), anyoneCanPay());
}
/**
* Returns a decoded signature.
*
* @param requireCanonicalEncoding if the encoding of the signature must
* be canonical.
* @param requireCanonicalSValue if the S-value must be canonical (below half
* the order of the curve).
* @throws SignatureDecodeException if the signature is unparseable in some way.
* @throws VerificationException if the signature is invalid.
*/
public static TransactionSignature decodeFromBitcoin(byte[] bytes, boolean requireCanonicalEncoding,
boolean requireCanonicalSValue) throws SignatureDecodeException, VerificationException {
// Bitcoin encoding is DER signature + sighash byte.
if (requireCanonicalEncoding && !isEncodingCanonical(bytes))
throw new VerificationException.NoncanonicalSignature();
ECKey.ECDSASignature sig = ECKey.ECDSASignature.decodeFromDER(bytes);
if (requireCanonicalSValue && !sig.isCanonical())
throw new VerificationException("S-value is not canonical.");
// In Bitcoin, any value of the final byte is valid, but not necessarily canonical. See javadocs for
// isEncodingCanonical to learn more about this. So we must store the exact byte found.
return new TransactionSignature(sig.r, sig.s, bytes[bytes.length - 1]);
}
}
| 8,844
| 45.798942
| 179
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/package-info.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
/**
* The crypto package contains classes that work with key derivation algorithms like scrypt (passwords to AES keys),
* BIP 32 hierarchies (chains of keys from a root seed), X.509 utilities for the payment protocol and other general
* cryptography tasks. It also contains a class that can disable the (long since obsolete) DRM Java/US Govt imposes
* on strong crypto. This is legal because Oracle got permission to ship strong AES to everyone years ago but hasn't
* bothered to actually remove the logic barriers.
*/
package org.bitcoinj.crypto;
| 1,167
| 47.666667
| 116
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/TrustStoreLoader.java
|
/*
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.crypto;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
/**
* An implementation of TrustStoreLoader handles fetching a KeyStore from the operating system, a file, etc. It's
* necessary because the Java {@link KeyStore} abstraction is not completely seamless and for example
* we sometimes need slightly different techniques to load the key store on different versions of Android, MacOS,
* Windows, etc.
*/
public interface TrustStoreLoader {
KeyStore getKeyStore() throws FileNotFoundException, KeyStoreException;
String DEFAULT_KEYSTORE_TYPE = KeyStore.getDefaultType();
String DEFAULT_KEYSTORE_PASSWORD = "changeit";
class DefaultTrustStoreLoader implements TrustStoreLoader {
@Override
public KeyStore getKeyStore() throws FileNotFoundException, KeyStoreException {
String keystorePath = null;
String keystoreType = DEFAULT_KEYSTORE_TYPE;
try {
// Check if we are on Android.
Class<?> version = Class.forName("android.os.Build$VERSION");
// Build.VERSION_CODES.ICE_CREAM_SANDWICH is 14.
if (version.getDeclaredField("SDK_INT").getInt(version) >= 14) {
return loadIcsKeyStore();
} else {
keystoreType = "BKS";
keystorePath = System.getProperty("java.home")
+ "/etc/security/cacerts.bks".replace('/', File.separatorChar);
}
} catch (ClassNotFoundException e) {
// NOP. android.os.Build is not present, so we are not on Android. Fall through.
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e); // Should never happen.
}
if (keystorePath == null) {
keystorePath = System.getProperty("javax.net.ssl.trustStore");
}
if (keystorePath == null) {
return loadFallbackStore();
}
try {
return X509Utils.loadKeyStore(keystoreType, DEFAULT_KEYSTORE_PASSWORD,
new FileInputStream(keystorePath));
} catch (FileNotFoundException e) {
// If we failed to find a system trust store, load our own fallback trust store. This can fail on
// Android but we should never reach it there.
return loadFallbackStore();
}
}
private KeyStore loadIcsKeyStore() throws KeyStoreException {
try {
// After ICS, Android provided this nice method for loading the keystore,
// so we don't have to specify the location explicitly.
KeyStore keystore = KeyStore.getInstance("AndroidCAStore");
keystore.load(null, null);
return keystore;
} catch (IOException | GeneralSecurityException x) {
throw new KeyStoreException(x);
}
}
private KeyStore loadFallbackStore() throws FileNotFoundException, KeyStoreException {
return X509Utils.loadKeyStore("JKS", DEFAULT_KEYSTORE_PASSWORD, getClass().getResourceAsStream("cacerts"));
}
}
class FileTrustStoreLoader implements TrustStoreLoader {
private final File path;
public FileTrustStoreLoader(@Nonnull File path) throws FileNotFoundException {
if (!path.exists())
throw new FileNotFoundException(path.toString());
this.path = path;
}
@Override
public KeyStore getKeyStore() throws FileNotFoundException, KeyStoreException {
return X509Utils.loadKeyStore(DEFAULT_KEYSTORE_TYPE, DEFAULT_KEYSTORE_PASSWORD, new FileInputStream(path));
}
}
}
| 4,662
| 41.390909
| 119
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/ECKey.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2014 Andreas Schildbach
* Copyright 2014-2016 the libsecp256k1 contributors
*
* 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.
*/
package org.bitcoinj.crypto;
import com.google.common.base.MoreObjects;
import org.bitcoin.NativeSecp256k1;
import org.bitcoin.NativeSecp256k1Util;
import org.bitcoin.Secp256k1Context;
import org.bitcoinj.base.Address;
import org.bitcoinj.base.BitcoinNetwork;
import org.bitcoinj.base.LegacyAddress;
import org.bitcoinj.base.Network;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.SegwitAddress;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.base.internal.ByteUtils;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.base.VarInt;
import org.bitcoinj.crypto.internal.CryptoUtils;
import org.bitcoinj.crypto.utils.MessageVerifyUtils;
import org.bitcoinj.wallet.Protos;
import org.bitcoinj.wallet.Wallet;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.BERTags;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequenceGenerator;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.DLSequence;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.asn1.x9.X9IntegerConverter;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.ec.CustomNamedCurves;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECKeyGenerationParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.signers.ECDSASigner;
import org.bouncycastle.crypto.signers.HMacDSAKCalculator;
import org.bouncycastle.math.ec.ECAlgorithms;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.math.ec.FixedPointCombMultiplier;
import org.bouncycastle.math.ec.FixedPointUtil;
import org.bouncycastle.math.ec.custom.sec.SecP256K1Curve;
import org.bouncycastle.util.Properties;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.SignatureException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
import java.util.Optional;
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
import static org.bitcoinj.base.internal.Preconditions.checkState;
/**
* <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>ECKey also provides access to Bitcoin Core compatible text message signing, as accessible via the UI or JSON-RPC.
* This is slightly different to signing raw bytes - if you want to sign your own data and it won't be exposed as
* text to people, you don't want to use this. If in doubt, ask on the mailing list.</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>
*
* <p>This class supports a variety of serialization forms. The methods that accept/return byte arrays serialize
* private keys as raw byte arrays and public keys using the SEC standard byte encoding for public keys. Signatures
* are encoded using ASN.1/DER inside the Bitcoin protocol.</p>
*
* <p>A key can be <i>compressed</i> or <i>uncompressed</i>. This refers to whether the public key is represented
* when encoded into bytes as an (x, y) coordinate on the elliptic curve, or whether it's represented as just an X
* co-ordinate and an extra byte that carries a sign bit. With the latter form the Y coordinate can be calculated
* dynamically, however, <b>because the binary serialization is different the address of a key changes if its
* compression status is changed</b>. If you deviate from the defaults it's important to understand this: money sent
* to a compressed version of the key will have a different address to the same key in uncompressed form. Whether
* a public key is compressed or not is recorded in the SEC binary serialisation format, and preserved in a flag in
* this class so round-tripping preserves state. Unless you're working with old software or doing unusual things, you
* can usually ignore the compressed/uncompressed distinction.</p>
*/
public class ECKey implements EncryptableItem {
private static final Logger log = LoggerFactory.getLogger(ECKey.class);
// Note: this can be replaced with Arrays.compareUnsigned(a, b) once we require Java 9
private static final Comparator<byte[]> LEXICOGRAPHICAL_COMPARATOR = ByteUtils.arrayUnsignedComparator();
/** Sorts oldest keys first, newest last. */
public static final Comparator<ECKey> AGE_COMPARATOR = Comparator.comparing(ecKey -> ecKey.creationTime().orElse(Instant.EPOCH));
/** Compares by extracting pub key as a {@code byte[]} and using a lexicographic comparator */
public static final Comparator<ECKey> PUBKEY_COMPARATOR = Comparator.comparing(ECKey::getPubKey, LEXICOGRAPHICAL_COMPARATOR);
// The parameters of the secp256k1 curve that Bitcoin uses.
private static final X9ECParameters CURVE_PARAMS = CustomNamedCurves.getByName("secp256k1");
/** The parameters of the secp256k1 curve that Bitcoin uses. */
public static final ECDomainParameters CURVE;
/**
* Equal to CURVE.getN().shiftRight(1), used for canonicalising the S value of a signature. If you aren't
* sure what this is about, you can ignore it.
*/
public static final BigInteger HALF_CURVE_ORDER;
private static final SecureRandom secureRandom;
static {
// Tell Bouncy Castle to precompute data that's needed during secp256k1 calculations.
FixedPointUtil.precompute(CURVE_PARAMS.getG());
CURVE = new ECDomainParameters(CURVE_PARAMS.getCurve(), CURVE_PARAMS.getG(), CURVE_PARAMS.getN(),
CURVE_PARAMS.getH());
HALF_CURVE_ORDER = CURVE_PARAMS.getN().shiftRight(1);
secureRandom = new SecureRandom();
}
// The two parts of the key. If "pub" is set but not "priv", we can only verify signatures, not make them.
@Nullable protected final BigInteger priv; // A field element.
protected final LazyECPoint pub;
// Creation time of the key, or null if the key was deserialized from a version that did
// not have this field.
@Nullable protected Instant creationTime = null;
protected KeyCrypter keyCrypter;
protected EncryptedData encryptedPrivateKey;
private byte[] pubKeyHash;
/**
* Generates an entirely new keypair. Point compression is used so the resulting public key will be 33 bytes
* (32 for the co-ordinate and 1 byte to represent the y bit).
*/
public ECKey() {
this(secureRandom);
}
/**
* Generates an entirely new keypair with the given {@link SecureRandom} object. Point compression is used so the
* resulting public key will be 33 bytes (32 for the co-ordinate and 1 byte to represent the y bit).
*/
public ECKey(SecureRandom secureRandom) {
ECKeyPairGenerator generator = new ECKeyPairGenerator();
ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(CURVE, secureRandom);
generator.init(keygenParams);
AsymmetricCipherKeyPair keypair = generator.generateKeyPair();
ECPrivateKeyParameters privParams = (ECPrivateKeyParameters) keypair.getPrivate();
ECPublicKeyParameters pubParams = (ECPublicKeyParameters) keypair.getPublic();
priv = privParams.getD();
pub = new LazyECPoint(pubParams.getQ(), true);
creationTime = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS);
}
protected ECKey(@Nullable BigInteger priv, ECPoint pub, boolean compressed) {
this(priv, new LazyECPoint(Objects.requireNonNull(pub), compressed));
}
protected ECKey(@Nullable BigInteger priv, LazyECPoint pub) {
if (priv != null) {
checkArgument(priv.bitLength() <= 32 * 8, () ->
"private key exceeds 32 bytes: " + priv.bitLength() + " bits");
// Try and catch buggy callers or bad key imports, etc. Zero and one are special because these are often
// used as sentinel values and because scripting languages have a habit of auto-casting true and false to
// 1 and 0 or vice-versa. Type confusion bugs could therefore result in private keys with these values.
checkArgument(!priv.equals(BigInteger.ZERO));
checkArgument(!priv.equals(BigInteger.ONE));
}
this.priv = priv;
this.pub = Objects.requireNonNull(pub);
}
/**
* Construct an ECKey from an ASN.1 encoded private key. These are produced by OpenSSL and stored by Bitcoin
* Core in its wallet. Note that this is slow because it requires an EC point multiply.
*/
public static ECKey fromASN1(byte[] asn1privkey) {
return extractKeyFromASN1(asn1privkey);
}
/**
* Creates an ECKey given the private key only. The public key is calculated from it (this is slow). The resulting
* public key is compressed.
*/
public static ECKey fromPrivate(BigInteger privKey) {
return fromPrivate(privKey, true);
}
/**
* Creates an ECKey given the private key only. The public key is calculated from it (this is slow).
* @param compressed Determines whether the resulting ECKey will use a compressed encoding for the public key.
*/
public static ECKey fromPrivate(BigInteger privKey, boolean compressed) {
ECPoint point = publicPointFromPrivate(privKey);
return new ECKey(privKey, new LazyECPoint(point, compressed));
}
/**
* Creates an ECKey given the private key only. The public key is calculated from it (this is slow). The resulting
* public key is compressed.
*/
public static ECKey fromPrivate(byte[] privKeyBytes) {
return fromPrivate(ByteUtils.bytesToBigInteger(privKeyBytes));
}
/**
* Creates an ECKey given the private key only. The public key is calculated from it (this is slow).
* @param compressed Determines whether the resulting ECKey will use a compressed encoding for the public key.
*/
public static ECKey fromPrivate(byte[] privKeyBytes, boolean compressed) {
return fromPrivate(ByteUtils.bytesToBigInteger(privKeyBytes), compressed);
}
/**
* 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.
* @param compressed Determines whether the resulting ECKey will use a compressed encoding for the public key.
*/
public static ECKey fromPrivateAndPrecalculatedPublic(BigInteger priv, ECPoint pub, boolean compressed) {
return new ECKey(priv, pub, compressed);
}
/**
* 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.
*/
public static ECKey fromPrivateAndPrecalculatedPublic(byte[] priv, byte[] pub) {
Objects.requireNonNull(priv);
Objects.requireNonNull(pub);
return new ECKey(ByteUtils.bytesToBigInteger(priv), new LazyECPoint(CURVE.getCurve(), pub));
}
/**
* Creates an ECKey that cannot be used for signing, only verifying signatures, from the given point.
* @param compressed Determines whether the resulting ECKey will use a compressed encoding for the public key.
*/
public static ECKey fromPublicOnly(ECPoint pub, boolean compressed) {
return new ECKey(null, pub, compressed);
}
/**
* 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.
*/
public static ECKey fromPublicOnly(byte[] pub) {
return new ECKey(null, new LazyECPoint(CURVE.getCurve(), pub));
}
public static ECKey fromPublicOnly(ECKey key) {
return fromPublicOnly(key.getPubKeyPoint(), key.isCompressed());
}
/**
* 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.
*/
public ECKey decompress() {
if (!pub.isCompressed())
return this;
else
return new ECKey(priv, new LazyECPoint(pub.get(), false));
}
/**
* Constructs a key that has an encrypted private component. The given object wraps encrypted bytes and an
* initialization vector. Note that the key will not be decrypted during this call: the returned ECKey is
* unusable for signing unless a decryption key is supplied.
*/
public static ECKey fromEncrypted(EncryptedData encryptedPrivateKey, KeyCrypter crypter, byte[] pubKey) {
ECKey key = fromPublicOnly(pubKey);
key.encryptedPrivateKey = Objects.requireNonNull(encryptedPrivateKey);
key.keyCrypter = Objects.requireNonNull(crypter);
return key;
}
/**
* Returns true if this key doesn't have unencrypted access to private key bytes. This may be because it was never
* given any private key bytes to begin with (a watching key), or because the key is encrypted. You can use
* {@link #isEncrypted()} to tell the cases apart.
*/
public boolean isPubKeyOnly() {
return priv == null;
}
/**
* Returns true if this key has unencrypted access to private key bytes. Does the opposite of
* {@link #isPubKeyOnly()}.
*/
public boolean hasPrivKey() {
return priv != null;
}
/** Returns true if this key is watch only, meaning it has a public key but no private key. */
public boolean isWatching() {
return isPubKeyOnly() && !isEncrypted();
}
/**
* Output this ECKey as an ASN.1 encoded private key, as understood by OpenSSL or used by Bitcoin Core
* in its wallet storage format.
* @throws ECKey.MissingPrivateKeyException if the private key is missing or encrypted.
*/
public byte[] toASN1() {
try {
byte[] privKeyBytes = getPrivKeyBytes();
ByteArrayOutputStream baos = new ByteArrayOutputStream(400);
// ASN1_SEQUENCE(EC_PRIVATEKEY) = {
// ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),
// ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),
// ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),
// ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)
// } ASN1_SEQUENCE_END(EC_PRIVATEKEY)
DERSequenceGenerator seq = new DERSequenceGenerator(baos);
seq.addObject(new ASN1Integer(1)); // version
seq.addObject(new DEROctetString(privKeyBytes));
seq.addObject(new DERTaggedObject(0, CURVE_PARAMS.toASN1Primitive()));
seq.addObject(new DERTaggedObject(1, new DERBitString(getPubKey())));
seq.close();
return baos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen, writing to memory stream.
}
}
/**
* Returns public key bytes from the given private key. To convert a byte array into a BigInteger,
* use {@link ByteUtils#bytesToBigInteger(byte[])}
*/
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed) {
ECPoint point = publicPointFromPrivate(privKey);
return point.getEncoded(compressed);
}
/**
* Returns public key point from the given private key. To convert a byte array into a BigInteger,
* use {@link ByteUtils#bytesToBigInteger(byte[])}
*/
public static ECPoint publicPointFromPrivate(BigInteger privKey) {
/*
* TODO: FixedPointCombMultiplier currently doesn't support scalars longer than the group order,
* but that could change in future versions.
*/
if (privKey.bitLength() > CURVE.getN().bitLength()) {
privKey = privKey.mod(CURVE.getN());
}
return new FixedPointCombMultiplier().multiply(CURVE.getG(), privKey);
}
/** Gets the hash160 form of the public key (as seen in addresses). */
public byte[] getPubKeyHash() {
if (pubKeyHash == null)
pubKeyHash = CryptoUtils.sha256hash160(this.pub.getEncoded());
return pubKeyHash;
}
/**
* Gets the raw public key value. This appears in transaction scriptSigs. Note that this is <b>not</b> the same
* as the pubKeyHash/address.
*/
public byte[] getPubKey() {
return pub.getEncoded();
}
/** Gets the public key in the form of an elliptic curve point object from Bouncy Castle. */
public ECPoint getPubKeyPoint() {
return pub.get();
}
/**
* 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).
*
* @throws java.lang.IllegalStateException if the private key bytes are not available.
*/
public BigInteger getPrivKey() {
if (priv == null)
throw new MissingPrivateKeyException();
return priv;
}
/**
* Returns whether this key is using the compressed form or not. Compressed pubkeys are only 33 bytes, not 64.
*/
public boolean isCompressed() {
return pub.isCompressed();
}
public Address toAddress(ScriptType scriptType, Network network) {
if (scriptType == ScriptType.P2PKH) {
return LegacyAddress.fromPubKeyHash(network, this.getPubKeyHash());
} else if (scriptType == ScriptType.P2WPKH) {
checkArgument(this.isCompressed(), () ->
"only compressed keys allowed");
return SegwitAddress.fromHash(network, this.getPubKeyHash());
} else {
throw new IllegalArgumentException(scriptType.toString());
}
}
/**
* Groups the two components that make up a signature, and provides a way to encode to DER form, which is
* how ECDSA signatures are represented when embedded in other data structures in the Bitcoin 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;
/**
* Constructs a signature with the given components. Does NOT automatically canonicalise the signature.
*/
public ECDSASignature(BigInteger r, BigInteger s) {
this.r = r;
this.s = s;
}
/**
* Returns true if the S component is "low", that means it is below {@link ECKey#HALF_CURVE_ORDER}. See <a
* href="https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#Low_S_values_in_signatures">BIP62</a>.
*/
public boolean isCanonical() {
return s.compareTo(HALF_CURVE_ORDER) <= 0;
}
/**
* 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 Bitcoin 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.
*/
public ECDSASignature toCanonicalised() {
if (!isCanonical()) {
// 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;
}
}
/**
* DER is an international standard for serializing data structures which is widely used in cryptography.
* It's somewhat like protocol buffers but less convenient. This method returns a standard DER encoding
* of the signature, as recognized by OpenSSL and other libraries.
*/
public byte[] encodeToDER() {
try {
return derByteStream().toByteArray();
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
/**
* @throws SignatureDecodeException if the signature is unparseable in some way.
*/
public static ECDSASignature decodeFromDER(byte[] bytes) throws SignatureDecodeException {
ASN1InputStream decoder = null;
try {
// BouncyCastle by default is strict about parsing ASN.1 integers. We relax this check, because some
// Bitcoin signatures would not parse.
Properties.setThreadOverride("org.bouncycastle.asn1.allow_unsafe_integer", true);
decoder = new ASN1InputStream(bytes);
final ASN1Primitive seqObj = decoder.readObject();
if (seqObj == null)
throw new SignatureDecodeException("Reached past end of ASN.1 stream.");
if (!(seqObj instanceof DLSequence))
throw new SignatureDecodeException("Read unexpected class: " + seqObj.getClass().getName());
final DLSequence seq = (DLSequence) seqObj;
ASN1Integer r, s;
try {
r = (ASN1Integer) seq.getObjectAt(0);
s = (ASN1Integer) seq.getObjectAt(1);
} catch (ClassCastException e) {
throw new SignatureDecodeException(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 SignatureDecodeException(e);
} finally {
if (decoder != null)
try { decoder.close(); } catch (IOException x) {}
Properties.removeThreadOverride("org.bouncycastle.asn1.allow_unsafe_integer");
}
}
protected ByteArrayOutputStream derByteStream() throws IOException {
// Usually 70-72 bytes.
ByteArrayOutputStream bos = new ByteArrayOutputStream(72);
DERSequenceGenerator seq = new DERSequenceGenerator(bos);
seq.addObject(new ASN1Integer(r));
seq.addObject(new ASN1Integer(s));
seq.close();
return bos;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ECDSASignature other = (ECDSASignature) o;
return r.equals(other.r) && s.equals(other.s);
}
@Override
public int hashCode() {
return Objects.hash(r, s);
}
}
/**
* Signs the given hash and returns the R and S components as BigIntegers. In the Bitcoin protocol, they are
* usually encoded using ASN.1 format, so you want {@link ECKey.ECDSASignature#toASN1()}
* instead. However sometimes the independent components can be useful, for instance, if you're going to do
* further EC maths on them.
* @throws KeyCrypterException if this ECKey doesn't have a private part.
*/
public ECDSASignature sign(Sha256Hash input) throws KeyCrypterException {
return sign(input, null);
}
/**
* Signs the given hash and returns the R and S components as BigIntegers. In the Bitcoin protocol, they are
* usually encoded using DER format, so you want {@link ECKey.ECDSASignature#encodeToDER()}
* instead. However sometimes the independent components can be useful, for instance, if you're doing to do further
* EC maths on them.
*
* @param aesKey The AES key to use for decryption of the private key. If null then no decryption is required.
* @throws KeyCrypterException if there's something wrong with aesKey.
* @throws ECKey.MissingPrivateKeyException if this key cannot sign because it's pubkey only.
*/
public ECDSASignature sign(Sha256Hash input, @Nullable AesKey aesKey) throws KeyCrypterException {
KeyCrypter crypter = getKeyCrypter();
if (crypter != null) {
if (aesKey == null)
throw new KeyIsEncryptedException();
return decrypt(aesKey).sign(input);
} else {
// No decryption of private key required.
if (priv == null)
throw new MissingPrivateKeyException();
}
return doSign(input, priv);
}
protected ECDSASignature doSign(Sha256Hash input, BigInteger privateKeyForSigning) {
if (Secp256k1Context.isEnabled()) {
try {
byte[] signature = NativeSecp256k1.sign(
input.getBytes(),
ByteUtils.bigIntegerToBytes(privateKeyForSigning, 32)
);
return ECDSASignature.decodeFromDER(signature);
} catch (NativeSecp256k1Util.AssertFailException e) {
log.error("Caught AssertFailException inside secp256k1", e);
throw new RuntimeException(e);
} catch (SignatureDecodeException e) {
throw new RuntimeException(e); // cannot happen
}
}
Objects.requireNonNull(privateKeyForSigning);
ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKeyForSigning, CURVE);
signer.init(true, privKey);
BigInteger[] components = signer.generateSignature(input.getBytes());
return new ECDSASignature(components[0], components[1]).toCanonicalised();
}
/**
* <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 ASN.1 encoded signature.
* @param pub The public key bytes to use.
*/
public static boolean verify(byte[] data, ECDSASignature signature, byte[] pub) {
if (Secp256k1Context.isEnabled()) {
try {
return NativeSecp256k1.verify(data, signature.encodeToDER(), pub);
} catch (NativeSecp256k1Util.AssertFailException e) {
log.error("Caught AssertFailException inside secp256k1", e);
return false;
}
}
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 e) {
// 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.
log.error("Caught NPE inside bouncy castle", e);
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 ASN.1 encoded signature.
* @param pub The public key bytes to use.
* @throws SignatureDecodeException if the signature is unparseable in some way.
*/
public static boolean verify(byte[] data, byte[] signature, byte[] pub) throws SignatureDecodeException {
if (Secp256k1Context.isEnabled()) {
try {
return NativeSecp256k1.verify(data, signature, pub);
} catch (NativeSecp256k1Util.AssertFailException e) {
log.error("Caught AssertFailException inside secp256k1", e);
return false;
}
}
return verify(data, ECDSASignature.decodeFromDER(signature), pub);
}
/**
* Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key.
*
* @param hash Hash of the data to verify.
* @param signature ASN.1 encoded signature.
* @throws SignatureDecodeException if the signature is unparseable in some way.
*/
public boolean verify(byte[] hash, byte[] signature) throws SignatureDecodeException {
return ECKey.verify(hash, signature, getPubKey());
}
/**
* Verifies the given R/S pair (signature) against a hash using the public key.
*/
public boolean verify(Sha256Hash sigHash, ECDSASignature signature) {
return ECKey.verify(sigHash.getBytes(), signature, getPubKey());
}
/**
* Verifies the given ASN.1 encoded ECDSA signature against a hash using the public key, and throws an exception
* if the signature doesn't match
* @throws SignatureDecodeException if the signature is unparseable in some way.
* @throws java.security.SignatureException if the signature does not match.
*/
public void verifyOrThrow(byte[] hash, byte[] signature) throws SignatureDecodeException, SignatureException {
if (!verify(hash, signature))
throw new SignatureException();
}
/**
* Verifies the given R/S pair (signature) against a hash using the public key, and throws an exception
* if the signature doesn't match
* @throws java.security.SignatureException if the signature does not match.
*/
public void verifyOrThrow(Sha256Hash sigHash, ECDSASignature signature) throws SignatureException {
if (!ECKey.verify(sigHash.getBytes(), signature, getPubKey()))
throw new SignatureException();
}
/**
* Returns true if the given pubkey is canonical, i.e. the correct length taking into account compression.
*/
public static boolean isPubKeyCanonical(byte[] pubkey) {
if (pubkey.length < 33)
return false;
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;
}
/**
* Returns true if the given pubkey is in its compressed form.
*/
public static boolean isPubKeyCompressed(byte[] encoded) {
if (encoded.length == 33 && (encoded[0] == 0x02 || encoded[0] == 0x03))
return true;
else if (encoded.length == 65 && encoded[0] == 0x04)
return false;
else
throw new IllegalArgumentException(ByteUtils.formatHex(encoded));
}
private static ECKey extractKeyFromASN1(byte[] asn1privkey) {
// To understand this code, see the definition of the ASN.1 format for EC private keys in the OpenSSL source
// code in ec_asn1.c:
//
// ASN1_SEQUENCE(EC_PRIVATEKEY) = {
// ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),
// ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),
// ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),
// ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)
// } ASN1_SEQUENCE_END(EC_PRIVATEKEY)
//
try {
ASN1InputStream decoder = new ASN1InputStream(asn1privkey);
DLSequence seq = (DLSequence) decoder.readObject();
checkArgument(decoder.readObject() == null, () ->
"input contains extra bytes");
decoder.close();
checkArgument(seq.size() == 4, () ->
"input does not appear to be an ASN.1 OpenSSL EC private key");
checkArgument(((ASN1Integer) seq.getObjectAt(0)).getValue().equals(BigInteger.ONE), () ->
"input is of wrong version");
byte[] privbits = ((ASN1OctetString) seq.getObjectAt(1)).getOctets();
BigInteger privkey = ByteUtils.bytesToBigInteger(privbits);
ASN1TaggedObject pubkey = (ASN1TaggedObject) seq.getObjectAt(3);
checkArgument(pubkey.getTagNo() == 1, () ->
"input has 'publicKey' with bad tag number");
checkArgument(pubkey.getTagClass() == BERTags.CONTEXT_SPECIFIC, () ->
"input has 'publicKey' with bad tag class");
byte[] pubbits = ((DERBitString) pubkey.getBaseObject()).getBytes();
checkArgument(pubbits.length == 33 || pubbits.length == 65, () ->
"input has 'publicKey' with invalid length");
int encoding = pubbits[0] & 0xFF;
// Only allow compressed(2,3) and uncompressed(4), not infinity(0) or hybrid(6,7)
checkArgument(encoding >= 2 && encoding <= 4, () ->
"input has 'publicKey' with invalid encoding");
// Now sanity check to ensure the pubkey bytes match the privkey.
ECKey key = ECKey.fromPrivate(privkey, isPubKeyCompressed(pubbits));
checkArgument (Arrays.equals(key.getPubKey(), pubbits), () ->
"public key in ASN.1 structure does not match private key.");
return key;
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen, reading from memory stream.
}
}
/**
* Signs a text message using the standard Bitcoin messaging signing format and returns the signature as a base64
* encoded string.
*
* @throws IllegalStateException if this ECKey does not have the private part.
* @throws KeyCrypterException if this ECKey is encrypted and no AESKey is provided or it does not decrypt the ECKey.
* @deprecated use {@link #signMessage(String, ScriptType)} instead and specify the correct script type
*/
@Deprecated
public String signMessage(String message) throws KeyCrypterException {
return signMessage(message, null, ScriptType.P2PKH);
}
/**
* Signs a text message using the standard Bitcoin messaging signing format and returns the signature as a base64
* encoded string.
*
* @throws IllegalStateException if this ECKey does not have the private part.
* @throws KeyCrypterException if this ECKey is encrypted and no AESKey is provided or it does not decrypt the ECKey.
*/
public String signMessage(String message, ScriptType scriptType) throws KeyCrypterException {
return signMessage(message, null, scriptType);
}
/**
* Signs a text message using the standard Bitcoin messaging signing format and returns the signature as a base64
* encoded string.
*
* @throws IllegalStateException if this ECKey does not have the private part.
* @throws KeyCrypterException if this ECKey is encrypted and no AESKey is provided or it does not decrypt the ECKey.
* @deprecated use {@link #signMessage(String, AesKey, ScriptType)} instead and specify the correct script type
*/
@Deprecated
public String signMessage(String message, @Nullable AesKey aesKey) throws KeyCrypterException {
return signMessage(message, aesKey, ScriptType.P2PKH);
}
/**
* Signs a text message using the standard Bitcoin messaging signing format and returns the signature as a base64
* encoded string.
*
* @throws IllegalArgumentException if uncompressed key is used for Segwit scriptType, or unsupported script type is specified
* @throws IllegalStateException if this ECKey does not have the private part.
* @throws KeyCrypterException if this ECKey is encrypted and no AESKey is provided or it does not decrypt the ECKey.
*/
public String signMessage(String message, @Nullable AesKey aesKey, ScriptType scriptType) throws KeyCrypterException {
if (!isCompressed() && (scriptType == ScriptType.P2WPKH || scriptType == ScriptType.P2SH)) {
throw new IllegalArgumentException("Segwit P2WPKH and P2SH-P2WPKH script types only can be used with compressed keys. See BIP 141.");
}
byte[] data = formatMessageForSigning(message);
Sha256Hash hash = Sha256Hash.twiceOf(data);
ECDSASignature sig = sign(hash, aesKey);
byte recId = findRecoveryId(hash, sig);
// Meaning of header byte ranges:
// * 27-30: P2PKH uncompressed, recId 0-3
// * 31-34: P2PKH compressed, recId 0-3
// * 35-38: Segwit P2SH (always compressed), recId 0-3
// * 39-42: Segwit Bech32 (always compressed), recId 0-3
// as defined in https://github.com/bitcoin/bips/blob/master/bip-0137.mediawiki#procedure-for-signingverifying-a-signature
int headerByte;
switch (scriptType) {
case P2PKH:
headerByte = recId + 27 + (isCompressed() ? 4 : 0);
break;
case P2SH: // P2SH-P2WPKH ("legacy-segwit")
headerByte = recId + 35;
break;
case P2WPKH:
headerByte = recId + 39;
break;
default:
throw new IllegalArgumentException("Unsupported script type for message signing.");
}
byte[] sigData = new byte[65]; // 1 header + 32 bytes for R + 32 bytes for S
sigData[0] = (byte)headerByte;
System.arraycopy(ByteUtils.bigIntegerToBytes(sig.r, 32), 0, sigData, 1, 32);
System.arraycopy(ByteUtils.bigIntegerToBytes(sig.s, 32), 0, sigData, 33, 32);
return new String(Base64.encode(sigData), StandardCharsets.UTF_8);
}
/**
* Given an arbitrary piece of text and a Bitcoin-format 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. These sorts of signatures are compatible with the Bitcoin-Qt/bitcoind
* format generated by signmessage/verifymessage RPCs and GUI menu options. They are intended for humans to verify
* their communications with each other, hence the base64 format and the fact that the input is text.
*
* @param message Some piece of human-readable text.
* @param signatureBase64 The Bitcoin-format message signature in base64
* @throws SignatureException If the public key could not be recovered or if there was a signature format error.
*/
public static ECKey signedMessageToKey(String message, 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);
int header = signatureEncoded[0] & 0xFF;
// allowed range of valid header byte values as defined in BIP 137:
if (header < 27 || header > 42)
throw new SignatureException("Header byte out of range: " + header);
BigInteger r = ByteUtils.bytesToBigInteger(Arrays.copyOfRange(signatureEncoded, 1, 33));
BigInteger s = ByteUtils.bytesToBigInteger(Arrays.copyOfRange(signatureEncoded, 33, 65));
ECDSASignature sig = new ECDSASignature(r, s);
byte[] messageBytes = formatMessageForSigning(message);
// Note that the C++ code doesn't actually seem to specify any character encoding. Presumably it's whatever
// JSON-SPIRIT hands back. Assume UTF-8 for now.
Sha256Hash messageHash = Sha256Hash.twiceOf(messageBytes);
boolean compressed = false;
// Meaning of header byte ranges:
// * 27-30: P2PKH uncompressed, recId 0-3
// * 31-34: P2PKH compressed, recId 0-3
// * 35-38: Segwit P2SH (always compressed), recId 0-3
// * 39-42: Segwit Bech32 (always compressed), recId 0-3
// as defined in https://github.com/bitcoin/bips/blob/master/bip-0137.mediawiki#procedure-for-signingverifying-a-signature
// this is a signature created with a Segwit bech32 address
if (header >= 39) {
header -= 12;
compressed = true; // by definition in BIP 141
}
// this is a signature created with a Segwit p2sh (p2sh-p2wpkh) address
else if (header >= 35) {
header -= 8;
compressed = true; // by definition in BIP 141
}
// this is a signature created with a compressed p2pkh address
else if (header >= 31) {
compressed = true;
header -= 4;
}
// else: signature created with an uncompressed p2pkh address
// As the recovery of a pubkey from an ECDSA signature will recover several possible
// public keys, the header byte is used to carry information, which of the possible
// keys was the key used to create the signature (see also BIP 137):
// header byte: 27 = first key with even y, 28 = first key with odd y,
// 29 = second key with even y, 30 = second key with odd y
int recId = header - 27;
ECKey key = ECKey.recoverFromSignature(recId, sig, messageHash, compressed);
if (key == null)
throw new SignatureException("Could not recover public key from signature");
return key;
}
/**
* Convenience wrapper around {@link ECKey#signedMessageToKey(String, String)}. If the key derived from the
* signature is not the same as this one, throws a SignatureException.
* @deprecated Use {@link MessageVerifyUtils#verifyMessage(Address, String, String)} instead,
* which works with different address types, which works also with legacy segwit (P2SH-P2WPKH, 3…)
* and native segwit addresses (P2WPKH, bc1…).
*/
@Deprecated
public void verifyMessage(String message, String signatureBase64) throws SignatureException {
ECKey key = ECKey.signedMessageToKey(message, signatureBase64);
if (!key.pub.equals(pub))
throw new SignatureException("Signature did not match for message");
}
/**
* Returns the recovery ID, a byte with value between 0 and 3, inclusive, that specifies which of 4 possible
* curve points was used to sign a message. This value is also referred to as "v".
*
* @throws RuntimeException if no recovery ID can be found.
*/
public byte findRecoveryId(Sha256Hash hash, ECDSASignature sig) {
byte recId = -1;
for (byte i = 0; i < 4; i++) {
ECKey k = ECKey.recoverFromSignature(i, sig, hash, isCompressed());
if (k != null && k.pub.equals(pub)) {
recId = i;
break;
}
}
if (recId == -1)
throw new RuntimeException("Could not construct a recoverable key. This should never happen.");
return recId;
}
/**
* <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 message Hash of the data that was signed.
* @param compressed Whether or not the original pubkey was compressed.
* @return An ECKey containing only the public part, or null if recovery wasn't possible.
*/
@Nullable
public static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message, boolean compressed) {
checkArgument(recId >= 0, () -> "recId must be positive");
checkArgument(sig.r.signum() >= 0, () -> "r must be positive");
checkArgument(sig.s.signum() >= 0, () -> "s must be positive");
Objects.requireNonNull(message);
// see https://www.secg.org/sec1-v2.pdf, section 4.1.6
// 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.
BigInteger prime = SecP256K1Curve.q;
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 = message.toBigInteger();
// 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 q = ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv);
return ECKey.fromPublicOnly(q, compressed);
}
/** Decompress a compressed public key (x co-ord and low-bit of y-coord). */
private static ECPoint decompressKey(BigInteger xBN, boolean yBit) {
X9IntegerConverter x9 = new X9IntegerConverter();
byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE.getCurve()));
compEnc[0] = (byte)(yBit ? 0x03 : 0x02);
return CURVE.getCurve().decodePoint(compEnc);
}
/**
* Returns a 32 byte array containing the private key.
* @throws ECKey.MissingPrivateKeyException if the private key bytes are missing/encrypted.
*/
public byte[] getPrivKeyBytes() {
return ByteUtils.bigIntegerToBytes(getPrivKey(), 32);
}
/**
* Exports the private key in the form used by Bitcoin Core's "dumpprivkey" and "importprivkey" commands. Use
* the {@link DumpedPrivateKey#toString()} method to get the string.
*
* @param network The network this key is intended for use on.
* @return Private key bytes as a {@link DumpedPrivateKey}.
* @throws IllegalStateException if the private key is not available.
*/
public DumpedPrivateKey getPrivateKeyEncoded(Network network) {
return new DumpedPrivateKey(network, getPrivKeyBytes(), isCompressed());
}
/**
* Exports the private key in the form used by Bitcoin Core's "dumpprivkey" and "importprivkey" commands. Use
* the {@link DumpedPrivateKey#toString()} method to get the string.
*
* @param params The network this key is intended for use on.
* @return Private key bytes as a {@link DumpedPrivateKey}.
* @throws IllegalStateException if the private key is not available.
* @deprecated Use {@link #getPrivateKeyEncoded(Network)}
*/
@Deprecated
public DumpedPrivateKey getPrivateKeyEncoded(NetworkParameters params) {
return getPrivateKeyEncoded(params.network());
}
/**
* Returns the creation time of this key, or empty if the key was deserialized from a version that did not store
* that data.
*/
@Override
public Optional<Instant> creationTime() {
return Optional.ofNullable(creationTime);
}
/**
* Sets the creation time of this key. This method can be useful when
* you have a raw key you are importing from somewhere else.
* @param creationTime creation time of this key
*/
public void setCreationTime(Instant creationTime) {
this.creationTime = Objects.requireNonNull(creationTime);
}
/**
* Clears the creation time of this key. This is mainly used deserialization and cloning. Normally you should not
* need to use this, as keys should have proper creation times whenever possible.
*/
public void clearCreationTime() {
this.creationTime = null;
}
/** @deprecated use {@link #setCreationTime(Instant)} */
@Deprecated
public void setCreationTimeSeconds(long creationTimeSecs) {
if (creationTimeSecs > 0)
setCreationTime(Instant.ofEpochSecond(creationTimeSecs));
else if (creationTimeSecs == 0)
clearCreationTime();
else
throw new IllegalArgumentException("Cannot set creation time to negative value: " + creationTimeSecs);
}
/**
* Create an encrypted private key with the keyCrypter and the AES key supplied.
* This method returns a new encrypted key and leaves the original unchanged.
*
* @param keyCrypter The keyCrypter that specifies exactly how the encrypted bytes are created.
* @param aesKey The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached as it is slow to create).
* @return encryptedKey
*/
public ECKey encrypt(KeyCrypter keyCrypter, AesKey aesKey) throws KeyCrypterException {
Objects.requireNonNull(keyCrypter);
final byte[] privKeyBytes = getPrivKeyBytes();
EncryptedData encryptedPrivateKey = keyCrypter.encrypt(privKeyBytes, aesKey);
ECKey result = ECKey.fromEncrypted(encryptedPrivateKey, keyCrypter, getPubKey());
if (creationTime != null)
result.setCreationTime(creationTime);
else
result.clearCreationTime();
return result;
}
/**
* Create a decrypted private key with the keyCrypter and AES key supplied. Note that if the aesKey is wrong, this
* has some chance of throwing KeyCrypterException due to the corrupted padding that will result, but it can also
* just yield a garbage key.
*
* @param keyCrypter The keyCrypter that specifies exactly how the decrypted bytes are created.
* @param aesKey The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached).
*/
public ECKey decrypt(KeyCrypter keyCrypter, AesKey aesKey) throws KeyCrypterException {
Objects.requireNonNull(keyCrypter);
// Check that the keyCrypter matches the one used to encrypt the keys, if set.
if (this.keyCrypter != null && !this.keyCrypter.equals(keyCrypter))
throw new KeyCrypterException("The keyCrypter being used to decrypt the key is different to the one that was used to encrypt it");
checkState(encryptedPrivateKey != null, () ->
"this key is not encrypted");
byte[] unencryptedPrivateKey = keyCrypter.decrypt(encryptedPrivateKey, aesKey);
if (unencryptedPrivateKey.length != 32)
throw new KeyCrypterException.InvalidCipherText(
"Decrypted key must be 32 bytes long, but is " + unencryptedPrivateKey.length);
ECKey key = ECKey.fromPrivate(unencryptedPrivateKey, isCompressed());
if (!Arrays.equals(key.getPubKey(), getPubKey()))
throw new KeyCrypterException("Provided AES key is wrong");
if (creationTime != null)
key.setCreationTime(creationTime);
else
key.clearCreationTime();
return key;
}
/**
* Create a decrypted private key with AES key. Note that if the AES key is wrong, this
* has some chance of throwing KeyCrypterException due to the corrupted padding that will result, but it can also
* just yield a garbage key.
*
* @param aesKey The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached).
*/
public ECKey decrypt(AesKey aesKey) throws KeyCrypterException {
final KeyCrypter crypter = getKeyCrypter();
if (crypter == null)
throw new KeyCrypterException("No key crypter available");
return decrypt(crypter, aesKey);
}
/**
* Creates decrypted private key if needed.
*/
public ECKey maybeDecrypt(@Nullable AesKey aesKey) throws KeyCrypterException {
return isEncrypted() && aesKey != null ? decrypt(aesKey) : this;
}
/**
* <p>Check that it is possible to decrypt the key with the keyCrypter and that the original key is returned.</p>
*
* <p>Because it is a critical failure if the private keys cannot be decrypted successfully (resulting of loss of all
* bitcoins controlled by the private key) you can use this method to check when you *encrypt* a wallet that
* it can definitely be decrypted successfully.</p>
*
* <p>See {@link Wallet#encrypt(KeyCrypter keyCrypter, AesKey aesKey)} for example usage.</p>
*
* @return true if the encrypted key can be decrypted back to the original key successfully.
*/
public static boolean encryptionIsReversible(ECKey originalKey, ECKey encryptedKey, KeyCrypter keyCrypter, AesKey aesKey) {
try {
ECKey rebornUnencryptedKey = encryptedKey.decrypt(keyCrypter, aesKey);
byte[] originalPrivateKeyBytes = originalKey.getPrivKeyBytes();
byte[] rebornKeyBytes = rebornUnencryptedKey.getPrivKeyBytes();
if (!Arrays.equals(originalPrivateKeyBytes, rebornKeyBytes)) {
log.error("The check that encryption could be reversed failed for {}", originalKey);
return false;
}
return true;
} catch (KeyCrypterException kce) {
log.error(kce.getMessage());
return false;
}
}
/**
* Indicates whether the private key is encrypted (true) or not (false).
* A private key is deemed to be encrypted when there is both a KeyCrypter and the encryptedPrivateKey is non-zero.
*/
@Override
public boolean isEncrypted() {
return keyCrypter != null && encryptedPrivateKey != null && encryptedPrivateKey.encryptedBytes.length > 0;
}
@Nullable
@Override
public Protos.Wallet.EncryptionType getEncryptionType() {
return keyCrypter != null ? keyCrypter.getUnderstoodEncryptionType() : Protos.Wallet.EncryptionType.UNENCRYPTED;
}
/**
* A wrapper for {@link #getPrivKeyBytes()} that returns null if the private key bytes are missing or would have
* to be derived (for the HD key case).
*/
@Override
@Nullable
public byte[] getSecretBytes() {
if (hasPrivKey())
return getPrivKeyBytes();
else
return null;
}
/** An alias for {@link #getEncryptedPrivateKey()} */
@Nullable
@Override
public EncryptedData getEncryptedData() {
return getEncryptedPrivateKey();
}
/**
* Returns the the encrypted private key bytes and initialisation vector for this ECKey, or null if the ECKey
* is not encrypted.
*/
@Nullable
public EncryptedData getEncryptedPrivateKey() {
return encryptedPrivateKey;
}
/**
* Returns the KeyCrypter that was used to encrypt to encrypt this ECKey. You need this to decrypt the ECKey.
*/
@Nullable
public KeyCrypter getKeyCrypter() {
return keyCrypter;
}
public static class MissingPrivateKeyException extends RuntimeException {
}
public static class KeyIsEncryptedException extends MissingPrivateKeyException {
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof ECKey)) return false;
ECKey other = (ECKey) o;
return Objects.equals(this.priv, other.priv)
&& Objects.equals(this.pub, other.pub)
&& Objects.equals(this.creationTime, other.creationTime)
&& Objects.equals(this.keyCrypter, other.keyCrypter)
&& Objects.equals(this.encryptedPrivateKey, other.encryptedPrivateKey);
}
@Override
public int hashCode() {
return pub.hashCode();
}
@Override
public String toString() {
return toString(false, null, BitcoinNetwork.MAINNET);
}
/**
* 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 {@link #toString()}.
*/
public String toStringWithPrivate(@Nullable AesKey aesKey, Network network) {
return toString(true, aesKey, network);
}
/**
* 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 {@link #toString()}.
* @deprecated Use {@link #toStringWithPrivate(AesKey, Network)}
*/
@Deprecated
public String toStringWithPrivate(@Nullable AesKey aesKey, NetworkParameters params) {
return toStringWithPrivate(aesKey, params.network());
}
public String getPrivateKeyAsHex() {
return ByteUtils.formatHex(getPrivKeyBytes());
}
public String getPublicKeyAsHex() {
return ByteUtils.formatHex(pub.getEncoded());
}
public String getPrivateKeyAsWiF(Network network) {
return getPrivateKeyEncoded(network).toString();
}
/**
* @deprecated Use {@link #getPrivateKeyEncoded(Network)}
*/
@Deprecated
public String getPrivateKeyAsWiF(NetworkParameters params) {
return getPrivateKeyAsWiF(params.network());
}
private String toString(boolean includePrivate, @Nullable AesKey aesKey, Network network) {
final MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues();
helper.add("pub HEX", getPublicKeyAsHex());
if (includePrivate) {
ECKey decryptedKey = isEncrypted() ? decrypt(Objects.requireNonNull(aesKey)) : this;
try {
helper.add("priv HEX", decryptedKey.getPrivateKeyAsHex());
helper.add("priv WIF", decryptedKey.getPrivateKeyAsWiF(network));
} catch (IllegalStateException e) {
// TODO: Make hasPrivKey() work for deterministic keys and fix this.
} catch (Exception e) {
final String message = e.getMessage();
helper.add("priv EXCEPTION", e.getClass().getName() + (message != null ? ": " + message : ""));
}
}
if (creationTime != null)
helper.add("creationTime", creationTime);
helper.add("keyCrypter", keyCrypter);
if (includePrivate)
helper.add("encryptedPrivateKey", encryptedPrivateKey);
helper.add("isEncrypted", isEncrypted());
helper.add("isPubKeyOnly", isPubKeyOnly());
return helper.toString();
}
/**
* @deprecated Use {@link #toString(boolean, AesKey, Network)}
*/
@Deprecated
private String toString(boolean includePrivate, @Nullable AesKey aesKey, @Nullable NetworkParameters params) {
Network network = (params != null) ? params.network() : BitcoinNetwork.MAINNET;
return toString(includePrivate, aesKey, network);
}
public void formatKeyWithAddress(boolean includePrivateKeys, @Nullable AesKey aesKey, StringBuilder builder,
Network network, ScriptType outputScriptType, @Nullable String comment) {
builder.append(" addr:");
if (outputScriptType != null) {
builder.append(toAddress(outputScriptType, network));
} else {
builder.append(toAddress(ScriptType.P2PKH, network));
if (isCompressed())
builder.append(',').append(toAddress(ScriptType.P2WPKH, network));
}
if (!isCompressed())
builder.append(" UNCOMPRESSED");
builder.append(" hash160:");
builder.append(ByteUtils.formatHex(getPubKeyHash()));
if (creationTime != null)
builder.append(" creationTime:").append(creationTime).append(" [")
.append(TimeUtils.dateTimeFormat(creationTime)).append("]");
if (comment != null)
builder.append(" (").append(comment).append(")");
builder.append("\n");
if (includePrivateKeys) {
builder.append(" ");
builder.append(toStringWithPrivate(aesKey, network));
builder.append("\n");
}
}
/**
* @deprecated Use {@link #formatKeyWithAddress(boolean, AesKey, StringBuilder, Network, ScriptType, String)}
*/
@Deprecated
public void formatKeyWithAddress(boolean includePrivateKeys, @Nullable AesKey aesKey, StringBuilder builder,
NetworkParameters params, ScriptType outputScriptType, @Nullable String comment) {
formatKeyWithAddress(includePrivateKeys, aesKey, builder, params.network(), outputScriptType, comment);
}
/** The string that prefixes all text messages signed using Bitcoin keys. */
private static final String BITCOIN_SIGNED_MESSAGE_HEADER = "Bitcoin Signed Message:\n";
private static final byte[] BITCOIN_SIGNED_MESSAGE_HEADER_BYTES = BITCOIN_SIGNED_MESSAGE_HEADER.getBytes(StandardCharsets.UTF_8);
/**
* <p>Given a textual message, returns a byte buffer formatted as follows:</p>
* <p>{@code [24] "Bitcoin Signed Message:\n" [message.length as a varint] message}</p>
*/
private static byte[] formatMessageForSigning(String message) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(BITCOIN_SIGNED_MESSAGE_HEADER_BYTES.length);
bos.write(BITCOIN_SIGNED_MESSAGE_HEADER_BYTES);
byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8);
VarInt size = VarInt.of(messageBytes.length);
bos.write(size.serialize());
bos.write(messageBytes);
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
}
}
| 67,431
| 46.089385
| 149
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/PBKDF2SHA512.java
|
/*
* Copyright (c) 2012 Cole Barnes [cryptofreek{at}gmail{dot}com]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package org.bitcoinj.crypto;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
/**
* <p>This is a clean-room implementation of PBKDF2 using RFC 2898 as a reference.</p>
*
* <p>RFC 2898: http://tools.ietf.org/html/rfc2898#section-5.2</p>
*
* <p>This code passes all RFC 6070 test vectors: http://tools.ietf.org/html/rfc6070</p>
*
* <p>http://cryptofreek.org/2012/11/29/pbkdf2-pure-java-implementation/<br>
* Modified to use SHA-512 - Ken Sedgwick ken@bonsai.com</p>
*/
public class PBKDF2SHA512 {
public static byte[] derive(String P, String S, int c, int dkLen) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
int hLen = 20;
if (dkLen > ((Math.pow(2, 32)) - 1) * hLen) {
throw new IllegalArgumentException("derived key too long");
} else {
int l = (int) Math.ceil((double) dkLen / (double) hLen);
// int r = dkLen - (l-1)*hLen;
for (int i = 1; i <= l; i++) {
byte[] T = F(P, S, c, i);
baos.write(T);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
byte[] baDerived = new byte[dkLen];
System.arraycopy(baos.toByteArray(), 0, baDerived, 0, baDerived.length);
return baDerived;
}
private static byte[] F(String P, String S, int c, int i) throws Exception {
byte[] U_LAST = null;
byte[] U_XOR = null;
SecretKeySpec key = new SecretKeySpec(P.getBytes(StandardCharsets.UTF_8), "HmacSHA512");
Mac mac = Mac.getInstance(key.getAlgorithm());
mac.init(key);
for (int j = 0; j < c; j++) {
if (j == 0) {
byte[] baS = S.getBytes(StandardCharsets.UTF_8);
byte[] baI = INT(i);
byte[] baU = new byte[baS.length + baI.length];
System.arraycopy(baS, 0, baU, 0, baS.length);
System.arraycopy(baI, 0, baU, baS.length, baI.length);
U_XOR = mac.doFinal(baU);
U_LAST = U_XOR;
mac.reset();
} else {
byte[] baU = mac.doFinal(U_LAST);
mac.reset();
for (int k = 0; k < U_XOR.length; k++) {
U_XOR[k] = (byte) (U_XOR[k] ^ baU[k]);
}
U_LAST = baU;
}
}
return U_XOR;
}
private static byte[] INT(int i) {
ByteBuffer bb = ByteBuffer.allocate(4);
bb.order(ByteOrder.BIG_ENDIAN);
bb.putInt(i);
return bb.array();
}
}
| 3,961
| 33.754386
| 96
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/LazyECPoint.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.crypto;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECFieldElement;
import org.bouncycastle.math.ec.ECPoint;
import javax.annotation.Nullable;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Objects;
/**
* A wrapper around ECPoint that delays decoding of the point for as long as possible. This is useful because point
* encode/decode in Bouncy Castle is quite slow especially on Dalvik, as it often involves decompression/recompression.
*/
public class LazyECPoint {
// If curve is set, bits is also set. If curve is unset, point is set and bits is unset. Point can be set along
// with curve and bits when the cached form has been accessed and thus must have been converted.
private final ECCurve curve;
private final byte[] bits;
private final boolean compressed;
// This field is effectively final - once set it won't change again. However it can be set after
// construction.
@Nullable
private ECPoint point;
/**
* Construct a LazyECPoint from a public key. Due to the delayed decoding of the point the validation of the
* public key is delayed too, e.g. until a getter is called.
*
* @param curve a curve the point is on
* @param bits public key bytes
*/
public LazyECPoint(ECCurve curve, byte[] bits) {
this.curve = curve;
this.bits = bits;
this.compressed = ECKey.isPubKeyCompressed(bits);
}
/**
* Construct a LazyECPoint from an already decoded point.
*
* @param point the wrapped point
* @param compressed true if the represented public key is compressed
*/
public LazyECPoint(ECPoint point, boolean compressed) {
this.point = Objects.requireNonNull(point).normalize();
this.compressed = compressed;
this.curve = null;
this.bits = null;
}
/**
* Returns a compressed version of this elliptic curve point. Returns the same point if it's already compressed.
* See the {@link ECKey} class docs for a discussion of point compression.
*/
public LazyECPoint compress() {
return compressed ? this : new LazyECPoint(get(), true);
}
/**
* Returns a decompressed version of this elliptic curve point. Returns the same point if it's already compressed.
* See the {@link ECKey} class docs for a discussion of point compression.
*/
public LazyECPoint decompress() {
return !compressed ? this : new LazyECPoint(get(), false);
}
public ECPoint get() {
if (point == null)
point = curve.decodePoint(bits);
return point;
}
public byte[] getEncoded() {
if (bits != null)
return Arrays.copyOf(bits, bits.length);
else
return get().getEncoded(compressed);
}
// Delegated methods.
public ECPoint getDetachedPoint() {
return get().getDetachedPoint();
}
public boolean isInfinity() {
return get().isInfinity();
}
public ECPoint timesPow2(int e) {
return get().timesPow2(e);
}
public ECFieldElement getYCoord() {
return get().getYCoord();
}
public ECFieldElement[] getZCoords() {
return get().getZCoords();
}
public boolean isNormalized() {
return get().isNormalized();
}
public boolean isCompressed() {
return compressed;
}
public ECPoint multiply(BigInteger k) {
return get().multiply(k);
}
public ECPoint subtract(ECPoint b) {
return get().subtract(b);
}
public boolean isValid() {
return get().isValid();
}
public ECPoint scaleY(ECFieldElement scale) {
return get().scaleY(scale);
}
public ECFieldElement getXCoord() {
return get().getXCoord();
}
public ECPoint scaleX(ECFieldElement scale) {
return get().scaleX(scale);
}
public boolean equals(ECPoint other) {
return get().equals(other);
}
public ECPoint negate() {
return get().negate();
}
public ECPoint threeTimes() {
return get().threeTimes();
}
public ECFieldElement getZCoord(int index) {
return get().getZCoord(index);
}
public byte[] getEncoded(boolean compressed) {
if (compressed == isCompressed() && bits != null)
return Arrays.copyOf(bits, bits.length);
else
return get().getEncoded(compressed);
}
public ECPoint add(ECPoint b) {
return get().add(b);
}
public ECPoint twicePlus(ECPoint b) {
return get().twicePlus(b);
}
public ECCurve getCurve() {
return get().getCurve();
}
public ECPoint normalize() {
return get().normalize();
}
public ECFieldElement getY() {
return this.normalize().getYCoord();
}
public ECPoint twice() {
return get().twice();
}
public ECFieldElement getAffineYCoord() {
return get().getAffineYCoord();
}
public ECFieldElement getAffineXCoord() {
return get().getAffineXCoord();
}
public ECFieldElement getX() {
return this.normalize().getXCoord();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return Arrays.equals(getCanonicalEncoding(), ((LazyECPoint)o).getCanonicalEncoding());
}
@Override
public int hashCode() {
return Arrays.hashCode(getCanonicalEncoding());
}
private byte[] getCanonicalEncoding() {
return getEncoded(true);
}
}
| 6,301
| 26.519651
| 119
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/ChildNumber.java
|
/*
* Copyright 2013 Matija Mazi.
*
* 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.
*/
package org.bitcoinj.crypto;
import java.util.List;
import java.util.Locale;
/**
* <p>This is just a wrapper for the i (child number) as per BIP 32 with a boolean getter for the most significant bit
* and a getter for the actual 0-based child number. A {@link List} of these forms a <i>path</i> through a
* {@link DeterministicHierarchy}. This class is immutable.
*/
public class ChildNumber implements Comparable<ChildNumber> {
/**
* The bit that's set in the child number to indicate whether this key is "hardened". Given a hardened key, it is
* not possible to derive a child public key if you know only the hardened public key. With a non-hardened key this
* is possible, so you can derive trees of public keys given only a public parent, but the downside is that it's
* possible to leak private keys if you disclose a parent public key and a child private key (elliptic curve maths
* allows you to work upwards).
*/
public static final int HARDENED_BIT = 0x80000000;
public static final ChildNumber ZERO = new ChildNumber(0);
public static final ChildNumber ZERO_HARDENED = new ChildNumber(0, true);
public static final ChildNumber ONE = new ChildNumber(1);
public static final ChildNumber ONE_HARDENED = new ChildNumber(1, true);
// See BIP-43, Purpose Field for Deterministic Wallets: https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki
public static final ChildNumber PURPOSE_BIP44 = new ChildNumber(44, true); // P2PKH
public static final ChildNumber PURPOSE_BIP49 = new ChildNumber(49, true); // P2WPKH-nested-in-P2SH
public static final ChildNumber PURPOSE_BIP84 = new ChildNumber(84, true); // P2WPKH
public static final ChildNumber PURPOSE_BIP86 = new ChildNumber(86, true); // P2TR
public static final ChildNumber COINTYPE_BTC = new ChildNumber(0, true); // MainNet
public static final ChildNumber COINTYPE_TBTC = new ChildNumber(1, true); // TestNet
public static final ChildNumber CHANGE_RECEIVING = new ChildNumber(0, false);
public static final ChildNumber CHANGE_CHANGE = new ChildNumber(1, false);
/** Integer i as per BIP 32 spec, including the MSB denoting derivation type (0 = public, 1 = private) **/
private final int i;
public ChildNumber(int childNumber, boolean isHardened) {
if (hasHardenedBit(childNumber))
throw new IllegalArgumentException("Most significant bit is reserved and shouldn't be set: " + childNumber);
i = isHardened ? (childNumber | HARDENED_BIT) : childNumber;
}
public ChildNumber(int i) {
this.i = i;
}
/** Returns the uint32 encoded form of the path element, including the most significant bit. */
public int getI() {
return i;
}
/** Returns the uint32 encoded form of the path element, including the most significant bit. */
public int i() { return i; }
public boolean isHardened() {
return hasHardenedBit(i);
}
private static boolean hasHardenedBit(int a) {
return (a & HARDENED_BIT) != 0;
}
/** Returns the child number without the hardening bit set (i.e. index in that part of the tree). */
public int num() {
return i & (~HARDENED_BIT);
}
@Override
public String toString() {
return String.format(Locale.US, "%d%s", num(), isHardened() ? "H" : "");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return i == ((ChildNumber)o).i;
}
@Override
public int hashCode() {
return i;
}
@Override
public int compareTo(ChildNumber other) {
// note that in this implementation compareTo() is not consistent with equals()
return Integer.compare(this.num(), other.num());
}
}
| 4,473
| 39.306306
| 122
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/HDUtils.java
|
/*
* Copyright 2013 Matija Mazi.
* Copyright 2014 Giannis Dzegoutanis.
*
* 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.
*/
package org.bitcoinj.crypto;
import org.bouncycastle.crypto.digests.SHA512Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import java.nio.ByteBuffer;
import java.util.Arrays;
/**
* Static utilities used in BIP 32 Hierarchical Deterministic Wallets (HDW).
*/
public final class HDUtils {
static HMac createHmacSha512Digest(byte[] key) {
SHA512Digest digest = new SHA512Digest();
HMac hMac = new HMac(digest);
hMac.init(new KeyParameter(key));
return hMac;
}
static byte[] hmacSha512(HMac hmacSha512, byte[] input) {
hmacSha512.reset();
hmacSha512.update(input, 0, input.length);
byte[] out = new byte[64];
hmacSha512.doFinal(out, 0);
return out;
}
public static byte[] hmacSha512(byte[] key, byte[] data) {
return hmacSha512(createHmacSha512Digest(key), data);
}
static byte[] toCompressed(byte[] uncompressedPoint) {
return ECKey.CURVE.getCurve().decodePoint(uncompressedPoint).getEncoded(true);
}
static byte[] longTo4ByteArray(long n) {
byte[] bytes = Arrays.copyOfRange(ByteBuffer.allocate(8).putLong(n).array(), 4, 8);
assert bytes.length == 4 : bytes.length;
return bytes;
}
}
| 1,933
| 30.704918
| 91
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/DumpedPrivateKey.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2015 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.crypto;
import org.bitcoinj.base.Base58;
import org.bitcoinj.base.Network;
import org.bitcoinj.base.exceptions.AddressFormatException;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.params.Networks;
import javax.annotation.Nullable;
import java.util.Arrays;
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
/**
* Parses and generates private keys in the form used by the Bitcoin "dumpprivkey" command. This is the private key
* bytes with a header byte and 4 checksum bytes at the end. If there are 33 private key bytes instead of 32, then
* the last byte is a discriminator value for the compressed pubkey.
*/
public class DumpedPrivateKey extends EncodedPrivateKey {
/**
* Construct a private key from its Base58 representation.
* @param network
* The expected Network or null if you don't want validation.
* @param base58
* The textual form of the private key.
* @throws AddressFormatException
* if the given base58 doesn't parse or the checksum is invalid
* @throws AddressFormatException.WrongNetwork
* if the given private key is valid but for a different chain (eg testnet vs mainnet)
*/
public static DumpedPrivateKey fromBase58(@Nullable Network network, String base58)
throws AddressFormatException, AddressFormatException.WrongNetwork {
byte[] versionAndDataBytes = Base58.decodeChecked(base58);
int version = versionAndDataBytes[0] & 0xFF;
byte[] bytes = Arrays.copyOfRange(versionAndDataBytes, 1, versionAndDataBytes.length);
if (network == null) {
for (NetworkParameters p : Networks.get())
if (version == p.getDumpedPrivateKeyHeader())
return new DumpedPrivateKey(p.network(), bytes);
throw new AddressFormatException.InvalidPrefix("No network found for version " + version);
} else {
NetworkParameters params = NetworkParameters.of(network);
if (version == params.getDumpedPrivateKeyHeader())
return new DumpedPrivateKey(network, bytes);
throw new AddressFormatException.WrongNetwork(version);
}
}
/**
* Construct a private key from its Base58 representation.
* @param params
* The expected Network or null if you don't want validation.
* @param base58
* The textual form of the private key.
* @throws AddressFormatException
* if the given base58 doesn't parse or the checksum is invalid
* @throws AddressFormatException.WrongNetwork
* if the given private key is valid but for a different chain (eg testnet vs mainnet)
* @deprecated use {@link #fromBase58(Network, String)}
*/
@Deprecated
public static DumpedPrivateKey fromBase58(@Nullable NetworkParameters params, String base58)
throws AddressFormatException, AddressFormatException.WrongNetwork {
return fromBase58(params == null ? null : params.network(), base58);
}
private DumpedPrivateKey(Network network, byte[] bytes) {
super(network, bytes);
if (bytes.length != 32 && bytes.length != 33)
throw new AddressFormatException.InvalidDataLength(
"Wrong number of bytes for a private key (32 or 33): " + bytes.length);
}
// Used by ECKey.getPrivateKeyEncoded()
DumpedPrivateKey(Network network, byte[] keyBytes, boolean compressed) {
this(network, encode(keyBytes, compressed));
}
/**
* Returns the base58-encoded textual form, including version and checksum bytes.
*
* @return textual form
*/
public String toBase58() {
NetworkParameters params = NetworkParameters.of(network);
return Base58.encodeChecked(params.getDumpedPrivateKeyHeader(), bytes);
}
private static byte[] encode(byte[] keyBytes, boolean compressed) {
checkArgument(keyBytes.length == 32, () -> "private keys must be 32 bytes");
if (!compressed) {
return keyBytes;
} else {
// Keys that have compressed public components have an extra 1 byte on the end in dumped form.
byte[] bytes = new byte[33];
System.arraycopy(keyBytes, 0, bytes, 0, 32);
bytes[32] = 1;
return bytes;
}
}
/**
* Returns an ECKey created from this encoded private key.
*/
public ECKey getKey() {
return ECKey.fromPrivate(Arrays.copyOf(bytes, 32), isPubKeyCompressed());
}
/**
* Returns true if the public key corresponding to this private key is compressed.
*/
public boolean isPubKeyCompressed() {
return bytes.length == 33 && bytes[32] == 1;
}
@Override
public String toString() {
return toBase58();
}
}
| 5,557
| 38.985612
| 115
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/KeyCrypterScrypt.java
|
/*
* Copyright 2013 Jim Burton.
* Copyright 2014 Andreas Schildbach
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* 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.
*/
package org.bitcoinj.crypto;
import com.google.protobuf.ByteString;
import org.bitcoinj.base.internal.Stopwatch;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.wallet.Protos;
import org.bitcoinj.wallet.Protos.ScryptParameters;
import org.bitcoinj.wallet.Protos.Wallet.EncryptionType;
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.generators.SCrypt;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Objects;
/**
* <p>This class encrypts and decrypts byte arrays and strings using scrypt as the
* key derivation function and AES for the encryption.</p>
*
* <p>You can use this class to:</p>
*
* <p>1) Using a user password, create an AES key that can encrypt and decrypt your private keys.
* To convert the password to the AES key, scrypt is used. This is an algorithm resistant
* to brute force attacks. You can use the ScryptParameters to tune how difficult you
* want this to be generation to be.</p>
*
* <p>2) Using the AES Key generated above, you then can encrypt and decrypt any bytes using
* the AES symmetric cipher. Eight bytes of salt is used to prevent dictionary attacks.</p>
*/
public class KeyCrypterScrypt implements KeyCrypter {
private static final Logger log = LoggerFactory.getLogger(KeyCrypterScrypt.class);
/**
* Key length in bytes.
*/
public static final int KEY_LENGTH = 32; // = 256 bits.
/**
* The size of an AES block in bytes.
* This is also the length of the initialisation vector.
*/
public static final int BLOCK_LENGTH = 16; // = 128 bits.
/**
* The length of the salt used.
*/
public static final int SALT_LENGTH = 8;
static {
secureRandom = new SecureRandom();
}
private static final SecureRandom secureRandom;
/** Returns SALT_LENGTH (8) bytes of random data */
public static byte[] randomSalt() {
byte[] salt = new byte[SALT_LENGTH];
secureRandom.nextBytes(salt);
return salt;
}
// Scrypt parameters.
private final ScryptParameters scryptParameters;
/**
* Encryption/Decryption using default parameters and a random salt.
*/
public KeyCrypterScrypt() {
Protos.ScryptParameters.Builder scryptParametersBuilder = Protos.ScryptParameters.newBuilder().setSalt(
ByteString.copyFrom(randomSalt()));
this.scryptParameters = scryptParametersBuilder.build();
}
/**
* Encryption/Decryption using custom number of iterations parameters and a random salt.
* As of August 2016, a useful value for mobile devices is 4096 (derivation takes about 1 second).
*
* @param iterations
* number of scrypt iterations
*/
public KeyCrypterScrypt(int iterations) {
Protos.ScryptParameters.Builder scryptParametersBuilder = Protos.ScryptParameters.newBuilder()
.setSalt(ByteString.copyFrom(randomSalt())).setN(iterations);
this.scryptParameters = scryptParametersBuilder.build();
}
/**
* Encryption/ Decryption using specified Scrypt parameters.
*
* @param scryptParameters ScryptParameters to use
* @throws NullPointerException if the scryptParameters or any of its N, R or P is null.
*/
public KeyCrypterScrypt(ScryptParameters scryptParameters) {
this.scryptParameters = Objects.requireNonNull(scryptParameters);
// Check there is a non-empty salt.
// (Some early MultiBit wallets has a missing salt so it is not a hard fail).
if (scryptParameters.getSalt() == null
|| scryptParameters.getSalt().toByteArray() == null
|| scryptParameters.getSalt().toByteArray().length == 0) {
log.warn("You are using a ScryptParameters with no salt. Your encryption may be vulnerable to a dictionary attack.");
}
}
/**
* Generate AES key.
*
* This is a very slow operation compared to encrypt/ decrypt so it is normally worth caching the result.
*
* @param password The password to use in key generation
* @return The AesKey containing the created AES key
* @throws KeyCrypterException
*/
@Override
public AesKey deriveKey(CharSequence password) throws KeyCrypterException {
byte[] passwordBytes = null;
try {
passwordBytes = convertToByteArray(password);
byte[] salt = new byte[0];
if ( scryptParameters.getSalt() != null) {
salt = scryptParameters.getSalt().toByteArray();
} else {
// Warn the user that they are not using a salt.
// (Some early MultiBit wallets had a blank salt).
log.warn("You are using a ScryptParameters with no salt. Your encryption may be vulnerable to a dictionary attack.");
}
Stopwatch watch = Stopwatch.start();
byte[] keyBytes = SCrypt.generate(passwordBytes, salt, (int) scryptParameters.getN(), scryptParameters.getR(), scryptParameters.getP(), KEY_LENGTH);
log.info("Deriving key took {} for {}.", watch, scryptParametersString());
return new AesKey(keyBytes);
} catch (Exception e) {
throw new KeyCrypterException("Could not generate key from password and salt.", e);
} finally {
// Zero the password bytes.
if (passwordBytes != null) {
java.util.Arrays.fill(passwordBytes, (byte) 0);
}
}
}
/**
* Password based encryption using AES - CBC 256 bits.
*/
@Override
public EncryptedData encrypt(byte[] plainBytes, AesKey aesKey) throws KeyCrypterException {
Objects.requireNonNull(plainBytes);
Objects.requireNonNull(aesKey);
try {
// Generate iv - each encryption call has a different iv.
byte[] iv = new byte[BLOCK_LENGTH];
secureRandom.nextBytes(iv);
ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.bytes()), iv);
// Encrypt using AES.
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
cipher.init(true, keyWithIv);
byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];
final int length1 = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
final int length2 = cipher.doFinal(encryptedBytes, length1);
return new EncryptedData(iv, Arrays.copyOf(encryptedBytes, length1 + length2));
} catch (Exception e) {
throw new KeyCrypterException("Could not encrypt bytes.", e);
}
}
/**
* Decrypt bytes previously encrypted with this class.
*
* @param dataToDecrypt The data to decrypt
* @param aesKey The AES key to use for decryption
* @return The decrypted bytes
* @throws KeyCrypterException if bytes could not be decrypted
*/
@Override
public byte[] decrypt(EncryptedData dataToDecrypt, AesKey aesKey) throws KeyCrypterException {
Objects.requireNonNull(dataToDecrypt);
Objects.requireNonNull(aesKey);
try {
ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.bytes()), dataToDecrypt.initialisationVector);
// Decrypt the message.
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
cipher.init(false, keyWithIv);
byte[] cipherBytes = dataToDecrypt.encryptedBytes;
byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];
final int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);
final int length2 = cipher.doFinal(decryptedBytes, length1);
return Arrays.copyOf(decryptedBytes, length1 + length2);
} catch (InvalidCipherTextException e) {
throw new KeyCrypterException.InvalidCipherText("Could not decrypt bytes", e);
} catch (RuntimeException e) {
throw new KeyCrypterException("Could not decrypt bytes", e);
}
}
/**
* Convert a CharSequence (which are UTF16) into a byte array.
*
* Note: a String.getBytes() is not used to avoid creating a String of the password in the JVM.
*/
private static byte[] convertToByteArray(CharSequence charSequence) {
Objects.requireNonNull(charSequence);
byte[] byteArray = new byte[charSequence.length() << 1];
for(int i = 0; i < charSequence.length(); i++) {
int bytePosition = i << 1;
byteArray[bytePosition] = (byte) ((charSequence.charAt(i)&0xFF00)>>8);
byteArray[bytePosition + 1] = (byte) (charSequence.charAt(i)&0x00FF);
}
return byteArray;
}
public ScryptParameters getScryptParameters() {
return scryptParameters;
}
/**
* Return the EncryptionType enum value which denotes the type of encryption/ decryption that this KeyCrypter
* can understand.
*/
@Override
public EncryptionType getUnderstoodEncryptionType() {
return EncryptionType.ENCRYPTED_SCRYPT_AES;
}
@Override
public String toString() {
return "AES-" + KEY_LENGTH * 8 + "-CBC, Scrypt (" + scryptParametersString() + ")";
}
private String scryptParametersString() {
return "N=" + scryptParameters.getN() + ", r=" + scryptParameters.getR() + ", p=" + scryptParameters.getP();
}
@Override
public int hashCode() {
return Objects.hash(scryptParameters);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return Objects.equals(scryptParameters, ((KeyCrypterScrypt)o).scryptParameters);
}
}
| 11,089
| 38.607143
| 160
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/EncryptableItem.java
|
/*
* Copyright 2014 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.
*/
package org.bitcoinj.crypto;
import org.bitcoinj.wallet.Protos;
import javax.annotation.Nullable;
import java.time.Instant;
import java.util.Optional;
/**
* Provides a uniform way to access something that can be optionally encrypted with a
* {@link KeyCrypter}, yielding an {@link EncryptedData}, and
* which can have a creation time associated with it.
*/
public interface EncryptableItem {
/** Returns whether the item is encrypted or not. If it is, then {@link #getSecretBytes()} will return null. */
boolean isEncrypted();
/** Returns the raw bytes of the item, if not encrypted, or null if encrypted or the secret is missing. */
@Nullable
byte[] getSecretBytes();
/** Returns the initialization vector and encrypted secret bytes, or null if not encrypted. */
@Nullable
EncryptedData getEncryptedData();
/** Returns an enum constant describing what algorithm was used to encrypt the key or UNENCRYPTED. */
Protos.Wallet.EncryptionType getEncryptionType();
/** Returns the time at which this encryptable item was first created/derived, or empty of unknown. */
Optional<Instant> creationTime();
/** @deprecated use {@link #creationTime()} */
@Deprecated
default long getCreationTimeSeconds() {
Optional<Instant> creationTime = creationTime();
return creationTime.isPresent() ? creationTime.get().getEpochSecond() : 0;
}
}
| 2,011
| 35.581818
| 115
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/DeterministicKey.java
|
/*
* Copyright 2013 Matija Mazi.
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.crypto;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import org.bitcoinj.base.Network;
import org.bitcoinj.base.ScriptType;
import org.bitcoinj.base.internal.ByteUtils;
import org.bitcoinj.base.Base58;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.crypto.internal.CryptoUtils;
import org.bouncycastle.math.ec.ECPoint;
import javax.annotation.Nullable;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
import static org.bitcoinj.base.internal.Preconditions.checkState;
/**
* A deterministic key is a node in a {@link DeterministicHierarchy}. As per
* <a href="https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki">the BIP 32 specification</a> it is a pair
* (key, chaincode). If you know its path in the tree and its chain code you can derive more keys from this. To obtain
* one of these, you can call {@link HDKeyDerivation#createMasterPrivateKey(byte[])}.
*/
public class DeterministicKey extends ECKey {
/** Sorts deterministic keys in the order of their child number. That's <i>usually</i> the order used to derive them. */
public static final Comparator<ECKey> CHILDNUM_ORDER = (k1, k2) -> {
ChildNumber cn1 = ((DeterministicKey) k1).getChildNumber();
ChildNumber cn2 = ((DeterministicKey) k2).getChildNumber();
return cn1.compareTo(cn2);
};
private final DeterministicKey parent;
private final HDPath childNumberPath;
private final int depth;
private int parentFingerprint; // 0 if this key is root node of key hierarchy
/** 32 bytes */
private final byte[] chainCode;
/** Constructs a key from its components. This is not normally something you should use. */
public DeterministicKey(List<ChildNumber> childNumberPath,
byte[] chainCode,
LazyECPoint publicAsPoint,
@Nullable BigInteger priv,
@Nullable DeterministicKey parent) {
super(priv, publicAsPoint.compress());
checkArgument(chainCode.length == 32);
this.parent = parent;
this.childNumberPath = HDPath.M(Objects.requireNonNull(childNumberPath));
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
this.depth = parent == null ? 0 : parent.depth + 1;
this.parentFingerprint = (parent != null) ? parent.getFingerprint() : 0;
}
public DeterministicKey(List<ChildNumber> childNumberPath,
byte[] chainCode,
ECPoint publicAsPoint,
boolean compressed,
@Nullable BigInteger priv,
@Nullable DeterministicKey parent) {
this(childNumberPath, chainCode, new LazyECPoint(publicAsPoint, compressed), priv, parent);
}
/** Constructs a key from its components. This is not normally something you should use. */
public DeterministicKey(HDPath hdPath,
byte[] chainCode,
BigInteger priv,
@Nullable DeterministicKey parent) {
super(priv, ECKey.publicPointFromPrivate(priv), true);
checkArgument(chainCode.length == 32);
this.parent = parent;
this.childNumberPath = Objects.requireNonNull(hdPath);
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
this.depth = parent == null ? 0 : parent.depth + 1;
this.parentFingerprint = (parent != null) ? parent.getFingerprint() : 0;
}
/** Constructs a key from its components. This is not normally something you should use. */
public DeterministicKey(List<ChildNumber> childNumberPath,
byte[] chainCode,
KeyCrypter crypter,
LazyECPoint pub,
EncryptedData priv,
@Nullable DeterministicKey parent) {
this(childNumberPath, chainCode, pub, null, parent);
this.encryptedPrivateKey = Objects.requireNonNull(priv);
this.keyCrypter = Objects.requireNonNull(crypter);
}
/**
* Return the fingerprint of this key's parent as an int value, or zero if this key is the
* root node of the key hierarchy. Raise an exception if the arguments are inconsistent.
* This method exists to avoid code repetition in the constructors.
*/
private int ascertainParentFingerprint(int parentFingerprint)
throws IllegalArgumentException {
if (parentFingerprint != 0) {
if (parent != null)
checkArgument(parent.getFingerprint() == parentFingerprint, () ->
"parent fingerprint mismatch: " + Integer.toHexString(parent.getFingerprint()) + " vs " + Integer.toHexString(parentFingerprint));
return parentFingerprint;
} else return 0;
}
/**
* Constructs a key from its components, including its public key data and possibly-redundant
* information about its parent key. Invoked when deserializing, but otherwise not something that
* you normally should use.
*/
public DeterministicKey(List<ChildNumber> childNumberPath,
byte[] chainCode,
LazyECPoint publicAsPoint,
@Nullable DeterministicKey parent,
int depth,
int parentFingerprint) {
super(null, publicAsPoint.compress());
checkArgument(chainCode.length == 32);
this.parent = parent;
this.childNumberPath = HDPath.M(Objects.requireNonNull(childNumberPath));
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
this.depth = depth;
this.parentFingerprint = ascertainParentFingerprint(parentFingerprint);
}
/**
* Constructs a key from its components, including its private key data and possibly-redundant
* information about its parent key. Invoked when deserializing, but otherwise not something that
* you normally should use.
*/
public DeterministicKey(List<ChildNumber> childNumberPath,
byte[] chainCode,
BigInteger priv,
@Nullable DeterministicKey parent,
int depth,
int parentFingerprint) {
super(priv, ECKey.publicPointFromPrivate(priv), true);
checkArgument(chainCode.length == 32);
this.parent = parent;
this.childNumberPath = HDPath.M(Objects.requireNonNull(childNumberPath));
this.chainCode = Arrays.copyOf(chainCode, chainCode.length);
this.depth = depth;
this.parentFingerprint = ascertainParentFingerprint(parentFingerprint);
}
/** Clones the key */
public DeterministicKey(DeterministicKey keyToClone, DeterministicKey newParent) {
super(keyToClone.priv, keyToClone.pub.get(), keyToClone.pub.isCompressed());
this.parent = newParent;
this.childNumberPath = keyToClone.childNumberPath;
this.chainCode = keyToClone.chainCode;
this.encryptedPrivateKey = keyToClone.encryptedPrivateKey;
this.depth = this.childNumberPath.size();
this.parentFingerprint = this.parent.getFingerprint();
}
/**
* Returns the path through some {@link DeterministicHierarchy} which reaches this keys position in the tree.
* A path can be written as 0/1/0 which means the first child of the root, the second child of that node, then
* the first child of that node.
*/
public HDPath getPath() {
return childNumberPath;
}
/**
* Returns the path of this key as a human-readable string starting with M or m to indicate the master key.
*/
public String getPathAsString() {
return getPath().toString();
}
/**
* Return this key's depth in the hierarchy, where the root node is at depth zero.
* This may be different than the number of segments in the path if this key was
* deserialized without access to its parent.
*/
public int getDepth() {
return depth;
}
/** Returns the last element of the path returned by {@link DeterministicKey#getPath()} */
public ChildNumber getChildNumber() {
return childNumberPath.size() == 0 ? ChildNumber.ZERO : childNumberPath.get(childNumberPath.size() - 1);
}
/**
* Returns the chain code associated with this key. See the specification to learn more about chain codes.
*/
public byte[] getChainCode() {
return chainCode;
}
/**
* Returns RIPE-MD160(SHA256(pub key bytes)).
*/
public byte[] getIdentifier() {
return CryptoUtils.sha256hash160(getPubKey());
}
/** Returns the first 32 bits of the result of {@link #getIdentifier()}. */
public int getFingerprint() {
// TODO: why is this different than armory's fingerprint? BIP 32: "The first 32 bits of the identifier are called the fingerprint."
return ByteBuffer.wrap(Arrays.copyOfRange(getIdentifier(), 0, 4)).getInt();
}
@Nullable
public DeterministicKey getParent() {
return parent;
}
/**
* Return the fingerprint of the key from which this key was derived, if this is a
* child key, or else an array of four zero-value bytes.
*/
public int getParentFingerprint() {
return parentFingerprint;
}
/**
* Returns private key bytes, padded with zeros to 33 bytes.
* @throws java.lang.IllegalStateException if the private key bytes are missing.
*/
public byte[] getPrivKeyBytes33() {
byte[] bytes33 = new byte[33];
byte[] priv = getPrivKeyBytes();
System.arraycopy(priv, 0, bytes33, 33 - priv.length, priv.length);
return bytes33;
}
/**
* Returns the same key with the private bytes removed. May return the same instance. The purpose of this is to save
* memory: the private key can always be very efficiently rederived from a parent that a private key, so storing
* all the private keys in RAM is a poor tradeoff especially on constrained devices. This means that the returned
* key may still be usable for signing and so on, so don't expect it to be a true pubkey-only object! If you want
* that then you should follow this call with a call to {@link #dropParent()}.
*/
public DeterministicKey dropPrivateBytes() {
if (isPubKeyOnly())
return this;
else
return new DeterministicKey(getPath(), getChainCode(), pub, null, parent);
}
/**
* <p>Returns the same key with the parent pointer removed (it still knows its own path and the parent fingerprint).</p>
*
* <p>If this key doesn't have private key bytes stored/cached itself, but could rederive them from the parent, then
* the new key returned by this method won't be able to do that. Thus, using dropPrivateBytes().dropParent() on a
* regular DeterministicKey will yield a new DeterministicKey that cannot sign or do other things involving the
* private key at all.</p>
*/
public DeterministicKey dropParent() {
DeterministicKey key = new DeterministicKey(getPath(), getChainCode(), pub, priv, null);
key.parentFingerprint = parentFingerprint;
return key;
}
static byte[] addChecksum(byte[] input) {
int inputLength = input.length;
byte[] checksummed = new byte[inputLength + 4];
System.arraycopy(input, 0, checksummed, 0, inputLength);
byte[] checksum = Sha256Hash.hashTwice(input);
System.arraycopy(checksum, 0, checksummed, inputLength, 4);
return checksummed;
}
@Override
public DeterministicKey encrypt(KeyCrypter keyCrypter, AesKey aesKey) throws KeyCrypterException {
throw new UnsupportedOperationException("Must supply a new parent for encryption");
}
public DeterministicKey encrypt(KeyCrypter keyCrypter, AesKey aesKey, @Nullable DeterministicKey newParent) throws KeyCrypterException {
// Same as the parent code, except we construct a DeterministicKey instead of an ECKey.
Objects.requireNonNull(keyCrypter);
if (newParent != null)
checkArgument(newParent.isEncrypted());
final byte[] privKeyBytes = getPrivKeyBytes();
checkState(privKeyBytes != null, () -> "Private key is not available");
EncryptedData encryptedPrivateKey = keyCrypter.encrypt(privKeyBytes, aesKey);
DeterministicKey key = new DeterministicKey(childNumberPath, chainCode, keyCrypter, pub, encryptedPrivateKey, newParent);
if (newParent == null) {
Optional<Instant> creationTime = this.creationTime();
if (creationTime.isPresent())
key.setCreationTime(creationTime.get());
else
key.clearCreationTime();
}
return key;
}
/**
* A deterministic key is considered to be 'public key only' if it hasn't got a private key part and it cannot be
* rederived. If the hierarchy is encrypted this returns true.
*/
@Override
public boolean isPubKeyOnly() {
return super.isPubKeyOnly() && (parent == null || parent.isPubKeyOnly());
}
@Override
public boolean hasPrivKey() {
return findParentWithPrivKey() != null;
}
@Nullable
@Override
public byte[] getSecretBytes() {
return priv != null ? getPrivKeyBytes() : null;
}
/**
* A deterministic key is considered to be encrypted if it has access to encrypted private key bytes, OR if its
* parent does. The reason is because the parent would be encrypted under the same key and this key knows how to
* rederive its own private key bytes from the parent, if needed.
*/
@Override
public boolean isEncrypted() {
return priv == null && (super.isEncrypted() || (parent != null && parent.isEncrypted()));
}
/**
* Returns this keys {@link KeyCrypter} <b>or</b> the keycrypter of its parent key.
*/
@Override @Nullable
public KeyCrypter getKeyCrypter() {
if (keyCrypter != null)
return keyCrypter;
else if (parent != null)
return parent.getKeyCrypter();
else
return null;
}
@Override
public ECDSASignature sign(Sha256Hash input, @Nullable AesKey aesKey) throws KeyCrypterException {
if (isEncrypted()) {
// If the key is encrypted, ECKey.sign will decrypt it first before rerunning sign. Decryption walks the
// key hierarchy to find the private key (see below), so, we can just run the inherited method.
return super.sign(input, aesKey);
} else {
// If it's not encrypted, derive the private via the parents.
final BigInteger privateKey = findOrDerivePrivateKey();
if (privateKey == null) {
// This key is a part of a public-key only hierarchy and cannot be used for signing
throw new MissingPrivateKeyException();
}
return super.doSign(input, privateKey);
}
}
@Override
public DeterministicKey decrypt(KeyCrypter keyCrypter, AesKey aesKey) throws KeyCrypterException {
Objects.requireNonNull(keyCrypter);
// Check that the keyCrypter matches the one used to encrypt the keys, if set.
if (this.keyCrypter != null && !this.keyCrypter.equals(keyCrypter))
throw new KeyCrypterException("The keyCrypter being used to decrypt the key is different to the one that was used to encrypt it");
BigInteger privKey = findOrDeriveEncryptedPrivateKey(keyCrypter, aesKey);
DeterministicKey key = new DeterministicKey(childNumberPath, chainCode, privKey, parent);
if (!Arrays.equals(key.getPubKey(), getPubKey()))
throw new KeyCrypterException.PublicPrivateMismatch("Provided AES key is wrong");
if (parent == null) {
Optional<Instant> creationTime = this.creationTime();
if (creationTime.isPresent())
key.setCreationTime(creationTime.get());
else
key.clearCreationTime();
}
return key;
}
@Override
public DeterministicKey decrypt(AesKey aesKey) throws KeyCrypterException {
return (DeterministicKey) super.decrypt(aesKey);
}
// For when a key is encrypted, either decrypt our encrypted private key bytes, or work up the tree asking parents
// to decrypt and re-derive.
private BigInteger findOrDeriveEncryptedPrivateKey(KeyCrypter keyCrypter, AesKey aesKey) {
if (encryptedPrivateKey != null) {
byte[] decryptedKey = keyCrypter.decrypt(encryptedPrivateKey, aesKey);
if (decryptedKey.length != 32)
throw new KeyCrypterException.InvalidCipherText(
"Decrypted key must be 32 bytes long, but is " + decryptedKey.length);
return ByteUtils.bytesToBigInteger(decryptedKey);
}
// Otherwise we don't have it, but maybe we can figure it out from our parents. Walk up the tree looking for
// the first key that has some encrypted private key data.
DeterministicKey cursor = parent;
while (cursor != null) {
if (cursor.encryptedPrivateKey != null) break;
cursor = cursor.parent;
}
if (cursor == null)
throw new KeyCrypterException("Neither this key nor its parents have an encrypted private key");
byte[] parentalPrivateKeyBytes = keyCrypter.decrypt(cursor.encryptedPrivateKey, aesKey);
if (parentalPrivateKeyBytes.length != 32)
throw new KeyCrypterException.InvalidCipherText(
"Decrypted key must be 32 bytes long, but is " + parentalPrivateKeyBytes.length);
return derivePrivateKeyDownwards(cursor, parentalPrivateKeyBytes);
}
private DeterministicKey findParentWithPrivKey() {
DeterministicKey cursor = this;
while (cursor != null) {
if (cursor.priv != null) break;
cursor = cursor.parent;
}
return cursor;
}
@Nullable
private BigInteger findOrDerivePrivateKey() {
DeterministicKey cursor = findParentWithPrivKey();
if (cursor == null)
return null;
return derivePrivateKeyDownwards(cursor, cursor.priv.toByteArray());
}
private BigInteger derivePrivateKeyDownwards(DeterministicKey cursor, byte[] parentalPrivateKeyBytes) {
DeterministicKey downCursor = new DeterministicKey(cursor.childNumberPath, cursor.chainCode,
cursor.pub, ByteUtils.bytesToBigInteger(parentalPrivateKeyBytes), cursor.parent);
// Now we have to rederive the keys along the path back to ourselves. That path can be found by just truncating
// our path with the length of the parents path.
List<ChildNumber> path = childNumberPath.subList(cursor.getPath().size(), childNumberPath.size());
for (ChildNumber num : path) {
downCursor = HDKeyDerivation.deriveChildKey(downCursor, num);
}
// downCursor is now the same key as us, but with private key bytes.
// If it's not, it means we tried decrypting with an invalid password and earlier checks e.g. for padding didn't
// catch it.
if (!downCursor.pub.equals(pub))
throw new KeyCrypterException.PublicPrivateMismatch("Could not decrypt bytes");
return Objects.requireNonNull(downCursor.priv);
}
/**
* Derives a child at the given index using hardened derivation. Note: {@code index} is
* not the "i" value. If you want the softened derivation, then use instead
* {@code HDKeyDerivation.deriveChildKey(this, new ChildNumber(child, false))}.
*/
public DeterministicKey derive(int child) {
return HDKeyDerivation.deriveChildKey(this, new ChildNumber(child, true));
}
/**
* Returns the private key of this deterministic key. Even if this object isn't storing the private key,
* it can be re-derived by walking up to the parents if necessary and this is what will happen.
* @throws java.lang.IllegalStateException if the parents are encrypted or a watching chain.
*/
@Override
public BigInteger getPrivKey() {
final BigInteger key = findOrDerivePrivateKey();
checkState(key != null, () ->
"private key bytes not available");
return key;
}
@VisibleForTesting
byte[] serialize(Network network, boolean pub) {
return serialize(network, pub, ScriptType.P2PKH);
}
/**
* @deprecated Use {@link #serialize(Network, boolean)}
*/
@VisibleForTesting
@Deprecated
byte[] serialize(NetworkParameters params, boolean pub) {
return serialize(params.network(), pub);
}
// TODO: remove outputScriptType parameter and merge with the two-param serialize() method. When deprecated serializePubB58/serializePrivB58 methods are removed.
private byte[] serialize(Network network, boolean pub, ScriptType outputScriptType) {
// TODO: Remove use of NetworkParameters after we can get BIP32 headers from Network enum
NetworkParameters params = NetworkParameters.of(network);
ByteBuffer ser = ByteBuffer.allocate(78);
if (outputScriptType == ScriptType.P2PKH)
ser.putInt(pub ? params.getBip32HeaderP2PKHpub() : params.getBip32HeaderP2PKHpriv());
else if (outputScriptType == ScriptType.P2WPKH)
ser.putInt(pub ? params.getBip32HeaderP2WPKHpub() : params.getBip32HeaderP2WPKHpriv());
else
throw new IllegalStateException(outputScriptType.toString());
ser.put((byte) getDepth());
ser.putInt(getParentFingerprint());
ser.putInt(getChildNumber().i());
ser.put(getChainCode());
ser.put(pub ? getPubKey() : getPrivKeyBytes33());
checkState(ser.position() == 78);
return ser.array();
}
/**
* Serialize public key to Base58
* <p>
* outputScriptType should not be used in generating "xpub" format. (and "ypub", "zpub", etc. should not be used)
* @param network which network to serialize key for
* @param outputScriptType output script type
* @return the key serialized as a Base58 address
* @see <a href="https://bitcoin.stackexchange.com/questions/89261/why-does-importmulti-not-support-zpub-and-ypub/89281#89281">Why does importmulti not support zpub and ypub?</a>
* @deprecated Use a {@link #serializePubB58(Network)} or a descriptor if you need output type information
*/
public String serializePubB58(Network network, ScriptType outputScriptType) {
return toBase58(serialize(network, true, outputScriptType));
}
/**
* @deprecated Use {@link #serializePubB58(Network, ScriptType)}
*/
@Deprecated
public String serializePubB58(NetworkParameters params, ScriptType outputScriptType) {
return serializePubB58(params.network(), outputScriptType);
}
/**
* Serialize private key to Base58
* <p>
* outputScriptType should not be used in generating "xprv" format. (and "zprv", "vprv", etc. should not be used)
* @param network which network to serialize key for
* @param outputScriptType output script type
* @return the key serialized as a Base58 address
* @see <a href="https://bitcoin.stackexchange.com/questions/89261/why-does-importmulti-not-support-zpub-and-ypub/89281#89281">Why does importmulti not support zpub and ypub?</a>
* @deprecated Use a {@link #serializePrivB58(Network)} or a descriptor if you need output type information
*/
public String serializePrivB58(Network network, ScriptType outputScriptType) {
return toBase58(serialize(network, false, outputScriptType));
}
/**
* @deprecated Use {@link #serializePrivB58(Network, ScriptType)}
*/
@Deprecated
public String serializePrivB58(NetworkParameters params, ScriptType outputScriptType) {
return serializePrivB58(params.network(), outputScriptType);
}
/**
* Serialize public key to Base58 (either "xpub" or "tpub")
* @param network which network to serialize key for
* @return the key serialized as a Base58 address
*/
public String serializePubB58(Network network) {
return toBase58(serialize(network, true));
}
/**
* @deprecated Use {@link #serializePubB58(Network)}
*/
@Deprecated
public String serializePubB58(NetworkParameters params) {
return serializePubB58(params.network());
}
/**
* Serialize private key to Base58 (either "xprv" or "tprv")
* @param network which network to serialize key for
* @return the key serialized as a Base58 address
*/
public String serializePrivB58(Network network) {
return toBase58(serialize(network, false));
}
/**
* @deprecated Use {@link #serializePrivB58(Network)}
*/
@Deprecated
public String serializePrivB58(NetworkParameters params) {
return serializePrivB58(params.network());
}
static String toBase58(byte[] ser) {
return Base58.encode(addChecksum(ser));
}
/** Deserialize a base-58-encoded HD Key with no parent */
public static DeterministicKey deserializeB58(String base58, Network network) {
return deserializeB58(null, base58, network);
}
/**
* @deprecated Use {@link #deserializeB58(String, Network)}
*/
@Deprecated
public static DeterministicKey deserializeB58(String base58, NetworkParameters params) {
return deserializeB58(base58, params.network());
}
/**
* Deserialize a base-58-encoded HD Key.
* @param parent The parent node in the given key's deterministic hierarchy.
* @throws IllegalArgumentException if the base58 encoded key could not be parsed.
*/
public static DeterministicKey deserializeB58(@Nullable DeterministicKey parent, String base58, Network network) {
return deserialize(network, Base58.decodeChecked(base58), parent);
}
/**
* @deprecated Use {@link #deserializeB58(DeterministicKey, String, Network)}
*/
@Deprecated
public static DeterministicKey deserializeB58(@Nullable DeterministicKey parent, String base58, NetworkParameters params) {
return deserializeB58(parent, base58, params.network());
}
/**
* Deserialize an HD Key with no parent
*/
public static DeterministicKey deserialize(Network network, byte[] serializedKey) {
return deserialize(network, serializedKey, null);
}
/**
* Deserialize an HD Key with no parent
* @deprecated Use {@link #deserialize(Network, byte[])}
*/
@Deprecated
public static DeterministicKey deserialize(NetworkParameters params, byte[] serializedKey) {
return deserialize(params.network(), serializedKey);
}
/**
* Deserialize an HD Key.
* @param parent The parent node in the given key's deterministic hierarchy.
*/
public static DeterministicKey deserialize(Network network, byte[] serializedKey, @Nullable DeterministicKey parent) {
ByteBuffer buffer = ByteBuffer.wrap(serializedKey);
int header = buffer.getInt();
// TODO: Remove us of NetworkParameters when we can get BIP32 header info from Network
NetworkParameters params = NetworkParameters.of(network);
final boolean pub = header == params.getBip32HeaderP2PKHpub() || header == params.getBip32HeaderP2WPKHpub();
final boolean priv = header == params.getBip32HeaderP2PKHpriv() || header == params.getBip32HeaderP2WPKHpriv();
if (!(pub || priv))
throw new IllegalArgumentException("Unknown header bytes: " + toBase58(serializedKey).substring(0, 4));
int depth = buffer.get() & 0xFF; // convert signed byte to positive int since depth cannot be negative
final int parentFingerprint = buffer.getInt();
final int i = buffer.getInt();
final ChildNumber childNumber = new ChildNumber(i);
HDPath path;
if (parent != null) {
if (parentFingerprint == 0)
throw new IllegalArgumentException("Parent was provided but this key doesn't have one");
if (parent.getFingerprint() != parentFingerprint)
throw new IllegalArgumentException("Parent fingerprints don't match");
path = parent.getPath().extend(childNumber);
if (path.size() != depth)
throw new IllegalArgumentException("Depth does not match");
} else {
if (depth >= 1)
// We have been given a key that is not a root key, yet we lack the object representing the parent.
// This can happen when deserializing an account key for a watching wallet. In this case, we assume that
// the client wants to conceal the key's position in the hierarchy. The path is truncated at the
// parent's node.
path = HDPath.M(childNumber);
else path = HDPath.M();
}
byte[] chainCode = new byte[32];
buffer.get(chainCode);
byte[] data = new byte[33];
buffer.get(data);
checkArgument(!buffer.hasRemaining(), () ->
"found unexpected data in key");
if (pub) {
return new DeterministicKey(path, chainCode, new LazyECPoint(ECKey.CURVE.getCurve(), data), parent, depth, parentFingerprint);
} else {
return new DeterministicKey(path, chainCode, ByteUtils.bytesToBigInteger(data), parent, depth, parentFingerprint);
}
}
/**
* Deserialize an HD Key.
* @deprecated Use {@link #deserialize(Network, byte[], DeterministicKey)}
*/
@Deprecated
public static DeterministicKey deserialize(NetworkParameters params, byte[] serializedKey, @Nullable DeterministicKey parent) {
return deserialize(params.network(), serializedKey, parent);
}
/**
* The creation time of a deterministic key is equal to that of its parent, unless this key is the root of a tree
* in which case the time is stored alongside the key as per normal, see {@link ECKey#creationTime()}.
*/
@Override
public Optional<Instant> creationTime() {
if (parent != null)
return parent.creationTime();
else
return super.creationTime();
}
/**
* The creation time of a deterministic key is equal to that of its parent, unless this key is the root of a tree.
* Thus, setting the creation time on a leaf is forbidden.
* @param creationTime creation time of this key
*/
@Override
public void setCreationTime(Instant creationTime) {
if (parent != null)
throw new IllegalStateException("Creation time can only be set on root keys.");
else
super.setCreationTime(creationTime);
}
/**
* Clears the creation time of this key. This is mainly used deserialization and cloning. Normally you should not
* need to use this, as keys should have proper creation times whenever possible.
*/
@Override
public void clearCreationTime() {
if (parent != null)
throw new IllegalStateException("Creation time can only be cleared on root keys.");
else
super.clearCreationTime();
}
/** @deprecated use {@link #setCreationTime(Instant)} */
@Deprecated
public void setCreationTimeSeconds(long creationTimeSecs) {
if (creationTimeSecs > 0)
setCreationTime(Instant.ofEpochSecond(creationTimeSecs));
else if (creationTimeSecs == 0)
clearCreationTime();
else
throw new IllegalArgumentException("Cannot set creation time to negative value: " + creationTimeSecs);
}
/**
* Verifies equality of all fields but NOT the parent pointer (thus the same key derived in two separate hierarchy
* objects will equal each other.
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DeterministicKey other = (DeterministicKey) o;
return super.equals(other)
&& Arrays.equals(this.chainCode, other.chainCode)
&& Objects.equals(this.childNumberPath, other.childNumberPath);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), Arrays.hashCode(chainCode), childNumberPath);
}
@Override
public String toString() {
final MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues();
helper.add("pub", ByteUtils.formatHex(pub.getEncoded()));
helper.add("chainCode", ByteUtils.formatHex(chainCode));
helper.add("path", getPathAsString());
Optional<Instant> creationTime = this.creationTime();
if (!creationTime.isPresent())
helper.add("creationTimeSeconds", "unknown");
else if (parent != null)
helper.add("creationTimeSeconds", creationTime.get().getEpochSecond() + " (inherited)");
else
helper.add("creationTimeSeconds", creationTime.get().getEpochSecond());
helper.add("isEncrypted", isEncrypted());
helper.add("isPubKeyOnly", isPubKeyOnly());
return helper.toString();
}
@Override
public void formatKeyWithAddress(boolean includePrivateKeys, @Nullable AesKey aesKey, StringBuilder builder,
Network network, ScriptType outputScriptType, @Nullable String comment) {
builder.append(" addr:").append(toAddress(outputScriptType, network).toString());
builder.append(" hash160:").append(ByteUtils.formatHex(getPubKeyHash()));
builder.append(" (").append(getPathAsString());
if (comment != null)
builder.append(", ").append(comment);
builder.append(")\n");
if (includePrivateKeys) {
builder.append(" ").append(toStringWithPrivate(aesKey, network)).append("\n");
}
}
/**
* @deprecated Use {@link #formatKeyWithAddress(boolean, AesKey, StringBuilder, Network, ScriptType, String)}
*/
@Override
@Deprecated
public void formatKeyWithAddress(boolean includePrivateKeys, @Nullable AesKey aesKey, StringBuilder builder,
NetworkParameters params, ScriptType outputScriptType, @Nullable String comment) {
formatKeyWithAddress(includePrivateKeys, aesKey, builder, params.network(), outputScriptType, comment);
}
}
| 35,879
| 42.970588
| 182
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/EncodedPrivateKey.java
|
/*
* Copyright 2011 Google Inc.
* Copyright 2018 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.crypto;
import org.bitcoinj.base.Network;
import org.bitcoinj.core.NetworkParameters;
import java.util.Arrays;
import java.util.Objects;
/**
* Some form of string-encoded private key. This form is useful for noting them down, e.g. on paper wallets.
*/
public abstract class EncodedPrivateKey {
protected final Network network;
protected final byte[] bytes;
protected EncodedPrivateKey(Network network, byte[] bytes) {
this.network = Objects.requireNonNull(network);
this.bytes = Objects.requireNonNull(bytes);
}
@Deprecated
protected EncodedPrivateKey(NetworkParameters params, byte[] bytes) {
this(Objects.requireNonNull(params).network(), Objects.requireNonNull(bytes));
}
/**
* Get the network this data is prefixed with.
* @return the Network.
*/
public Network network() {
return network;
}
/**
* @return network this data is valid for
* @deprecated Use {@link #network()}
*/
@Deprecated
public final NetworkParameters getParameters() {
return NetworkParameters.of(network);
}
@Override
public int hashCode() {
return Objects.hash(network, Arrays.hashCode(bytes));
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EncodedPrivateKey other = (EncodedPrivateKey) o;
return this.network.equals(other.network) && Arrays.equals(this.bytes, other.bytes);
}
}
| 2,195
| 29.082192
| 108
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/KeyCrypterException.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.crypto;
/**
* <p>Exception to provide the following:</p>
* <ul>
* <li>Provision of encryption / decryption exception</li>
* </ul>
* <p>This base exception acts as a general failure mode not attributable to a specific cause (other than
* that reported in the exception message). Since this is in English, it may not be worth reporting directly
* to the user other than as part of a "general failure to parse" response.</p>
*/
public class KeyCrypterException extends RuntimeException {
private static final long serialVersionUID = -4441989608332681377L;
public KeyCrypterException(String message) {
super(message);
}
public KeyCrypterException(String message, Throwable throwable) {
super(message, throwable);
}
/**
* This exception is thrown when a private key or seed is decrypted, it doesn't match its public key any
* more. This likely means the wrong decryption key has been used.
*/
public static class PublicPrivateMismatch extends KeyCrypterException {
public PublicPrivateMismatch(String message) {
super(message);
}
public PublicPrivateMismatch(String message, Throwable throwable) {
super(message, throwable);
}
}
/**
* This exception is thrown when a private key or seed is decrypted, the decrypted message is damaged
* (e.g. the padding is damaged). This likely means the wrong decryption key has been used.
*/
public static class InvalidCipherText extends KeyCrypterException {
public InvalidCipherText(String message) {
super(message);
}
public InvalidCipherText(String message, Throwable throwable) {
super(message, throwable);
}
}
}
| 2,401
| 34.850746
| 108
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/LinuxSecureRandom.java
|
/*
* Copyright 2013 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.
*/
package org.bitcoinj.crypto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.Provider;
import java.security.SecureRandomSpi;
import java.security.Security;
/**
* A SecureRandom implementation that is able to override the standard JVM provided implementation, and which simply
* serves random numbers by reading /dev/urandom. That is, it delegates to the kernel on UNIX systems and is unusable on
* other platforms. Attempts to manually set the seed are ignored. There is no difference between seed bytes and
* non-seed bytes, they are all from the same source.
*/
public class LinuxSecureRandom extends SecureRandomSpi {
private static final FileInputStream urandom;
private static class LinuxSecureRandomProvider extends Provider {
public LinuxSecureRandomProvider() {
super("LinuxSecureRandom", 1.0, "A Linux specific random number provider that uses /dev/urandom");
put("SecureRandom.LinuxSecureRandom", LinuxSecureRandom.class.getName());
}
}
private static final Logger log = LoggerFactory.getLogger(LinuxSecureRandom.class);
static {
try {
File file = new File("/dev/urandom");
// This stream is deliberately leaked.
urandom = new FileInputStream(file);
if (urandom.read() == -1)
throw new RuntimeException("/dev/urandom not readable?");
// Now override the default SecureRandom implementation with this one.
int position = Security.insertProviderAt(new LinuxSecureRandomProvider(), 1);
if (position != -1)
log.info("Secure randomness will be read from {} only.", file);
else
log.info("Randomness is already secure.");
} catch (FileNotFoundException e) {
// Should never happen.
log.error("/dev/urandom does not appear to exist or is not openable");
throw new RuntimeException(e);
} catch (IOException e) {
log.error("/dev/urandom does not appear to be readable");
throw new RuntimeException(e);
}
}
private final DataInputStream dis;
public LinuxSecureRandom() {
// DataInputStream is not thread safe, so each random object has its own.
dis = new DataInputStream(urandom);
}
@Override
protected void engineSetSeed(byte[] bytes) {
// Ignore.
}
@Override
protected void engineNextBytes(byte[] bytes) {
try {
dis.readFully(bytes); // This will block until all the bytes can be read.
} catch (IOException e) {
throw new RuntimeException(e); // Fatal error. Do not attempt to recover from this.
}
}
@Override
protected byte[] engineGenerateSeed(int i) {
byte[] bits = new byte[i];
engineNextBytes(bits);
return bits;
}
}
| 3,660
| 35.247525
| 120
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/MnemonicCode.java
|
/*
* Copyright 2013 Ken Sedgwick
* Copyright 2014 Andreas Schildbach
*
* 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.
*/
package org.bitcoinj.crypto;
import org.bitcoinj.base.Sha256Hash;
import org.bitcoinj.base.internal.PlatformUtils;
import org.bitcoinj.base.internal.Stopwatch;
import org.bitcoinj.base.internal.TimeUtils;
import org.bitcoinj.base.internal.StreamUtils;
import org.bitcoinj.base.internal.InternalUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.bitcoinj.base.internal.ByteUtils;
import static org.bitcoinj.base.internal.Preconditions.checkArgument;
/**
* A MnemonicCode object may be used to convert between binary seed values and
* lists of words per <a href="https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki">the BIP 39
* specification</a>
*/
public class MnemonicCode {
private static final Logger log = LoggerFactory.getLogger(MnemonicCode.class);
private final List<String> wordList;
private static final String BIP39_ENGLISH_RESOURCE_NAME = "mnemonic/wordlist/english.txt";
private static final String BIP39_ENGLISH_SHA256 = "ad90bf3beb7b0eb7e5acd74727dc0da96e0a280a258354e7293fb7e211ac03db";
/** UNIX time for when the BIP39 standard was finalised. This can be used as a default seed birthday. */
public static final Instant BIP39_STANDARDISATION_TIME = Instant.ofEpochSecond(1369267200);
/**
* @deprecated Use {@link #BIP39_STANDARDISATION_TIME}
*/
@Deprecated
public static final int BIP39_STANDARDISATION_TIME_SECS = Math.toIntExact(BIP39_STANDARDISATION_TIME.getEpochSecond());
private static final int PBKDF2_ROUNDS = 2048;
public static MnemonicCode INSTANCE;
static {
try {
INSTANCE = new MnemonicCode();
} catch (FileNotFoundException e) {
// We expect failure on Android. The developer has to set INSTANCE themselves.
if (!PlatformUtils.isAndroidRuntime())
log.error("Could not find word list", e);
} catch (IOException e) {
log.error("Failed to load word list", e);
}
}
/** Initialise from the included word list. Won't work on Android. */
public MnemonicCode() throws IOException {
this(openDefaultWords(), BIP39_ENGLISH_SHA256);
}
private static InputStream openDefaultWords() throws IOException {
InputStream stream = MnemonicCode.class.getResourceAsStream(BIP39_ENGLISH_RESOURCE_NAME);
if (stream == null)
throw new FileNotFoundException(BIP39_ENGLISH_RESOURCE_NAME);
return stream;
}
/**
* Creates an MnemonicCode object, initializing with words read from the supplied input stream. If a wordListDigest
* is supplied the digest of the words will be checked.
* @param wordstream input stream of 2048 line-seperated words
* @param wordListDigest hex-encoded Sha256 digest to check against
* @throws IOException if there was a problem reading the steam
* @throws IllegalArgumentException if list size is not 2048 or digest mismatch
*/
public MnemonicCode(InputStream wordstream, String wordListDigest) throws IOException, IllegalArgumentException {
MessageDigest md = Sha256Hash.newDigest();
try (BufferedReader br = new BufferedReader(new InputStreamReader(wordstream, StandardCharsets.UTF_8))) {
this.wordList = br.lines()
.peek(word -> md.update(word.getBytes()))
.collect(StreamUtils.toUnmodifiableList());
}
if (this.wordList.size() != 2048)
throw new IllegalArgumentException("input stream did not contain 2048 words");
// If a wordListDigest is supplied check to make sure it matches.
if (wordListDigest != null) {
byte[] digest = md.digest();
String hexdigest = ByteUtils.formatHex(digest);
if (!hexdigest.equals(wordListDigest))
throw new IllegalArgumentException("wordlist digest mismatch");
}
}
/**
* Gets the word list this code uses.
* @return unmodifiable word list
*/
public List<String> getWordList() {
return wordList;
}
/**
* Convert mnemonic word list to seed.
*/
public static byte[] toSeed(List<String> words, String passphrase) {
Objects.requireNonNull(passphrase, "A null passphrase is not allowed.");
// To create binary seed from mnemonic, we use PBKDF2 function
// with mnemonic sentence (in UTF-8) used as a password and
// string "mnemonic" + passphrase (again in UTF-8) used as a
// salt. Iteration count is set to 4096 and HMAC-SHA512 is
// used as a pseudo-random function. Desired length of the
// derived key is 512 bits (= 64 bytes).
//
String pass = InternalUtils.SPACE_JOINER.join(words);
String salt = "mnemonic" + passphrase;
Stopwatch watch = Stopwatch.start();
byte[] seed = PBKDF2SHA512.derive(pass, salt, PBKDF2_ROUNDS, 64);
log.info("PBKDF2 took {}", watch);
return seed;
}
/**
* Convert mnemonic word list to original entropy value.
*/
public byte[] toEntropy(List<String> words) throws MnemonicException.MnemonicLengthException, MnemonicException.MnemonicWordException, MnemonicException.MnemonicChecksumException {
if (words.size() % 3 > 0)
throw new MnemonicException.MnemonicLengthException("Word list size must be multiple of three words.");
if (words.size() == 0)
throw new MnemonicException.MnemonicLengthException("Word list is empty.");
// Look up all the words in the list and construct the
// concatenation of the original entropy and the checksum.
//
int concatLenBits = words.size() * 11;
boolean[] concatBits = new boolean[concatLenBits];
int wordindex = 0;
for (String word : words) {
// Find the words index in the wordlist.
int ndx = Collections.binarySearch(this.wordList, word);
if (ndx < 0)
throw new MnemonicException.MnemonicWordException(word);
// Set the next 11 bits to the value of the index.
for (int ii = 0; ii < 11; ++ii)
concatBits[(wordindex * 11) + ii] = (ndx & (1 << (10 - ii))) != 0;
++wordindex;
}
int checksumLengthBits = concatLenBits / 33;
int entropyLengthBits = concatLenBits - checksumLengthBits;
// Extract original entropy as bytes.
byte[] entropy = new byte[entropyLengthBits / 8];
for (int ii = 0; ii < entropy.length; ++ii)
for (int jj = 0; jj < 8; ++jj)
if (concatBits[(ii * 8) + jj])
entropy[ii] |= 1 << (7 - jj);
// Take the digest of the entropy.
byte[] hash = Sha256Hash.hash(entropy);
boolean[] hashBits = bytesToBits(hash);
// Check all the checksum bits.
for (int i = 0; i < checksumLengthBits; ++i)
if (concatBits[entropyLengthBits + i] != hashBits[i])
throw new MnemonicException.MnemonicChecksumException();
return entropy;
}
/**
* Convert entropy data to mnemonic word list.
* @param entropy entropy bits, length must be a multiple of 32 bits
*/
public List<String> toMnemonic(byte[] entropy) {
checkArgument(entropy.length % 4 == 0, () ->
"entropy length not multiple of 32 bits");
checkArgument(entropy.length > 0, () ->
"entropy is empty");
// We take initial entropy of ENT bits and compute its
// checksum by taking first ENT / 32 bits of its SHA256 hash.
byte[] hash = Sha256Hash.hash(entropy);
boolean[] hashBits = bytesToBits(hash);
boolean[] entropyBits = bytesToBits(entropy);
int checksumLengthBits = entropyBits.length / 32;
// We append these bits to the end of the initial entropy.
boolean[] concatBits = new boolean[entropyBits.length + checksumLengthBits];
System.arraycopy(entropyBits, 0, concatBits, 0, entropyBits.length);
System.arraycopy(hashBits, 0, concatBits, entropyBits.length, checksumLengthBits);
// Next we take these concatenated bits and split them into
// groups of 11 bits. Each group encodes number from 0-2047
// which is a position in a wordlist. We convert numbers into
// words and use joined words as mnemonic sentence.
ArrayList<String> words = new ArrayList<>();
int nwords = concatBits.length / 11;
for (int i = 0; i < nwords; ++i) {
int index = 0;
for (int j = 0; j < 11; ++j) {
index <<= 1;
if (concatBits[(i * 11) + j])
index |= 0x1;
}
words.add(this.wordList.get(index));
}
return words;
}
/**
* Check to see if a mnemonic word list is valid.
*/
public void check(List<String> words) throws MnemonicException {
toEntropy(words);
}
private static boolean[] bytesToBits(byte[] data) {
boolean[] bits = new boolean[data.length * 8];
for (int i = 0; i < data.length; ++i)
for (int j = 0; j < 8; ++j)
bits[(i * 8) + j] = (data[i] & (1 << (7 - j))) != 0;
return bits;
}
}
| 10,379
| 38.318182
| 184
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/EncryptedData.java
|
/*
* Copyright 2013 Jim Burton.
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* 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.
*/
package org.bitcoinj.crypto;
import java.util.Arrays;
import java.util.Objects;
/**
* <p>An instance of EncryptedData is a holder for an initialization vector and encrypted bytes. It is typically
* used to hold encrypted private key bytes.</p>
*
* <p>The initialisation vector is random data that is used to initialise the AES block cipher when the
* private key bytes were encrypted. You need these for decryption.</p>
*/
public final class EncryptedData {
public final byte[] initialisationVector;
public final byte[] encryptedBytes;
public EncryptedData(byte[] initialisationVector, byte[] encryptedBytes) {
this.initialisationVector = Arrays.copyOf(initialisationVector, initialisationVector.length);
this.encryptedBytes = Arrays.copyOf(encryptedBytes, encryptedBytes.length);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EncryptedData other = (EncryptedData) o;
return Arrays.equals(encryptedBytes, other.encryptedBytes) && Arrays.equals(initialisationVector, other.initialisationVector);
}
@Override
public int hashCode() {
return Objects.hash(Arrays.hashCode(encryptedBytes), Arrays.hashCode(initialisationVector));
}
@Override
public String toString() {
return "EncryptedData [initialisationVector=" + Arrays.toString(initialisationVector)
+ ", encryptedPrivateKey=" + Arrays.toString(encryptedBytes) + "]";
}
}
| 2,131
| 36.403509
| 134
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/KeyCrypter.java
|
/*
* Copyright 2013 Jim Burton.
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* 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.
*/
package org.bitcoinj.crypto;
import org.bitcoinj.wallet.Protos.Wallet.EncryptionType;
/**
* <p>A KeyCrypter can be used to encrypt and decrypt a message. The sequence of events to encrypt and then decrypt
* a message are as follows:</p>
*
* <p>(1) Ask the user for a password. deriveKey() is then called to create an KeyParameter. This contains the AES
* key that will be used for encryption.</p>
* <p>(2) Encrypt the message using encrypt(), providing the message bytes and the KeyParameter from (1). This returns
* an EncryptedData which contains the encryptedPrivateKey bytes and an initialisation vector.</p>
* <p>(3) To decrypt an EncryptedData, repeat step (1) to get a KeyParameter, then call decrypt().</p>
*
* <p>There can be different algorithms used for encryption/ decryption so the getUnderstoodEncryptionType is used
* to determine whether any given KeyCrypter can understand the type of encrypted data you have.</p>
*/
public interface KeyCrypter {
/**
* Return the EncryptionType enum value which denotes the type of encryption/ decryption that this KeyCrypter
* can understand.
*/
EncryptionType getUnderstoodEncryptionType();
/**
* Create an AESKey (which typically contains an AES key)
* @param password
* @return AESKey which typically contains the AES key to use for encrypting and decrypting
* @throws KeyCrypterException
*/
AesKey deriveKey(CharSequence password) throws KeyCrypterException;
/**
* Decrypt the provided encrypted bytes, converting them into unencrypted bytes.
*
* @throws KeyCrypterException if decryption was unsuccessful.
*/
byte[] decrypt(EncryptedData encryptedBytesToDecode, AesKey aesKey) throws KeyCrypterException;
/**
* Encrypt the supplied bytes, converting them into ciphertext.
*
* @return encryptedPrivateKey An encryptedPrivateKey containing the encrypted bytes and an initialisation vector.
* @throws KeyCrypterException if encryption was unsuccessful
*/
EncryptedData encrypt(byte[] plainBytes, AesKey aesKey) throws KeyCrypterException;
}
| 2,713
| 40.753846
| 118
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/SignatureDecodeException.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.crypto;
public class SignatureDecodeException extends Exception {
public SignatureDecodeException() {
super();
}
public SignatureDecodeException(String message) {
super(message);
}
public SignatureDecodeException(Throwable cause) {
super(cause);
}
public SignatureDecodeException(String message, Throwable cause) {
super(message, cause);
}
}
| 1,044
| 28.027778
| 75
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/HDDerivationException.java
|
/*
* Copyright 2013 Matija Mazi.
*
* 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.
*/
package org.bitcoinj.crypto;
public class HDDerivationException extends RuntimeException {
public HDDerivationException(String message) {
super(message);
}
}
| 771
| 31.166667
| 75
|
java
|
bitcoinj
|
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/AesKey.java
|
/*
* Copyright by the original author or authors.
*
* 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.
*/
package org.bitcoinj.crypto;
import org.bitcoinj.base.internal.ByteArray;
import org.bouncycastle.crypto.params.KeyParameter;
/**
* Wrapper for a {@code byte[]} containing an AES Key. This is a replacement for Bouncy Castle's {@link KeyParameter} which
* was used for this purpose in previous versions of <b>bitcoinj</b>. Unfortunately, this created a Gradle _API_ dependency
* on Bouncy Castle when that wasn't strictly necessary.
* <p>
* We have made this change without deprecation because it affected many method signatures and because updating is a trivial change.
* If for some reason you have code that uses the Bouncy Castle {@link KeyParameter} type and need to convert
* to or from {@code AesKey}, you can temporarily use {@link #ofKeyParameter(KeyParameter)} or {@link #toKeyParameter()}
*/
public class AesKey extends ByteArray {
/**
* Wrapper for a {@code byte[]} containing an AES Key
* @param keyBytes implementation-dependent AES Key bytes
*/
public AesKey(byte[] keyBytes) {
super(keyBytes);
}
/**
* Provided to ease migration from {@link KeyParameter}.
* @return The key bytes
* @deprecated Use {@link #bytes()}
*/
@Deprecated
public byte[] getKey() {
return bytes();
}
/**
* Provided to ease migration from {@link KeyParameter}.
* @param keyParameter instance to convert
* @return new, preferred container for AES keys
* @deprecated Use {@code new AesKey(keyParameter.bytes())}
*/
@Deprecated
public static AesKey ofKeyParameter(KeyParameter keyParameter) {
return new AesKey(keyParameter.getKey());
}
/**
* Provided to ease migration from {@link KeyParameter}.
* @return if for some reason you still need (temporarily, we hope) a {@link KeyParameter}
* @deprecated Use {@code new KeyParameter(key.bytes)}
*/
@Deprecated
public KeyParameter toKeyParameter() {
return new KeyParameter(this.bytes());
}
}
| 2,629
| 36.042254
| 133
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.