id int32 0 165k | repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23,400 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelServerState.java | PaymentChannelServerState.incrementPayment | public synchronized boolean incrementPayment(Coin refundSize, byte[] signatureBytes)
throws SignatureDecodeException, VerificationException, ValueOutOfRangeException,
InsufficientMoneyException {
stateMachine.checkState(State.READY);
checkNotNull(refundSize);
checkNotNull(signatureBytes);
TransactionSignature signature = TransactionSignature.decodeFromBitcoin(signatureBytes, true, false);
// We allow snapping to zero for the payment amount because it's treated specially later, but not less than
// the dust level because that would prevent the transaction from being relayed/mined.
final boolean fullyUsedUp = refundSize.equals(Coin.ZERO);
Coin newValueToMe = getTotalValue().subtract(refundSize);
if (newValueToMe.signum() < 0)
throw new ValueOutOfRangeException("Attempt to refund more than the contract allows.");
if (newValueToMe.compareTo(bestValueToMe) < 0)
throw new ValueOutOfRangeException("Attempt to roll back payment on the channel.");
SendRequest req = makeUnsignedChannelContract(newValueToMe);
if (!fullyUsedUp && refundSize.isLessThan(req.tx.getOutput(0).getMinNonDustValue()))
throw new ValueOutOfRangeException("Attempt to refund negative value or value too small to be accepted by the network");
// Get the wallet's copy of the contract (ie with confidence information), if this is null, the wallet
// was not connected to the peergroup when the contract was broadcast (which may cause issues down the road, and
// disables our double-spend check next)
Transaction walletContract = wallet.getTransaction(contract.getTxId());
checkNotNull(walletContract, "Wallet did not contain multisig contract {} after state was marked READY", contract.getTxId());
// Note that we check for DEAD state here, but this test is essentially useless in production because we will
// miss most double-spends due to bloom filtering right now anyway. This will eventually fixed by network-wide
// double-spend notifications, so we just wait instead of attempting to add all dependant outpoints to our bloom
// filters (and probably missing lots of edge-cases).
if (walletContract.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.DEAD) {
close();
throw new VerificationException("Multisig contract was double-spent");
}
Transaction.SigHash mode;
// If the client doesn't want anything back, they shouldn't sign any outputs at all.
if (fullyUsedUp)
mode = Transaction.SigHash.NONE;
else
mode = Transaction.SigHash.SINGLE;
if (signature.sigHashMode() != mode || !signature.anyoneCanPay())
throw new VerificationException("New payment signature was not signed with the right SIGHASH flags.");
// Now check the signature is correct.
// Note that the client must sign with SIGHASH_{SINGLE/NONE} | SIGHASH_ANYONECANPAY to allow us to add additional
// inputs (in case we need to add significant fee, or something...) and any outputs we want to pay to.
Sha256Hash sighash = req.tx.hashForSignature(0, getSignedScript(), mode, true);
if (!getClientKey().verify(sighash, signature))
throw new VerificationException("Signature does not verify on tx\n" + req.tx);
bestValueToMe = newValueToMe;
bestValueSignature = signatureBytes;
updateChannelInWallet();
return !fullyUsedUp;
} | java | public synchronized boolean incrementPayment(Coin refundSize, byte[] signatureBytes)
throws SignatureDecodeException, VerificationException, ValueOutOfRangeException,
InsufficientMoneyException {
stateMachine.checkState(State.READY);
checkNotNull(refundSize);
checkNotNull(signatureBytes);
TransactionSignature signature = TransactionSignature.decodeFromBitcoin(signatureBytes, true, false);
// We allow snapping to zero for the payment amount because it's treated specially later, but not less than
// the dust level because that would prevent the transaction from being relayed/mined.
final boolean fullyUsedUp = refundSize.equals(Coin.ZERO);
Coin newValueToMe = getTotalValue().subtract(refundSize);
if (newValueToMe.signum() < 0)
throw new ValueOutOfRangeException("Attempt to refund more than the contract allows.");
if (newValueToMe.compareTo(bestValueToMe) < 0)
throw new ValueOutOfRangeException("Attempt to roll back payment on the channel.");
SendRequest req = makeUnsignedChannelContract(newValueToMe);
if (!fullyUsedUp && refundSize.isLessThan(req.tx.getOutput(0).getMinNonDustValue()))
throw new ValueOutOfRangeException("Attempt to refund negative value or value too small to be accepted by the network");
// Get the wallet's copy of the contract (ie with confidence information), if this is null, the wallet
// was not connected to the peergroup when the contract was broadcast (which may cause issues down the road, and
// disables our double-spend check next)
Transaction walletContract = wallet.getTransaction(contract.getTxId());
checkNotNull(walletContract, "Wallet did not contain multisig contract {} after state was marked READY", contract.getTxId());
// Note that we check for DEAD state here, but this test is essentially useless in production because we will
// miss most double-spends due to bloom filtering right now anyway. This will eventually fixed by network-wide
// double-spend notifications, so we just wait instead of attempting to add all dependant outpoints to our bloom
// filters (and probably missing lots of edge-cases).
if (walletContract.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.DEAD) {
close();
throw new VerificationException("Multisig contract was double-spent");
}
Transaction.SigHash mode;
// If the client doesn't want anything back, they shouldn't sign any outputs at all.
if (fullyUsedUp)
mode = Transaction.SigHash.NONE;
else
mode = Transaction.SigHash.SINGLE;
if (signature.sigHashMode() != mode || !signature.anyoneCanPay())
throw new VerificationException("New payment signature was not signed with the right SIGHASH flags.");
// Now check the signature is correct.
// Note that the client must sign with SIGHASH_{SINGLE/NONE} | SIGHASH_ANYONECANPAY to allow us to add additional
// inputs (in case we need to add significant fee, or something...) and any outputs we want to pay to.
Sha256Hash sighash = req.tx.hashForSignature(0, getSignedScript(), mode, true);
if (!getClientKey().verify(sighash, signature))
throw new VerificationException("Signature does not verify on tx\n" + req.tx);
bestValueToMe = newValueToMe;
bestValueSignature = signatureBytes;
updateChannelInWallet();
return !fullyUsedUp;
} | [
"public",
"synchronized",
"boolean",
"incrementPayment",
"(",
"Coin",
"refundSize",
",",
"byte",
"[",
"]",
"signatureBytes",
")",
"throws",
"SignatureDecodeException",
",",
"VerificationException",
",",
"ValueOutOfRangeException",
",",
"InsufficientMoneyException",
"{",
"stateMachine",
".",
"checkState",
"(",
"State",
".",
"READY",
")",
";",
"checkNotNull",
"(",
"refundSize",
")",
";",
"checkNotNull",
"(",
"signatureBytes",
")",
";",
"TransactionSignature",
"signature",
"=",
"TransactionSignature",
".",
"decodeFromBitcoin",
"(",
"signatureBytes",
",",
"true",
",",
"false",
")",
";",
"// We allow snapping to zero for the payment amount because it's treated specially later, but not less than",
"// the dust level because that would prevent the transaction from being relayed/mined.",
"final",
"boolean",
"fullyUsedUp",
"=",
"refundSize",
".",
"equals",
"(",
"Coin",
".",
"ZERO",
")",
";",
"Coin",
"newValueToMe",
"=",
"getTotalValue",
"(",
")",
".",
"subtract",
"(",
"refundSize",
")",
";",
"if",
"(",
"newValueToMe",
".",
"signum",
"(",
")",
"<",
"0",
")",
"throw",
"new",
"ValueOutOfRangeException",
"(",
"\"Attempt to refund more than the contract allows.\"",
")",
";",
"if",
"(",
"newValueToMe",
".",
"compareTo",
"(",
"bestValueToMe",
")",
"<",
"0",
")",
"throw",
"new",
"ValueOutOfRangeException",
"(",
"\"Attempt to roll back payment on the channel.\"",
")",
";",
"SendRequest",
"req",
"=",
"makeUnsignedChannelContract",
"(",
"newValueToMe",
")",
";",
"if",
"(",
"!",
"fullyUsedUp",
"&&",
"refundSize",
".",
"isLessThan",
"(",
"req",
".",
"tx",
".",
"getOutput",
"(",
"0",
")",
".",
"getMinNonDustValue",
"(",
")",
")",
")",
"throw",
"new",
"ValueOutOfRangeException",
"(",
"\"Attempt to refund negative value or value too small to be accepted by the network\"",
")",
";",
"// Get the wallet's copy of the contract (ie with confidence information), if this is null, the wallet",
"// was not connected to the peergroup when the contract was broadcast (which may cause issues down the road, and",
"// disables our double-spend check next)",
"Transaction",
"walletContract",
"=",
"wallet",
".",
"getTransaction",
"(",
"contract",
".",
"getTxId",
"(",
")",
")",
";",
"checkNotNull",
"(",
"walletContract",
",",
"\"Wallet did not contain multisig contract {} after state was marked READY\"",
",",
"contract",
".",
"getTxId",
"(",
")",
")",
";",
"// Note that we check for DEAD state here, but this test is essentially useless in production because we will",
"// miss most double-spends due to bloom filtering right now anyway. This will eventually fixed by network-wide",
"// double-spend notifications, so we just wait instead of attempting to add all dependant outpoints to our bloom",
"// filters (and probably missing lots of edge-cases).",
"if",
"(",
"walletContract",
".",
"getConfidence",
"(",
")",
".",
"getConfidenceType",
"(",
")",
"==",
"TransactionConfidence",
".",
"ConfidenceType",
".",
"DEAD",
")",
"{",
"close",
"(",
")",
";",
"throw",
"new",
"VerificationException",
"(",
"\"Multisig contract was double-spent\"",
")",
";",
"}",
"Transaction",
".",
"SigHash",
"mode",
";",
"// If the client doesn't want anything back, they shouldn't sign any outputs at all.",
"if",
"(",
"fullyUsedUp",
")",
"mode",
"=",
"Transaction",
".",
"SigHash",
".",
"NONE",
";",
"else",
"mode",
"=",
"Transaction",
".",
"SigHash",
".",
"SINGLE",
";",
"if",
"(",
"signature",
".",
"sigHashMode",
"(",
")",
"!=",
"mode",
"||",
"!",
"signature",
".",
"anyoneCanPay",
"(",
")",
")",
"throw",
"new",
"VerificationException",
"(",
"\"New payment signature was not signed with the right SIGHASH flags.\"",
")",
";",
"// Now check the signature is correct.",
"// Note that the client must sign with SIGHASH_{SINGLE/NONE} | SIGHASH_ANYONECANPAY to allow us to add additional",
"// inputs (in case we need to add significant fee, or something...) and any outputs we want to pay to.",
"Sha256Hash",
"sighash",
"=",
"req",
".",
"tx",
".",
"hashForSignature",
"(",
"0",
",",
"getSignedScript",
"(",
")",
",",
"mode",
",",
"true",
")",
";",
"if",
"(",
"!",
"getClientKey",
"(",
")",
".",
"verify",
"(",
"sighash",
",",
"signature",
")",
")",
"throw",
"new",
"VerificationException",
"(",
"\"Signature does not verify on tx\\n\"",
"+",
"req",
".",
"tx",
")",
";",
"bestValueToMe",
"=",
"newValueToMe",
";",
"bestValueSignature",
"=",
"signatureBytes",
";",
"updateChannelInWallet",
"(",
")",
";",
"return",
"!",
"fullyUsedUp",
";",
"}"
] | Called when the client provides us with a new signature and wishes to increment total payment by size.
Verifies the provided signature and only updates values if everything checks out.
If the new refundSize is not the lowest we have seen, it is simply ignored.
@param refundSize How many satoshis of the original contract are refunded to the client (the rest are ours)
@param signatureBytes The new signature spending the multi-sig contract to a new payment transaction
@throws VerificationException If the signature does not verify or size is out of range (incl being rejected by the network as dust).
@return true if there is more value left on the channel, false if it is now fully used up. | [
"Called",
"when",
"the",
"client",
"provides",
"us",
"with",
"a",
"new",
"signature",
"and",
"wishes",
"to",
"increment",
"total",
"payment",
"by",
"size",
".",
"Verifies",
"the",
"provided",
"signature",
"and",
"only",
"updates",
"values",
"if",
"everything",
"checks",
"out",
".",
"If",
"the",
"new",
"refundSize",
"is",
"not",
"the",
"lowest",
"we",
"have",
"seen",
"it",
"is",
"simply",
"ignored",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelServerState.java#L240-L297 |
23,401 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcAutoFormat.java | BtcAutoFormat.scale | @Override
protected int scale(BigInteger satoshis, int fractionPlaces) {
/* The algorithm is as follows. TODO: is there a way to optimize step 4?
1. Can we use coin denomination w/ no rounding? If yes, do it.
2. Else, can we use millicoin denomination w/ no rounding? If yes, do it.
3. Else, can we use micro denomination w/ no rounding? If yes, do it.
4. Otherwise we must round:
(a) round to nearest coin + decimals
(b) round to nearest millicoin + decimals
(c) round to nearest microcoin + decimals
Subtract each of (a), (b) and (c) from the true value, and choose the
denomination that gives smallest absolute difference. It case of tie, use the
smaller denomination.
*/
int places;
int coinOffset = Math.max(SMALLEST_UNIT_EXPONENT - fractionPlaces, 0);
BigDecimal inCoins = new BigDecimal(satoshis).movePointLeft(coinOffset);
if (inCoins.remainder(ONE).compareTo(ZERO) == 0) {
places = COIN_SCALE;
} else {
BigDecimal inMillis = inCoins.movePointRight(MILLICOIN_SCALE);
if (inMillis.remainder(ONE).compareTo(ZERO) == 0) {
places = MILLICOIN_SCALE;
} else {
BigDecimal inMicros = inCoins.movePointRight(MICROCOIN_SCALE);
if (inMicros.remainder(ONE).compareTo(ZERO) == 0) {
places = MICROCOIN_SCALE;
} else {
// no way to avoid rounding: so what denomination gives smallest error?
BigDecimal a = inCoins.subtract(inCoins.setScale(0, HALF_UP)).
movePointRight(coinOffset).abs();
BigDecimal b = inMillis.subtract(inMillis.setScale(0, HALF_UP)).
movePointRight(coinOffset - MILLICOIN_SCALE).abs();
BigDecimal c = inMicros.subtract(inMicros.setScale(0, HALF_UP)).
movePointRight(coinOffset - MICROCOIN_SCALE).abs();
if (a.compareTo(b) < 0)
if (a.compareTo(c) < 0) places = COIN_SCALE;
else places = MICROCOIN_SCALE;
else if (b.compareTo(c) < 0) places = MILLICOIN_SCALE;
else places = MICROCOIN_SCALE;
}
}
}
prefixUnitsIndicator(numberFormat, places);
return places;
} | java | @Override
protected int scale(BigInteger satoshis, int fractionPlaces) {
/* The algorithm is as follows. TODO: is there a way to optimize step 4?
1. Can we use coin denomination w/ no rounding? If yes, do it.
2. Else, can we use millicoin denomination w/ no rounding? If yes, do it.
3. Else, can we use micro denomination w/ no rounding? If yes, do it.
4. Otherwise we must round:
(a) round to nearest coin + decimals
(b) round to nearest millicoin + decimals
(c) round to nearest microcoin + decimals
Subtract each of (a), (b) and (c) from the true value, and choose the
denomination that gives smallest absolute difference. It case of tie, use the
smaller denomination.
*/
int places;
int coinOffset = Math.max(SMALLEST_UNIT_EXPONENT - fractionPlaces, 0);
BigDecimal inCoins = new BigDecimal(satoshis).movePointLeft(coinOffset);
if (inCoins.remainder(ONE).compareTo(ZERO) == 0) {
places = COIN_SCALE;
} else {
BigDecimal inMillis = inCoins.movePointRight(MILLICOIN_SCALE);
if (inMillis.remainder(ONE).compareTo(ZERO) == 0) {
places = MILLICOIN_SCALE;
} else {
BigDecimal inMicros = inCoins.movePointRight(MICROCOIN_SCALE);
if (inMicros.remainder(ONE).compareTo(ZERO) == 0) {
places = MICROCOIN_SCALE;
} else {
// no way to avoid rounding: so what denomination gives smallest error?
BigDecimal a = inCoins.subtract(inCoins.setScale(0, HALF_UP)).
movePointRight(coinOffset).abs();
BigDecimal b = inMillis.subtract(inMillis.setScale(0, HALF_UP)).
movePointRight(coinOffset - MILLICOIN_SCALE).abs();
BigDecimal c = inMicros.subtract(inMicros.setScale(0, HALF_UP)).
movePointRight(coinOffset - MICROCOIN_SCALE).abs();
if (a.compareTo(b) < 0)
if (a.compareTo(c) < 0) places = COIN_SCALE;
else places = MICROCOIN_SCALE;
else if (b.compareTo(c) < 0) places = MILLICOIN_SCALE;
else places = MICROCOIN_SCALE;
}
}
}
prefixUnitsIndicator(numberFormat, places);
return places;
} | [
"@",
"Override",
"protected",
"int",
"scale",
"(",
"BigInteger",
"satoshis",
",",
"int",
"fractionPlaces",
")",
"{",
"/* The algorithm is as follows. TODO: is there a way to optimize step 4?\n 1. Can we use coin denomination w/ no rounding? If yes, do it.\n 2. Else, can we use millicoin denomination w/ no rounding? If yes, do it.\n 3. Else, can we use micro denomination w/ no rounding? If yes, do it.\n 4. Otherwise we must round:\n (a) round to nearest coin + decimals\n (b) round to nearest millicoin + decimals\n (c) round to nearest microcoin + decimals\n Subtract each of (a), (b) and (c) from the true value, and choose the\n denomination that gives smallest absolute difference. It case of tie, use the\n smaller denomination.\n */",
"int",
"places",
";",
"int",
"coinOffset",
"=",
"Math",
".",
"max",
"(",
"SMALLEST_UNIT_EXPONENT",
"-",
"fractionPlaces",
",",
"0",
")",
";",
"BigDecimal",
"inCoins",
"=",
"new",
"BigDecimal",
"(",
"satoshis",
")",
".",
"movePointLeft",
"(",
"coinOffset",
")",
";",
"if",
"(",
"inCoins",
".",
"remainder",
"(",
"ONE",
")",
".",
"compareTo",
"(",
"ZERO",
")",
"==",
"0",
")",
"{",
"places",
"=",
"COIN_SCALE",
";",
"}",
"else",
"{",
"BigDecimal",
"inMillis",
"=",
"inCoins",
".",
"movePointRight",
"(",
"MILLICOIN_SCALE",
")",
";",
"if",
"(",
"inMillis",
".",
"remainder",
"(",
"ONE",
")",
".",
"compareTo",
"(",
"ZERO",
")",
"==",
"0",
")",
"{",
"places",
"=",
"MILLICOIN_SCALE",
";",
"}",
"else",
"{",
"BigDecimal",
"inMicros",
"=",
"inCoins",
".",
"movePointRight",
"(",
"MICROCOIN_SCALE",
")",
";",
"if",
"(",
"inMicros",
".",
"remainder",
"(",
"ONE",
")",
".",
"compareTo",
"(",
"ZERO",
")",
"==",
"0",
")",
"{",
"places",
"=",
"MICROCOIN_SCALE",
";",
"}",
"else",
"{",
"// no way to avoid rounding: so what denomination gives smallest error?",
"BigDecimal",
"a",
"=",
"inCoins",
".",
"subtract",
"(",
"inCoins",
".",
"setScale",
"(",
"0",
",",
"HALF_UP",
")",
")",
".",
"movePointRight",
"(",
"coinOffset",
")",
".",
"abs",
"(",
")",
";",
"BigDecimal",
"b",
"=",
"inMillis",
".",
"subtract",
"(",
"inMillis",
".",
"setScale",
"(",
"0",
",",
"HALF_UP",
")",
")",
".",
"movePointRight",
"(",
"coinOffset",
"-",
"MILLICOIN_SCALE",
")",
".",
"abs",
"(",
")",
";",
"BigDecimal",
"c",
"=",
"inMicros",
".",
"subtract",
"(",
"inMicros",
".",
"setScale",
"(",
"0",
",",
"HALF_UP",
")",
")",
".",
"movePointRight",
"(",
"coinOffset",
"-",
"MICROCOIN_SCALE",
")",
".",
"abs",
"(",
")",
";",
"if",
"(",
"a",
".",
"compareTo",
"(",
"b",
")",
"<",
"0",
")",
"if",
"(",
"a",
".",
"compareTo",
"(",
"c",
")",
"<",
"0",
")",
"places",
"=",
"COIN_SCALE",
";",
"else",
"places",
"=",
"MICROCOIN_SCALE",
";",
"else",
"if",
"(",
"b",
".",
"compareTo",
"(",
"c",
")",
"<",
"0",
")",
"places",
"=",
"MILLICOIN_SCALE",
";",
"else",
"places",
"=",
"MICROCOIN_SCALE",
";",
"}",
"}",
"}",
"prefixUnitsIndicator",
"(",
"numberFormat",
",",
"places",
")",
";",
"return",
"places",
";",
"}"
] | Calculate the appropriate denomination for the given Bitcoin monetary value. This
method takes a BigInteger representing a quantity of satoshis, and returns the
number of places that value's decimal point is to be moved when formatting said value
in order that the resulting number represents the correct quantity of denominational
units.
<p>As a side-effect, this sets the units indicators of the underlying NumberFormat object.
Only invoke this from a synchronized method, and be sure to put the DecimalFormatSymbols
back to its proper state, otherwise immutability, equals() and hashCode() fail. | [
"Calculate",
"the",
"appropriate",
"denomination",
"for",
"the",
"given",
"Bitcoin",
"monetary",
"value",
".",
"This",
"method",
"takes",
"a",
"BigInteger",
"representing",
"a",
"quantity",
"of",
"satoshis",
"and",
"returns",
"the",
"number",
"of",
"places",
"that",
"value",
"s",
"decimal",
"point",
"is",
"to",
"be",
"moved",
"when",
"formatting",
"said",
"value",
"in",
"order",
"that",
"the",
"resulting",
"number",
"represents",
"the",
"correct",
"quantity",
"of",
"denominational",
"units",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcAutoFormat.java#L127-L172 |
23,402 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/FilteredBlock.java | FilteredBlock.getTransactionHashes | public List<Sha256Hash> getTransactionHashes() throws VerificationException {
if (cachedTransactionHashes != null)
return Collections.unmodifiableList(cachedTransactionHashes);
List<Sha256Hash> hashesMatched = new LinkedList<>();
if (header.getMerkleRoot().equals(merkleTree.getTxnHashAndMerkleRoot(hashesMatched))) {
cachedTransactionHashes = hashesMatched;
return Collections.unmodifiableList(cachedTransactionHashes);
} else
throw new VerificationException("Merkle root of block header does not match merkle root of partial merkle tree.");
} | java | public List<Sha256Hash> getTransactionHashes() throws VerificationException {
if (cachedTransactionHashes != null)
return Collections.unmodifiableList(cachedTransactionHashes);
List<Sha256Hash> hashesMatched = new LinkedList<>();
if (header.getMerkleRoot().equals(merkleTree.getTxnHashAndMerkleRoot(hashesMatched))) {
cachedTransactionHashes = hashesMatched;
return Collections.unmodifiableList(cachedTransactionHashes);
} else
throw new VerificationException("Merkle root of block header does not match merkle root of partial merkle tree.");
} | [
"public",
"List",
"<",
"Sha256Hash",
">",
"getTransactionHashes",
"(",
")",
"throws",
"VerificationException",
"{",
"if",
"(",
"cachedTransactionHashes",
"!=",
"null",
")",
"return",
"Collections",
".",
"unmodifiableList",
"(",
"cachedTransactionHashes",
")",
";",
"List",
"<",
"Sha256Hash",
">",
"hashesMatched",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"if",
"(",
"header",
".",
"getMerkleRoot",
"(",
")",
".",
"equals",
"(",
"merkleTree",
".",
"getTxnHashAndMerkleRoot",
"(",
"hashesMatched",
")",
")",
")",
"{",
"cachedTransactionHashes",
"=",
"hashesMatched",
";",
"return",
"Collections",
".",
"unmodifiableList",
"(",
"cachedTransactionHashes",
")",
";",
"}",
"else",
"throw",
"new",
"VerificationException",
"(",
"\"Merkle root of block header does not match merkle root of partial merkle tree.\"",
")",
";",
"}"
] | Gets a list of leaf hashes which are contained in the partial merkle tree in this filtered block
@throws ProtocolException If the partial merkle block is invalid or the merkle root of the partial merkle block doesn't match the block header | [
"Gets",
"a",
"list",
"of",
"leaf",
"hashes",
"which",
"are",
"contained",
"in",
"the",
"partial",
"merkle",
"tree",
"in",
"this",
"filtered",
"block"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/FilteredBlock.java#L75-L84 |
23,403 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/FilteredBlock.java | FilteredBlock.provideTransaction | public boolean provideTransaction(Transaction tx) throws VerificationException {
Sha256Hash hash = tx.getTxId();
if (getTransactionHashes().contains(hash)) {
associatedTransactions.put(hash, tx);
return true;
}
return false;
} | java | public boolean provideTransaction(Transaction tx) throws VerificationException {
Sha256Hash hash = tx.getTxId();
if (getTransactionHashes().contains(hash)) {
associatedTransactions.put(hash, tx);
return true;
}
return false;
} | [
"public",
"boolean",
"provideTransaction",
"(",
"Transaction",
"tx",
")",
"throws",
"VerificationException",
"{",
"Sha256Hash",
"hash",
"=",
"tx",
".",
"getTxId",
"(",
")",
";",
"if",
"(",
"getTransactionHashes",
"(",
")",
".",
"contains",
"(",
"hash",
")",
")",
"{",
"associatedTransactions",
".",
"put",
"(",
"hash",
",",
"tx",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Provide this FilteredBlock with a transaction which is in its Merkle tree.
@return false if the tx is not relevant to this FilteredBlock | [
"Provide",
"this",
"FilteredBlock",
"with",
"a",
"transaction",
"which",
"is",
"in",
"its",
"Merkle",
"tree",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/FilteredBlock.java#L103-L110 |
23,404 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java | PaymentProtocol.parsePaymentRequest | public static PaymentSession parsePaymentRequest(Protos.PaymentRequest paymentRequest)
throws PaymentProtocolException {
return new PaymentSession(paymentRequest, false, null);
} | java | public static PaymentSession parsePaymentRequest(Protos.PaymentRequest paymentRequest)
throws PaymentProtocolException {
return new PaymentSession(paymentRequest, false, null);
} | [
"public",
"static",
"PaymentSession",
"parsePaymentRequest",
"(",
"Protos",
".",
"PaymentRequest",
"paymentRequest",
")",
"throws",
"PaymentProtocolException",
"{",
"return",
"new",
"PaymentSession",
"(",
"paymentRequest",
",",
"false",
",",
"null",
")",
";",
"}"
] | Parse a payment request.
@param paymentRequest payment request to parse
@return instance of {@link PaymentSession}, used as a value object
@throws PaymentProtocolException | [
"Parse",
"a",
"payment",
"request",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java#L113-L116 |
23,405 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java | PaymentProtocol.signPaymentRequest | public static void signPaymentRequest(Protos.PaymentRequest.Builder paymentRequest,
X509Certificate[] certificateChain, PrivateKey privateKey) {
try {
final Protos.X509Certificates.Builder certificates = Protos.X509Certificates.newBuilder();
for (final Certificate certificate : certificateChain)
certificates.addCertificate(ByteString.copyFrom(certificate.getEncoded()));
paymentRequest.setPkiType("x509+sha256");
paymentRequest.setPkiData(certificates.build().toByteString());
paymentRequest.setSignature(ByteString.EMPTY);
final Protos.PaymentRequest paymentRequestToSign = paymentRequest.build();
final String algorithm;
if ("RSA".equalsIgnoreCase(privateKey.getAlgorithm()))
algorithm = "SHA256withRSA";
else
throw new IllegalStateException(privateKey.getAlgorithm());
final Signature signature = Signature.getInstance(algorithm);
signature.initSign(privateKey);
signature.update(paymentRequestToSign.toByteArray());
paymentRequest.setSignature(ByteString.copyFrom(signature.sign()));
} catch (final GeneralSecurityException x) {
// Should never happen so don't make users have to think about it.
throw new RuntimeException(x);
}
} | java | public static void signPaymentRequest(Protos.PaymentRequest.Builder paymentRequest,
X509Certificate[] certificateChain, PrivateKey privateKey) {
try {
final Protos.X509Certificates.Builder certificates = Protos.X509Certificates.newBuilder();
for (final Certificate certificate : certificateChain)
certificates.addCertificate(ByteString.copyFrom(certificate.getEncoded()));
paymentRequest.setPkiType("x509+sha256");
paymentRequest.setPkiData(certificates.build().toByteString());
paymentRequest.setSignature(ByteString.EMPTY);
final Protos.PaymentRequest paymentRequestToSign = paymentRequest.build();
final String algorithm;
if ("RSA".equalsIgnoreCase(privateKey.getAlgorithm()))
algorithm = "SHA256withRSA";
else
throw new IllegalStateException(privateKey.getAlgorithm());
final Signature signature = Signature.getInstance(algorithm);
signature.initSign(privateKey);
signature.update(paymentRequestToSign.toByteArray());
paymentRequest.setSignature(ByteString.copyFrom(signature.sign()));
} catch (final GeneralSecurityException x) {
// Should never happen so don't make users have to think about it.
throw new RuntimeException(x);
}
} | [
"public",
"static",
"void",
"signPaymentRequest",
"(",
"Protos",
".",
"PaymentRequest",
".",
"Builder",
"paymentRequest",
",",
"X509Certificate",
"[",
"]",
"certificateChain",
",",
"PrivateKey",
"privateKey",
")",
"{",
"try",
"{",
"final",
"Protos",
".",
"X509Certificates",
".",
"Builder",
"certificates",
"=",
"Protos",
".",
"X509Certificates",
".",
"newBuilder",
"(",
")",
";",
"for",
"(",
"final",
"Certificate",
"certificate",
":",
"certificateChain",
")",
"certificates",
".",
"addCertificate",
"(",
"ByteString",
".",
"copyFrom",
"(",
"certificate",
".",
"getEncoded",
"(",
")",
")",
")",
";",
"paymentRequest",
".",
"setPkiType",
"(",
"\"x509+sha256\"",
")",
";",
"paymentRequest",
".",
"setPkiData",
"(",
"certificates",
".",
"build",
"(",
")",
".",
"toByteString",
"(",
")",
")",
";",
"paymentRequest",
".",
"setSignature",
"(",
"ByteString",
".",
"EMPTY",
")",
";",
"final",
"Protos",
".",
"PaymentRequest",
"paymentRequestToSign",
"=",
"paymentRequest",
".",
"build",
"(",
")",
";",
"final",
"String",
"algorithm",
";",
"if",
"(",
"\"RSA\"",
".",
"equalsIgnoreCase",
"(",
"privateKey",
".",
"getAlgorithm",
"(",
")",
")",
")",
"algorithm",
"=",
"\"SHA256withRSA\"",
";",
"else",
"throw",
"new",
"IllegalStateException",
"(",
"privateKey",
".",
"getAlgorithm",
"(",
")",
")",
";",
"final",
"Signature",
"signature",
"=",
"Signature",
".",
"getInstance",
"(",
"algorithm",
")",
";",
"signature",
".",
"initSign",
"(",
"privateKey",
")",
";",
"signature",
".",
"update",
"(",
"paymentRequestToSign",
".",
"toByteArray",
"(",
")",
")",
";",
"paymentRequest",
".",
"setSignature",
"(",
"ByteString",
".",
"copyFrom",
"(",
"signature",
".",
"sign",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"final",
"GeneralSecurityException",
"x",
")",
"{",
"// Should never happen so don't make users have to think about it.",
"throw",
"new",
"RuntimeException",
"(",
"x",
")",
";",
"}",
"}"
] | Sign the provided payment request.
@param paymentRequest Payment request to sign, in its builder form.
@param certificateChain Certificate chain to send with the payment request, ordered from client certificate to root
certificate. The root certificate itself may be omitted.
@param privateKey The key to sign with. Must match the public key from the first certificate of the certificate chain. | [
"Sign",
"the",
"provided",
"payment",
"request",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java#L126-L153 |
23,406 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java | PaymentProtocol.parseTransactionsFromPaymentMessage | public static List<Transaction> parseTransactionsFromPaymentMessage(NetworkParameters params,
Protos.Payment paymentMessage) {
final List<Transaction> transactions = new ArrayList<>(paymentMessage.getTransactionsCount());
for (final ByteString transaction : paymentMessage.getTransactionsList())
transactions.add(params.getDefaultSerializer().makeTransaction(transaction.toByteArray()));
return transactions;
} | java | public static List<Transaction> parseTransactionsFromPaymentMessage(NetworkParameters params,
Protos.Payment paymentMessage) {
final List<Transaction> transactions = new ArrayList<>(paymentMessage.getTransactionsCount());
for (final ByteString transaction : paymentMessage.getTransactionsList())
transactions.add(params.getDefaultSerializer().makeTransaction(transaction.toByteArray()));
return transactions;
} | [
"public",
"static",
"List",
"<",
"Transaction",
">",
"parseTransactionsFromPaymentMessage",
"(",
"NetworkParameters",
"params",
",",
"Protos",
".",
"Payment",
"paymentMessage",
")",
"{",
"final",
"List",
"<",
"Transaction",
">",
"transactions",
"=",
"new",
"ArrayList",
"<>",
"(",
"paymentMessage",
".",
"getTransactionsCount",
"(",
")",
")",
";",
"for",
"(",
"final",
"ByteString",
"transaction",
":",
"paymentMessage",
".",
"getTransactionsList",
"(",
")",
")",
"transactions",
".",
"(",
"params",
".",
"getDefaultSerializer",
"(",
")",
".",
"makeTransaction",
"(",
"transaction",
".",
"toByteArray",
"(",
")",
")",
")",
";",
"return",
"transactions",
";",
"}"
] | Parse transactions from payment message.
@param params network parameters (needed for transaction deserialization)
@param paymentMessage payment message to parse
@return list of transactions | [
"Parse",
"transactions",
"from",
"payment",
"message",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java#L341-L347 |
23,407 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java | PaymentProtocol.parsePaymentAck | public static Ack parsePaymentAck(Protos.PaymentACK paymentAck) {
final String memo = paymentAck.hasMemo() ? paymentAck.getMemo() : null;
return new Ack(memo);
} | java | public static Ack parsePaymentAck(Protos.PaymentACK paymentAck) {
final String memo = paymentAck.hasMemo() ? paymentAck.getMemo() : null;
return new Ack(memo);
} | [
"public",
"static",
"Ack",
"parsePaymentAck",
"(",
"Protos",
".",
"PaymentACK",
"paymentAck",
")",
"{",
"final",
"String",
"memo",
"=",
"paymentAck",
".",
"hasMemo",
"(",
")",
"?",
"paymentAck",
".",
"getMemo",
"(",
")",
":",
"null",
";",
"return",
"new",
"Ack",
"(",
"memo",
")",
";",
"}"
] | Parse payment ack into an object. | [
"Parse",
"payment",
"ack",
"into",
"an",
"object",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/payments/PaymentProtocol.java#L387-L390 |
23,408 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/HDUtils.java | HDUtils.append | public static ImmutableList<ChildNumber> append(List<ChildNumber> path, ChildNumber childNumber) {
return ImmutableList.<ChildNumber>builder().addAll(path).add(childNumber).build();
} | java | public static ImmutableList<ChildNumber> append(List<ChildNumber> path, ChildNumber childNumber) {
return ImmutableList.<ChildNumber>builder().addAll(path).add(childNumber).build();
} | [
"public",
"static",
"ImmutableList",
"<",
"ChildNumber",
">",
"append",
"(",
"List",
"<",
"ChildNumber",
">",
"path",
",",
"ChildNumber",
"childNumber",
")",
"{",
"return",
"ImmutableList",
".",
"<",
"ChildNumber",
">",
"builder",
"(",
")",
".",
"addAll",
"(",
"path",
")",
".",
"add",
"(",
"childNumber",
")",
".",
"build",
"(",
")",
";",
"}"
] | Append a derivation level to an existing path | [
"Append",
"a",
"derivation",
"level",
"to",
"an",
"existing",
"path"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/HDUtils.java#L71-L73 |
23,409 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/HDUtils.java | HDUtils.concat | public static ImmutableList<ChildNumber> concat(List<ChildNumber> path, List<ChildNumber> path2) {
return ImmutableList.<ChildNumber>builder().addAll(path).addAll(path2).build();
} | java | public static ImmutableList<ChildNumber> concat(List<ChildNumber> path, List<ChildNumber> path2) {
return ImmutableList.<ChildNumber>builder().addAll(path).addAll(path2).build();
} | [
"public",
"static",
"ImmutableList",
"<",
"ChildNumber",
">",
"concat",
"(",
"List",
"<",
"ChildNumber",
">",
"path",
",",
"List",
"<",
"ChildNumber",
">",
"path2",
")",
"{",
"return",
"ImmutableList",
".",
"<",
"ChildNumber",
">",
"builder",
"(",
")",
".",
"addAll",
"(",
"path",
")",
".",
"addAll",
"(",
"path2",
")",
".",
"build",
"(",
")",
";",
"}"
] | Concatenate two derivation paths | [
"Concatenate",
"two",
"derivation",
"paths"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/HDUtils.java#L76-L78 |
23,410 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.getTxId | public Sha256Hash getTxId() {
if (cachedTxId == null) {
if (!hasWitnesses() && cachedWTxId != null) {
cachedTxId = cachedWTxId;
} else {
ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length < 32 ? 32 : length + 32);
try {
bitcoinSerializeToStream(stream, false);
} catch (IOException e) {
throw new RuntimeException(e); // cannot happen
}
cachedTxId = Sha256Hash.wrapReversed(Sha256Hash.hashTwice(stream.toByteArray()));
}
}
return cachedTxId;
} | java | public Sha256Hash getTxId() {
if (cachedTxId == null) {
if (!hasWitnesses() && cachedWTxId != null) {
cachedTxId = cachedWTxId;
} else {
ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length < 32 ? 32 : length + 32);
try {
bitcoinSerializeToStream(stream, false);
} catch (IOException e) {
throw new RuntimeException(e); // cannot happen
}
cachedTxId = Sha256Hash.wrapReversed(Sha256Hash.hashTwice(stream.toByteArray()));
}
}
return cachedTxId;
} | [
"public",
"Sha256Hash",
"getTxId",
"(",
")",
"{",
"if",
"(",
"cachedTxId",
"==",
"null",
")",
"{",
"if",
"(",
"!",
"hasWitnesses",
"(",
")",
"&&",
"cachedWTxId",
"!=",
"null",
")",
"{",
"cachedTxId",
"=",
"cachedWTxId",
";",
"}",
"else",
"{",
"ByteArrayOutputStream",
"stream",
"=",
"new",
"UnsafeByteArrayOutputStream",
"(",
"length",
"<",
"32",
"?",
"32",
":",
"length",
"+",
"32",
")",
";",
"try",
"{",
"bitcoinSerializeToStream",
"(",
"stream",
",",
"false",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"// cannot happen",
"}",
"cachedTxId",
"=",
"Sha256Hash",
".",
"wrapReversed",
"(",
"Sha256Hash",
".",
"hashTwice",
"(",
"stream",
".",
"toByteArray",
"(",
")",
")",
")",
";",
"}",
"}",
"return",
"cachedTxId",
";",
"}"
] | Returns the transaction id as you see them in block explorers. It is used as a reference by transaction inputs
via outpoints. | [
"Returns",
"the",
"transaction",
"id",
"as",
"you",
"see",
"them",
"in",
"block",
"explorers",
".",
"It",
"is",
"used",
"as",
"a",
"reference",
"by",
"transaction",
"inputs",
"via",
"outpoints",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L272-L287 |
23,411 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.getWeight | public int getWeight() {
if (!hasWitnesses())
return getMessageSize() * 4;
try (final ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length)) {
bitcoinSerializeToStream(stream, false);
final int baseSize = stream.size();
stream.reset();
bitcoinSerializeToStream(stream, true);
final int totalSize = stream.size();
return baseSize * 3 + totalSize;
} catch (IOException e) {
throw new RuntimeException(e); // cannot happen
}
} | java | public int getWeight() {
if (!hasWitnesses())
return getMessageSize() * 4;
try (final ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream(length)) {
bitcoinSerializeToStream(stream, false);
final int baseSize = stream.size();
stream.reset();
bitcoinSerializeToStream(stream, true);
final int totalSize = stream.size();
return baseSize * 3 + totalSize;
} catch (IOException e) {
throw new RuntimeException(e); // cannot happen
}
} | [
"public",
"int",
"getWeight",
"(",
")",
"{",
"if",
"(",
"!",
"hasWitnesses",
"(",
")",
")",
"return",
"getMessageSize",
"(",
")",
"*",
"4",
";",
"try",
"(",
"final",
"ByteArrayOutputStream",
"stream",
"=",
"new",
"UnsafeByteArrayOutputStream",
"(",
"length",
")",
")",
"{",
"bitcoinSerializeToStream",
"(",
"stream",
",",
"false",
")",
";",
"final",
"int",
"baseSize",
"=",
"stream",
".",
"size",
"(",
")",
";",
"stream",
".",
"reset",
"(",
")",
";",
"bitcoinSerializeToStream",
"(",
"stream",
",",
"true",
")",
";",
"final",
"int",
"totalSize",
"=",
"stream",
".",
"size",
"(",
")",
";",
"return",
"baseSize",
"*",
"3",
"+",
"totalSize",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"// cannot happen",
"}",
"}"
] | Gets the transaction weight as defined in BIP141. | [
"Gets",
"the",
"transaction",
"weight",
"as",
"defined",
"in",
"BIP141",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L311-L324 |
23,412 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.getInputSum | public Coin getInputSum() {
Coin inputTotal = Coin.ZERO;
for (TransactionInput input: inputs) {
Coin inputValue = input.getValue();
if (inputValue != null) {
inputTotal = inputTotal.add(inputValue);
}
}
return inputTotal;
} | java | public Coin getInputSum() {
Coin inputTotal = Coin.ZERO;
for (TransactionInput input: inputs) {
Coin inputValue = input.getValue();
if (inputValue != null) {
inputTotal = inputTotal.add(inputValue);
}
}
return inputTotal;
} | [
"public",
"Coin",
"getInputSum",
"(",
")",
"{",
"Coin",
"inputTotal",
"=",
"Coin",
".",
"ZERO",
";",
"for",
"(",
"TransactionInput",
"input",
":",
"inputs",
")",
"{",
"Coin",
"inputValue",
"=",
"input",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"inputValue",
"!=",
"null",
")",
"{",
"inputTotal",
"=",
"inputTotal",
".",
"add",
"(",
"inputValue",
")",
";",
"}",
"}",
"return",
"inputTotal",
";",
"}"
] | Gets the sum of the inputs, regardless of who owns them. | [
"Gets",
"the",
"sum",
"of",
"the",
"inputs",
"regardless",
"of",
"who",
"owns",
"them",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L336-L347 |
23,413 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.getValueSentToMe | public Coin getValueSentToMe(TransactionBag transactionBag) {
// This is tested in WalletTest.
Coin v = Coin.ZERO;
for (TransactionOutput o : outputs) {
if (!o.isMineOrWatched(transactionBag)) continue;
v = v.add(o.getValue());
}
return v;
} | java | public Coin getValueSentToMe(TransactionBag transactionBag) {
// This is tested in WalletTest.
Coin v = Coin.ZERO;
for (TransactionOutput o : outputs) {
if (!o.isMineOrWatched(transactionBag)) continue;
v = v.add(o.getValue());
}
return v;
} | [
"public",
"Coin",
"getValueSentToMe",
"(",
"TransactionBag",
"transactionBag",
")",
"{",
"// This is tested in WalletTest.",
"Coin",
"v",
"=",
"Coin",
".",
"ZERO",
";",
"for",
"(",
"TransactionOutput",
"o",
":",
"outputs",
")",
"{",
"if",
"(",
"!",
"o",
".",
"isMineOrWatched",
"(",
"transactionBag",
")",
")",
"continue",
";",
"v",
"=",
"v",
".",
"add",
"(",
"o",
".",
"getValue",
"(",
")",
")",
";",
"}",
"return",
"v",
";",
"}"
] | Calculates the sum of the outputs that are sending coins to a key in the wallet. | [
"Calculates",
"the",
"sum",
"of",
"the",
"outputs",
"that",
"are",
"sending",
"coins",
"to",
"a",
"key",
"in",
"the",
"wallet",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L352-L360 |
23,414 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.getValueSentFromMe | public Coin getValueSentFromMe(TransactionBag wallet) throws ScriptException {
// This is tested in WalletTest.
Coin v = Coin.ZERO;
for (TransactionInput input : inputs) {
// This input is taking value from a transaction in our wallet. To discover the value,
// we must find the connected transaction.
TransactionOutput connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.UNSPENT));
if (connected == null)
connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.SPENT));
if (connected == null)
connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.PENDING));
if (connected == null)
continue;
// The connected output may be the change to the sender of a previous input sent to this wallet. In this
// case we ignore it.
if (!connected.isMineOrWatched(wallet))
continue;
v = v.add(connected.getValue());
}
return v;
} | java | public Coin getValueSentFromMe(TransactionBag wallet) throws ScriptException {
// This is tested in WalletTest.
Coin v = Coin.ZERO;
for (TransactionInput input : inputs) {
// This input is taking value from a transaction in our wallet. To discover the value,
// we must find the connected transaction.
TransactionOutput connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.UNSPENT));
if (connected == null)
connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.SPENT));
if (connected == null)
connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.PENDING));
if (connected == null)
continue;
// The connected output may be the change to the sender of a previous input sent to this wallet. In this
// case we ignore it.
if (!connected.isMineOrWatched(wallet))
continue;
v = v.add(connected.getValue());
}
return v;
} | [
"public",
"Coin",
"getValueSentFromMe",
"(",
"TransactionBag",
"wallet",
")",
"throws",
"ScriptException",
"{",
"// This is tested in WalletTest.",
"Coin",
"v",
"=",
"Coin",
".",
"ZERO",
";",
"for",
"(",
"TransactionInput",
"input",
":",
"inputs",
")",
"{",
"// This input is taking value from a transaction in our wallet. To discover the value,",
"// we must find the connected transaction.",
"TransactionOutput",
"connected",
"=",
"input",
".",
"getConnectedOutput",
"(",
"wallet",
".",
"getTransactionPool",
"(",
"Pool",
".",
"UNSPENT",
")",
")",
";",
"if",
"(",
"connected",
"==",
"null",
")",
"connected",
"=",
"input",
".",
"getConnectedOutput",
"(",
"wallet",
".",
"getTransactionPool",
"(",
"Pool",
".",
"SPENT",
")",
")",
";",
"if",
"(",
"connected",
"==",
"null",
")",
"connected",
"=",
"input",
".",
"getConnectedOutput",
"(",
"wallet",
".",
"getTransactionPool",
"(",
"Pool",
".",
"PENDING",
")",
")",
";",
"if",
"(",
"connected",
"==",
"null",
")",
"continue",
";",
"// The connected output may be the change to the sender of a previous input sent to this wallet. In this",
"// case we ignore it.",
"if",
"(",
"!",
"connected",
".",
"isMineOrWatched",
"(",
"wallet",
")",
")",
"continue",
";",
"v",
"=",
"v",
".",
"add",
"(",
"connected",
".",
"getValue",
"(",
")",
")",
";",
"}",
"return",
"v",
";",
"}"
] | Calculates the sum of the inputs that are spending coins with keys in the wallet. This requires the
transactions sending coins to those keys to be in the wallet. This method will not attempt to download the
blocks containing the input transactions if the key is in the wallet but the transactions are not.
@return sum of the inputs that are spending coins with keys in the wallet | [
"Calculates",
"the",
"sum",
"of",
"the",
"inputs",
"that",
"are",
"spending",
"coins",
"with",
"keys",
"in",
"the",
"wallet",
".",
"This",
"requires",
"the",
"transactions",
"sending",
"coins",
"to",
"those",
"keys",
"to",
"be",
"in",
"the",
"wallet",
".",
"This",
"method",
"will",
"not",
"attempt",
"to",
"download",
"the",
"blocks",
"containing",
"the",
"input",
"transactions",
"if",
"the",
"key",
"is",
"in",
"the",
"wallet",
"but",
"the",
"transactions",
"are",
"not",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L424-L444 |
23,415 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.getOutputSum | public Coin getOutputSum() {
Coin totalOut = Coin.ZERO;
for (TransactionOutput output: outputs) {
totalOut = totalOut.add(output.getValue());
}
return totalOut;
} | java | public Coin getOutputSum() {
Coin totalOut = Coin.ZERO;
for (TransactionOutput output: outputs) {
totalOut = totalOut.add(output.getValue());
}
return totalOut;
} | [
"public",
"Coin",
"getOutputSum",
"(",
")",
"{",
"Coin",
"totalOut",
"=",
"Coin",
".",
"ZERO",
";",
"for",
"(",
"TransactionOutput",
"output",
":",
"outputs",
")",
"{",
"totalOut",
"=",
"totalOut",
".",
"add",
"(",
"output",
".",
"getValue",
"(",
")",
")",
";",
"}",
"return",
"totalOut",
";",
"}"
] | Gets the sum of the outputs of the transaction. If the outputs are less than the inputs, it does not count the fee.
@return the sum of the outputs regardless of who owns them. | [
"Gets",
"the",
"sum",
"of",
"the",
"outputs",
"of",
"the",
"transaction",
".",
"If",
"the",
"outputs",
"are",
"less",
"than",
"the",
"inputs",
"it",
"does",
"not",
"count",
"the",
"fee",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L450-L458 |
23,416 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.getFee | public Coin getFee() {
Coin fee = Coin.ZERO;
if (inputs.isEmpty() || outputs.isEmpty()) // Incomplete transaction
return null;
for (TransactionInput input : inputs) {
if (input.getValue() == null)
return null;
fee = fee.add(input.getValue());
}
for (TransactionOutput output : outputs) {
fee = fee.subtract(output.getValue());
}
return fee;
} | java | public Coin getFee() {
Coin fee = Coin.ZERO;
if (inputs.isEmpty() || outputs.isEmpty()) // Incomplete transaction
return null;
for (TransactionInput input : inputs) {
if (input.getValue() == null)
return null;
fee = fee.add(input.getValue());
}
for (TransactionOutput output : outputs) {
fee = fee.subtract(output.getValue());
}
return fee;
} | [
"public",
"Coin",
"getFee",
"(",
")",
"{",
"Coin",
"fee",
"=",
"Coin",
".",
"ZERO",
";",
"if",
"(",
"inputs",
".",
"isEmpty",
"(",
")",
"||",
"outputs",
".",
"isEmpty",
"(",
")",
")",
"// Incomplete transaction",
"return",
"null",
";",
"for",
"(",
"TransactionInput",
"input",
":",
"inputs",
")",
"{",
"if",
"(",
"input",
".",
"getValue",
"(",
")",
"==",
"null",
")",
"return",
"null",
";",
"fee",
"=",
"fee",
".",
"add",
"(",
"input",
".",
"getValue",
"(",
")",
")",
";",
"}",
"for",
"(",
"TransactionOutput",
"output",
":",
"outputs",
")",
"{",
"fee",
"=",
"fee",
".",
"subtract",
"(",
"output",
".",
"getValue",
"(",
")",
")",
";",
"}",
"return",
"fee",
";",
"}"
] | The transaction fee is the difference of the value of all inputs and the value of all outputs. Currently, the fee
can only be determined for transactions created by us.
@return fee, or null if it cannot be determined | [
"The",
"transaction",
"fee",
"is",
"the",
"difference",
"of",
"the",
"value",
"of",
"all",
"inputs",
"and",
"the",
"value",
"of",
"all",
"outputs",
".",
"Currently",
"the",
"fee",
"can",
"only",
"be",
"determined",
"for",
"transactions",
"created",
"by",
"us",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L485-L498 |
23,417 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.isEveryOwnedOutputSpent | public boolean isEveryOwnedOutputSpent(TransactionBag transactionBag) {
for (TransactionOutput output : outputs) {
if (output.isAvailableForSpending() && output.isMineOrWatched(transactionBag))
return false;
}
return true;
} | java | public boolean isEveryOwnedOutputSpent(TransactionBag transactionBag) {
for (TransactionOutput output : outputs) {
if (output.isAvailableForSpending() && output.isMineOrWatched(transactionBag))
return false;
}
return true;
} | [
"public",
"boolean",
"isEveryOwnedOutputSpent",
"(",
"TransactionBag",
"transactionBag",
")",
"{",
"for",
"(",
"TransactionOutput",
"output",
":",
"outputs",
")",
"{",
"if",
"(",
"output",
".",
"isAvailableForSpending",
"(",
")",
"&&",
"output",
".",
"isMineOrWatched",
"(",
"transactionBag",
")",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Returns false if this transaction has at least one output that is owned by the given wallet and unspent, true
otherwise. | [
"Returns",
"false",
"if",
"this",
"transaction",
"has",
"at",
"least",
"one",
"output",
"that",
"is",
"owned",
"by",
"the",
"given",
"wallet",
"and",
"unspent",
"true",
"otherwise",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L515-L521 |
23,418 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.isMature | public boolean isMature() {
if (!isCoinBase())
return true;
if (getConfidence().getConfidenceType() != ConfidenceType.BUILDING)
return false;
return getConfidence().getDepthInBlocks() >= params.getSpendableCoinbaseDepth();
} | java | public boolean isMature() {
if (!isCoinBase())
return true;
if (getConfidence().getConfidenceType() != ConfidenceType.BUILDING)
return false;
return getConfidence().getDepthInBlocks() >= params.getSpendableCoinbaseDepth();
} | [
"public",
"boolean",
"isMature",
"(",
")",
"{",
"if",
"(",
"!",
"isCoinBase",
"(",
")",
")",
"return",
"true",
";",
"if",
"(",
"getConfidence",
"(",
")",
".",
"getConfidenceType",
"(",
")",
"!=",
"ConfidenceType",
".",
"BUILDING",
")",
"return",
"false",
";",
"return",
"getConfidence",
"(",
")",
".",
"getDepthInBlocks",
"(",
")",
">=",
"params",
".",
"getSpendableCoinbaseDepth",
"(",
")",
";",
"}"
] | A transaction is mature if it is either a building coinbase tx that is as deep or deeper than the required coinbase depth, or a non-coinbase tx. | [
"A",
"transaction",
"is",
"mature",
"if",
"it",
"is",
"either",
"a",
"building",
"coinbase",
"tx",
"that",
"is",
"as",
"deep",
"or",
"deeper",
"than",
"the",
"required",
"coinbase",
"depth",
"or",
"a",
"non",
"-",
"coinbase",
"tx",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L739-L747 |
23,419 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.clearInputs | public void clearInputs() {
unCache();
for (TransactionInput input : inputs) {
input.setParent(null);
}
inputs.clear();
// You wanted to reserialize, right?
this.length = this.unsafeBitcoinSerialize().length;
} | java | public void clearInputs() {
unCache();
for (TransactionInput input : inputs) {
input.setParent(null);
}
inputs.clear();
// You wanted to reserialize, right?
this.length = this.unsafeBitcoinSerialize().length;
} | [
"public",
"void",
"clearInputs",
"(",
")",
"{",
"unCache",
"(",
")",
";",
"for",
"(",
"TransactionInput",
"input",
":",
"inputs",
")",
"{",
"input",
".",
"setParent",
"(",
"null",
")",
";",
"}",
"inputs",
".",
"clear",
"(",
")",
";",
"// You wanted to reserialize, right?",
"this",
".",
"length",
"=",
"this",
".",
"unsafeBitcoinSerialize",
"(",
")",
".",
"length",
";",
"}"
] | Removes all the inputs from this transaction.
Note that this also invalidates the length attribute | [
"Removes",
"all",
"the",
"inputs",
"from",
"this",
"transaction",
".",
"Note",
"that",
"this",
"also",
"invalidates",
"the",
"length",
"attribute"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L910-L918 |
23,420 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.addInput | public TransactionInput addInput(TransactionInput input) {
unCache();
input.setParent(this);
inputs.add(input);
adjustLength(inputs.size(), input.length);
return input;
} | java | public TransactionInput addInput(TransactionInput input) {
unCache();
input.setParent(this);
inputs.add(input);
adjustLength(inputs.size(), input.length);
return input;
} | [
"public",
"TransactionInput",
"addInput",
"(",
"TransactionInput",
"input",
")",
"{",
"unCache",
"(",
")",
";",
"input",
".",
"setParent",
"(",
"this",
")",
";",
"inputs",
".",
"add",
"(",
"input",
")",
";",
"adjustLength",
"(",
"inputs",
".",
"size",
"(",
")",
",",
"input",
".",
"length",
")",
";",
"return",
"input",
";",
"}"
] | Adds an input directly, with no checking that it's valid.
@return the new input. | [
"Adds",
"an",
"input",
"directly",
"with",
"no",
"checking",
"that",
"it",
"s",
"valid",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L935-L941 |
23,421 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.addInput | public TransactionInput addInput(Sha256Hash spendTxHash, long outputIndex, Script script) {
return addInput(new TransactionInput(params, this, script.getProgram(), new TransactionOutPoint(params, outputIndex, spendTxHash)));
} | java | public TransactionInput addInput(Sha256Hash spendTxHash, long outputIndex, Script script) {
return addInput(new TransactionInput(params, this, script.getProgram(), new TransactionOutPoint(params, outputIndex, spendTxHash)));
} | [
"public",
"TransactionInput",
"addInput",
"(",
"Sha256Hash",
"spendTxHash",
",",
"long",
"outputIndex",
",",
"Script",
"script",
")",
"{",
"return",
"addInput",
"(",
"new",
"TransactionInput",
"(",
"params",
",",
"this",
",",
"script",
".",
"getProgram",
"(",
")",
",",
"new",
"TransactionOutPoint",
"(",
"params",
",",
"outputIndex",
",",
"spendTxHash",
")",
")",
")",
";",
"}"
] | Creates and adds an input to this transaction, with no checking that it's valid.
@return the newly created input. | [
"Creates",
"and",
"adds",
"an",
"input",
"to",
"this",
"transaction",
"with",
"no",
"checking",
"that",
"it",
"s",
"valid",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L947-L949 |
23,422 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.clearOutputs | public void clearOutputs() {
unCache();
for (TransactionOutput output : outputs) {
output.setParent(null);
}
outputs.clear();
// You wanted to reserialize, right?
this.length = this.unsafeBitcoinSerialize().length;
} | java | public void clearOutputs() {
unCache();
for (TransactionOutput output : outputs) {
output.setParent(null);
}
outputs.clear();
// You wanted to reserialize, right?
this.length = this.unsafeBitcoinSerialize().length;
} | [
"public",
"void",
"clearOutputs",
"(",
")",
"{",
"unCache",
"(",
")",
";",
"for",
"(",
"TransactionOutput",
"output",
":",
"outputs",
")",
"{",
"output",
".",
"setParent",
"(",
"null",
")",
";",
"}",
"outputs",
".",
"clear",
"(",
")",
";",
"// You wanted to reserialize, right?",
"this",
".",
"length",
"=",
"this",
".",
"unsafeBitcoinSerialize",
"(",
")",
".",
"length",
";",
"}"
] | Removes all the outputs from this transaction.
Note that this also invalidates the length attribute | [
"Removes",
"all",
"the",
"outputs",
"from",
"this",
"transaction",
".",
"Note",
"that",
"this",
"also",
"invalidates",
"the",
"length",
"attribute"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L1017-L1025 |
23,423 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.addOutput | public TransactionOutput addOutput(TransactionOutput to) {
unCache();
to.setParent(this);
outputs.add(to);
adjustLength(outputs.size(), to.length);
return to;
} | java | public TransactionOutput addOutput(TransactionOutput to) {
unCache();
to.setParent(this);
outputs.add(to);
adjustLength(outputs.size(), to.length);
return to;
} | [
"public",
"TransactionOutput",
"addOutput",
"(",
"TransactionOutput",
"to",
")",
"{",
"unCache",
"(",
")",
";",
"to",
".",
"setParent",
"(",
"this",
")",
";",
"outputs",
".",
"add",
"(",
"to",
")",
";",
"adjustLength",
"(",
"outputs",
".",
"size",
"(",
")",
",",
"to",
".",
"length",
")",
";",
"return",
"to",
";",
"}"
] | Adds the given output to this transaction. The output must be completely initialized. Returns the given output. | [
"Adds",
"the",
"given",
"output",
"to",
"this",
"transaction",
".",
"The",
"output",
"must",
"be",
"completely",
"initialized",
".",
"Returns",
"the",
"given",
"output",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L1030-L1036 |
23,424 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.addOutput | public TransactionOutput addOutput(Coin value, Address address) {
return addOutput(new TransactionOutput(params, this, value, address));
} | java | public TransactionOutput addOutput(Coin value, Address address) {
return addOutput(new TransactionOutput(params, this, value, address));
} | [
"public",
"TransactionOutput",
"addOutput",
"(",
"Coin",
"value",
",",
"Address",
"address",
")",
"{",
"return",
"addOutput",
"(",
"new",
"TransactionOutput",
"(",
"params",
",",
"this",
",",
"value",
",",
"address",
")",
")",
";",
"}"
] | Creates an output based on the given address and value, adds it to this transaction, and returns the new output. | [
"Creates",
"an",
"output",
"based",
"on",
"the",
"given",
"address",
"and",
"value",
"adds",
"it",
"to",
"this",
"transaction",
"and",
"returns",
"the",
"new",
"output",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L1041-L1043 |
23,425 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.addOutput | public TransactionOutput addOutput(Coin value, Script script) {
return addOutput(new TransactionOutput(params, this, value, script.getProgram()));
} | java | public TransactionOutput addOutput(Coin value, Script script) {
return addOutput(new TransactionOutput(params, this, value, script.getProgram()));
} | [
"public",
"TransactionOutput",
"addOutput",
"(",
"Coin",
"value",
",",
"Script",
"script",
")",
"{",
"return",
"addOutput",
"(",
"new",
"TransactionOutput",
"(",
"params",
",",
"this",
",",
"value",
",",
"script",
".",
"getProgram",
"(",
")",
")",
")",
";",
"}"
] | Creates an output that pays to the given script. The address and key forms are specialisations of this method,
you won't normally need to use it unless you're doing unusual things. | [
"Creates",
"an",
"output",
"that",
"pays",
"to",
"the",
"given",
"script",
".",
"The",
"address",
"and",
"key",
"forms",
"are",
"specialisations",
"of",
"this",
"method",
"you",
"won",
"t",
"normally",
"need",
"to",
"use",
"it",
"unless",
"you",
"re",
"doing",
"unusual",
"things",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L1057-L1059 |
23,426 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.hashForSignature | public Sha256Hash hashForSignature(int inputIndex, byte[] connectedScript, byte sigHashType) {
// The SIGHASH flags are used in the design of contracts, please see this page for a further understanding of
// the purposes of the code in this method:
//
// https://en.bitcoin.it/wiki/Contracts
try {
// Create a copy of this transaction to operate upon because we need make changes to the inputs and outputs.
// It would not be thread-safe to change the attributes of the transaction object itself.
Transaction tx = this.params.getDefaultSerializer().makeTransaction(this.bitcoinSerialize());
// Clear input scripts in preparation for signing. If we're signing a fresh
// transaction that step isn't very helpful, but it doesn't add much cost relative to the actual
// EC math so we'll do it anyway.
for (int i = 0; i < tx.inputs.size(); i++) {
TransactionInput input = tx.inputs.get(i);
input.clearScriptBytes();
input.setWitness(null);
}
// This step has no purpose beyond being synchronized with Bitcoin Core's bugs. OP_CODESEPARATOR
// is a legacy holdover from a previous, broken design of executing scripts that shipped in Bitcoin 0.1.
// It was seriously flawed and would have let anyone take anyone elses money. Later versions switched to
// the design we use today where scripts are executed independently but share a stack. This left the
// OP_CODESEPARATOR instruction having no purpose as it was only meant to be used internally, not actually
// ever put into scripts. Deleting OP_CODESEPARATOR is a step that should never be required but if we don't
// do it, we could split off the best chain.
connectedScript = Script.removeAllInstancesOfOp(connectedScript, ScriptOpCodes.OP_CODESEPARATOR);
// Set the input to the script of its output. Bitcoin Core does this but the step has no obvious purpose as
// the signature covers the hash of the prevout transaction which obviously includes the output script
// already. Perhaps it felt safer to him in some way, or is another leftover from how the code was written.
TransactionInput input = tx.inputs.get(inputIndex);
input.setScriptBytes(connectedScript);
if ((sigHashType & 0x1f) == SigHash.NONE.value) {
// SIGHASH_NONE means no outputs are signed at all - the signature is effectively for a "blank cheque".
tx.outputs = new ArrayList<>(0);
// The signature isn't broken by new versions of the transaction issued by other parties.
for (int i = 0; i < tx.inputs.size(); i++)
if (i != inputIndex)
tx.inputs.get(i).setSequenceNumber(0);
} else if ((sigHashType & 0x1f) == SigHash.SINGLE.value) {
// SIGHASH_SINGLE means only sign the output at the same index as the input (ie, my output).
if (inputIndex >= tx.outputs.size()) {
// The input index is beyond the number of outputs, it's a buggy signature made by a broken
// Bitcoin implementation. Bitcoin Core also contains a bug in handling this case:
// any transaction output that is signed in this case will result in both the signed output
// and any future outputs to this public key being steal-able by anyone who has
// the resulting signature and the public key (both of which are part of the signed tx input).
// Bitcoin Core's bug is that SignatureHash was supposed to return a hash and on this codepath it
// actually returns the constant "1" to indicate an error, which is never checked for. Oops.
return Sha256Hash.wrap("0100000000000000000000000000000000000000000000000000000000000000");
}
// In SIGHASH_SINGLE the outputs after the matching input index are deleted, and the outputs before
// that position are "nulled out". Unintuitively, the value in a "null" transaction is set to -1.
tx.outputs = new ArrayList<>(tx.outputs.subList(0, inputIndex + 1));
for (int i = 0; i < inputIndex; i++)
tx.outputs.set(i, new TransactionOutput(tx.params, tx, Coin.NEGATIVE_SATOSHI, new byte[] {}));
// The signature isn't broken by new versions of the transaction issued by other parties.
for (int i = 0; i < tx.inputs.size(); i++)
if (i != inputIndex)
tx.inputs.get(i).setSequenceNumber(0);
}
if ((sigHashType & SigHash.ANYONECANPAY.value) == SigHash.ANYONECANPAY.value) {
// SIGHASH_ANYONECANPAY means the signature in the input is not broken by changes/additions/removals
// of other inputs. For example, this is useful for building assurance contracts.
tx.inputs = new ArrayList<>();
tx.inputs.add(input);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream(tx.length);
tx.bitcoinSerializeToStream(bos, false);
// We also have to write a hash type (sigHashType is actually an unsigned char)
uint32ToByteStreamLE(0x000000ff & sigHashType, bos);
// Note that this is NOT reversed to ensure it will be signed correctly. If it were to be printed out
// however then we would expect that it is IS reversed.
Sha256Hash hash = Sha256Hash.twiceOf(bos.toByteArray());
bos.close();
return hash;
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
} | java | public Sha256Hash hashForSignature(int inputIndex, byte[] connectedScript, byte sigHashType) {
// The SIGHASH flags are used in the design of contracts, please see this page for a further understanding of
// the purposes of the code in this method:
//
// https://en.bitcoin.it/wiki/Contracts
try {
// Create a copy of this transaction to operate upon because we need make changes to the inputs and outputs.
// It would not be thread-safe to change the attributes of the transaction object itself.
Transaction tx = this.params.getDefaultSerializer().makeTransaction(this.bitcoinSerialize());
// Clear input scripts in preparation for signing. If we're signing a fresh
// transaction that step isn't very helpful, but it doesn't add much cost relative to the actual
// EC math so we'll do it anyway.
for (int i = 0; i < tx.inputs.size(); i++) {
TransactionInput input = tx.inputs.get(i);
input.clearScriptBytes();
input.setWitness(null);
}
// This step has no purpose beyond being synchronized with Bitcoin Core's bugs. OP_CODESEPARATOR
// is a legacy holdover from a previous, broken design of executing scripts that shipped in Bitcoin 0.1.
// It was seriously flawed and would have let anyone take anyone elses money. Later versions switched to
// the design we use today where scripts are executed independently but share a stack. This left the
// OP_CODESEPARATOR instruction having no purpose as it was only meant to be used internally, not actually
// ever put into scripts. Deleting OP_CODESEPARATOR is a step that should never be required but if we don't
// do it, we could split off the best chain.
connectedScript = Script.removeAllInstancesOfOp(connectedScript, ScriptOpCodes.OP_CODESEPARATOR);
// Set the input to the script of its output. Bitcoin Core does this but the step has no obvious purpose as
// the signature covers the hash of the prevout transaction which obviously includes the output script
// already. Perhaps it felt safer to him in some way, or is another leftover from how the code was written.
TransactionInput input = tx.inputs.get(inputIndex);
input.setScriptBytes(connectedScript);
if ((sigHashType & 0x1f) == SigHash.NONE.value) {
// SIGHASH_NONE means no outputs are signed at all - the signature is effectively for a "blank cheque".
tx.outputs = new ArrayList<>(0);
// The signature isn't broken by new versions of the transaction issued by other parties.
for (int i = 0; i < tx.inputs.size(); i++)
if (i != inputIndex)
tx.inputs.get(i).setSequenceNumber(0);
} else if ((sigHashType & 0x1f) == SigHash.SINGLE.value) {
// SIGHASH_SINGLE means only sign the output at the same index as the input (ie, my output).
if (inputIndex >= tx.outputs.size()) {
// The input index is beyond the number of outputs, it's a buggy signature made by a broken
// Bitcoin implementation. Bitcoin Core also contains a bug in handling this case:
// any transaction output that is signed in this case will result in both the signed output
// and any future outputs to this public key being steal-able by anyone who has
// the resulting signature and the public key (both of which are part of the signed tx input).
// Bitcoin Core's bug is that SignatureHash was supposed to return a hash and on this codepath it
// actually returns the constant "1" to indicate an error, which is never checked for. Oops.
return Sha256Hash.wrap("0100000000000000000000000000000000000000000000000000000000000000");
}
// In SIGHASH_SINGLE the outputs after the matching input index are deleted, and the outputs before
// that position are "nulled out". Unintuitively, the value in a "null" transaction is set to -1.
tx.outputs = new ArrayList<>(tx.outputs.subList(0, inputIndex + 1));
for (int i = 0; i < inputIndex; i++)
tx.outputs.set(i, new TransactionOutput(tx.params, tx, Coin.NEGATIVE_SATOSHI, new byte[] {}));
// The signature isn't broken by new versions of the transaction issued by other parties.
for (int i = 0; i < tx.inputs.size(); i++)
if (i != inputIndex)
tx.inputs.get(i).setSequenceNumber(0);
}
if ((sigHashType & SigHash.ANYONECANPAY.value) == SigHash.ANYONECANPAY.value) {
// SIGHASH_ANYONECANPAY means the signature in the input is not broken by changes/additions/removals
// of other inputs. For example, this is useful for building assurance contracts.
tx.inputs = new ArrayList<>();
tx.inputs.add(input);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream(tx.length);
tx.bitcoinSerializeToStream(bos, false);
// We also have to write a hash type (sigHashType is actually an unsigned char)
uint32ToByteStreamLE(0x000000ff & sigHashType, bos);
// Note that this is NOT reversed to ensure it will be signed correctly. If it were to be printed out
// however then we would expect that it is IS reversed.
Sha256Hash hash = Sha256Hash.twiceOf(bos.toByteArray());
bos.close();
return hash;
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
} | [
"public",
"Sha256Hash",
"hashForSignature",
"(",
"int",
"inputIndex",
",",
"byte",
"[",
"]",
"connectedScript",
",",
"byte",
"sigHashType",
")",
"{",
"// The SIGHASH flags are used in the design of contracts, please see this page for a further understanding of",
"// the purposes of the code in this method:",
"//",
"// https://en.bitcoin.it/wiki/Contracts",
"try",
"{",
"// Create a copy of this transaction to operate upon because we need make changes to the inputs and outputs.",
"// It would not be thread-safe to change the attributes of the transaction object itself.",
"Transaction",
"tx",
"=",
"this",
".",
"params",
".",
"getDefaultSerializer",
"(",
")",
".",
"makeTransaction",
"(",
"this",
".",
"bitcoinSerialize",
"(",
")",
")",
";",
"// Clear input scripts in preparation for signing. If we're signing a fresh",
"// transaction that step isn't very helpful, but it doesn't add much cost relative to the actual",
"// EC math so we'll do it anyway.",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"tx",
".",
"inputs",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"TransactionInput",
"input",
"=",
"tx",
".",
"inputs",
".",
"get",
"(",
"i",
")",
";",
"input",
".",
"clearScriptBytes",
"(",
")",
";",
"input",
".",
"setWitness",
"(",
"null",
")",
";",
"}",
"// This step has no purpose beyond being synchronized with Bitcoin Core's bugs. OP_CODESEPARATOR",
"// is a legacy holdover from a previous, broken design of executing scripts that shipped in Bitcoin 0.1.",
"// It was seriously flawed and would have let anyone take anyone elses money. Later versions switched to",
"// the design we use today where scripts are executed independently but share a stack. This left the",
"// OP_CODESEPARATOR instruction having no purpose as it was only meant to be used internally, not actually",
"// ever put into scripts. Deleting OP_CODESEPARATOR is a step that should never be required but if we don't",
"// do it, we could split off the best chain.",
"connectedScript",
"=",
"Script",
".",
"removeAllInstancesOfOp",
"(",
"connectedScript",
",",
"ScriptOpCodes",
".",
"OP_CODESEPARATOR",
")",
";",
"// Set the input to the script of its output. Bitcoin Core does this but the step has no obvious purpose as",
"// the signature covers the hash of the prevout transaction which obviously includes the output script",
"// already. Perhaps it felt safer to him in some way, or is another leftover from how the code was written.",
"TransactionInput",
"input",
"=",
"tx",
".",
"inputs",
".",
"get",
"(",
"inputIndex",
")",
";",
"input",
".",
"setScriptBytes",
"(",
"connectedScript",
")",
";",
"if",
"(",
"(",
"sigHashType",
"&",
"0x1f",
")",
"==",
"SigHash",
".",
"NONE",
".",
"value",
")",
"{",
"// SIGHASH_NONE means no outputs are signed at all - the signature is effectively for a \"blank cheque\".",
"tx",
".",
"outputs",
"=",
"new",
"ArrayList",
"<>",
"(",
"0",
")",
";",
"// The signature isn't broken by new versions of the transaction issued by other parties.",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"tx",
".",
"inputs",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"if",
"(",
"i",
"!=",
"inputIndex",
")",
"tx",
".",
"inputs",
".",
"get",
"(",
"i",
")",
".",
"setSequenceNumber",
"(",
"0",
")",
";",
"}",
"else",
"if",
"(",
"(",
"sigHashType",
"&",
"0x1f",
")",
"==",
"SigHash",
".",
"SINGLE",
".",
"value",
")",
"{",
"// SIGHASH_SINGLE means only sign the output at the same index as the input (ie, my output).",
"if",
"(",
"inputIndex",
">=",
"tx",
".",
"outputs",
".",
"size",
"(",
")",
")",
"{",
"// The input index is beyond the number of outputs, it's a buggy signature made by a broken",
"// Bitcoin implementation. Bitcoin Core also contains a bug in handling this case:",
"// any transaction output that is signed in this case will result in both the signed output",
"// and any future outputs to this public key being steal-able by anyone who has",
"// the resulting signature and the public key (both of which are part of the signed tx input).",
"// Bitcoin Core's bug is that SignatureHash was supposed to return a hash and on this codepath it",
"// actually returns the constant \"1\" to indicate an error, which is never checked for. Oops.",
"return",
"Sha256Hash",
".",
"wrap",
"(",
"\"0100000000000000000000000000000000000000000000000000000000000000\"",
")",
";",
"}",
"// In SIGHASH_SINGLE the outputs after the matching input index are deleted, and the outputs before",
"// that position are \"nulled out\". Unintuitively, the value in a \"null\" transaction is set to -1.",
"tx",
".",
"outputs",
"=",
"new",
"ArrayList",
"<>",
"(",
"tx",
".",
"outputs",
".",
"subList",
"(",
"0",
",",
"inputIndex",
"+",
"1",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"inputIndex",
";",
"i",
"++",
")",
"tx",
".",
"outputs",
".",
"set",
"(",
"i",
",",
"new",
"TransactionOutput",
"(",
"tx",
".",
"params",
",",
"tx",
",",
"Coin",
".",
"NEGATIVE_SATOSHI",
",",
"new",
"byte",
"[",
"]",
"{",
"}",
")",
")",
";",
"// The signature isn't broken by new versions of the transaction issued by other parties.",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"tx",
".",
"inputs",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"if",
"(",
"i",
"!=",
"inputIndex",
")",
"tx",
".",
"inputs",
".",
"get",
"(",
"i",
")",
".",
"setSequenceNumber",
"(",
"0",
")",
";",
"}",
"if",
"(",
"(",
"sigHashType",
"&",
"SigHash",
".",
"ANYONECANPAY",
".",
"value",
")",
"==",
"SigHash",
".",
"ANYONECANPAY",
".",
"value",
")",
"{",
"// SIGHASH_ANYONECANPAY means the signature in the input is not broken by changes/additions/removals",
"// of other inputs. For example, this is useful for building assurance contracts.",
"tx",
".",
"inputs",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"tx",
".",
"inputs",
".",
"add",
"(",
"input",
")",
";",
"}",
"ByteArrayOutputStream",
"bos",
"=",
"new",
"ByteArrayOutputStream",
"(",
"tx",
".",
"length",
")",
";",
"tx",
".",
"bitcoinSerializeToStream",
"(",
"bos",
",",
"false",
")",
";",
"// We also have to write a hash type (sigHashType is actually an unsigned char)",
"uint32ToByteStreamLE",
"(",
"0x000000ff",
"&",
"sigHashType",
",",
"bos",
")",
";",
"// Note that this is NOT reversed to ensure it will be signed correctly. If it were to be printed out",
"// however then we would expect that it is IS reversed.",
"Sha256Hash",
"hash",
"=",
"Sha256Hash",
".",
"twiceOf",
"(",
"bos",
".",
"toByteArray",
"(",
")",
")",
";",
"bos",
".",
"close",
"(",
")",
";",
"return",
"hash",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"// Cannot happen.",
"}",
"}"
] | This is required for signatures which use a sigHashType which cannot be represented using SigHash and anyoneCanPay
See transaction c99c49da4c38af669dea436d3e73780dfdb6c1ecf9958baa52960e8baee30e73, which has sigHashType 0 | [
"This",
"is",
"required",
"for",
"signatures",
"which",
"use",
"a",
"sigHashType",
"which",
"cannot",
"be",
"represented",
"using",
"SigHash",
"and",
"anyoneCanPay",
"See",
"transaction",
"c99c49da4c38af669dea436d3e73780dfdb6c1ecf9958baa52960e8baee30e73",
"which",
"has",
"sigHashType",
"0"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L1188-L1274 |
23,427 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.getSigOpCount | public int getSigOpCount() throws ScriptException {
int sigOps = 0;
for (TransactionInput input : inputs)
sigOps += Script.getSigOpCount(input.getScriptBytes());
for (TransactionOutput output : outputs)
sigOps += Script.getSigOpCount(output.getScriptBytes());
return sigOps;
} | java | public int getSigOpCount() throws ScriptException {
int sigOps = 0;
for (TransactionInput input : inputs)
sigOps += Script.getSigOpCount(input.getScriptBytes());
for (TransactionOutput output : outputs)
sigOps += Script.getSigOpCount(output.getScriptBytes());
return sigOps;
} | [
"public",
"int",
"getSigOpCount",
"(",
")",
"throws",
"ScriptException",
"{",
"int",
"sigOps",
"=",
"0",
";",
"for",
"(",
"TransactionInput",
"input",
":",
"inputs",
")",
"sigOps",
"+=",
"Script",
".",
"getSigOpCount",
"(",
"input",
".",
"getScriptBytes",
"(",
")",
")",
";",
"for",
"(",
"TransactionOutput",
"output",
":",
"outputs",
")",
"sigOps",
"+=",
"Script",
".",
"getSigOpCount",
"(",
"output",
".",
"getScriptBytes",
"(",
")",
")",
";",
"return",
"sigOps",
";",
"}"
] | Gets the count of regular SigOps in this transactions | [
"Gets",
"the",
"count",
"of",
"regular",
"SigOps",
"in",
"this",
"transactions"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L1592-L1599 |
23,428 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.checkCoinBaseHeight | public void checkCoinBaseHeight(final int height)
throws VerificationException {
checkArgument(height >= Block.BLOCK_HEIGHT_GENESIS);
checkState(isCoinBase());
// Check block height is in coinbase input script
final TransactionInput in = this.getInputs().get(0);
final ScriptBuilder builder = new ScriptBuilder();
builder.number(height);
final byte[] expected = builder.build().getProgram();
final byte[] actual = in.getScriptBytes();
if (actual.length < expected.length) {
throw new VerificationException.CoinbaseHeightMismatch("Block height mismatch in coinbase.");
}
for (int scriptIdx = 0; scriptIdx < expected.length; scriptIdx++) {
if (actual[scriptIdx] != expected[scriptIdx]) {
throw new VerificationException.CoinbaseHeightMismatch("Block height mismatch in coinbase.");
}
}
} | java | public void checkCoinBaseHeight(final int height)
throws VerificationException {
checkArgument(height >= Block.BLOCK_HEIGHT_GENESIS);
checkState(isCoinBase());
// Check block height is in coinbase input script
final TransactionInput in = this.getInputs().get(0);
final ScriptBuilder builder = new ScriptBuilder();
builder.number(height);
final byte[] expected = builder.build().getProgram();
final byte[] actual = in.getScriptBytes();
if (actual.length < expected.length) {
throw new VerificationException.CoinbaseHeightMismatch("Block height mismatch in coinbase.");
}
for (int scriptIdx = 0; scriptIdx < expected.length; scriptIdx++) {
if (actual[scriptIdx] != expected[scriptIdx]) {
throw new VerificationException.CoinbaseHeightMismatch("Block height mismatch in coinbase.");
}
}
} | [
"public",
"void",
"checkCoinBaseHeight",
"(",
"final",
"int",
"height",
")",
"throws",
"VerificationException",
"{",
"checkArgument",
"(",
"height",
">=",
"Block",
".",
"BLOCK_HEIGHT_GENESIS",
")",
";",
"checkState",
"(",
"isCoinBase",
"(",
")",
")",
";",
"// Check block height is in coinbase input script",
"final",
"TransactionInput",
"in",
"=",
"this",
".",
"getInputs",
"(",
")",
".",
"get",
"(",
"0",
")",
";",
"final",
"ScriptBuilder",
"builder",
"=",
"new",
"ScriptBuilder",
"(",
")",
";",
"builder",
".",
"number",
"(",
"height",
")",
";",
"final",
"byte",
"[",
"]",
"expected",
"=",
"builder",
".",
"build",
"(",
")",
".",
"getProgram",
"(",
")",
";",
"final",
"byte",
"[",
"]",
"actual",
"=",
"in",
".",
"getScriptBytes",
"(",
")",
";",
"if",
"(",
"actual",
".",
"length",
"<",
"expected",
".",
"length",
")",
"{",
"throw",
"new",
"VerificationException",
".",
"CoinbaseHeightMismatch",
"(",
"\"Block height mismatch in coinbase.\"",
")",
";",
"}",
"for",
"(",
"int",
"scriptIdx",
"=",
"0",
";",
"scriptIdx",
"<",
"expected",
".",
"length",
";",
"scriptIdx",
"++",
")",
"{",
"if",
"(",
"actual",
"[",
"scriptIdx",
"]",
"!=",
"expected",
"[",
"scriptIdx",
"]",
")",
"{",
"throw",
"new",
"VerificationException",
".",
"CoinbaseHeightMismatch",
"(",
"\"Block height mismatch in coinbase.\"",
")",
";",
"}",
"}",
"}"
] | Check block height is in coinbase input script, for use after BIP 34
enforcement is enabled. | [
"Check",
"block",
"height",
"is",
"in",
"coinbase",
"input",
"script",
"for",
"use",
"after",
"BIP",
"34",
"enforcement",
"is",
"enabled",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L1605-L1624 |
23,429 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.findWitnessCommitment | public Sha256Hash findWitnessCommitment() {
checkState(isCoinBase());
for (TransactionOutput out : Lists.reverse(outputs)) {
Script scriptPubKey = out.getScriptPubKey();
if (ScriptPattern.isWitnessCommitment(scriptPubKey))
return ScriptPattern.extractWitnessCommitmentHash(scriptPubKey);
}
return null;
} | java | public Sha256Hash findWitnessCommitment() {
checkState(isCoinBase());
for (TransactionOutput out : Lists.reverse(outputs)) {
Script scriptPubKey = out.getScriptPubKey();
if (ScriptPattern.isWitnessCommitment(scriptPubKey))
return ScriptPattern.extractWitnessCommitmentHash(scriptPubKey);
}
return null;
} | [
"public",
"Sha256Hash",
"findWitnessCommitment",
"(",
")",
"{",
"checkState",
"(",
"isCoinBase",
"(",
")",
")",
";",
"for",
"(",
"TransactionOutput",
"out",
":",
"Lists",
".",
"reverse",
"(",
"outputs",
")",
")",
"{",
"Script",
"scriptPubKey",
"=",
"out",
".",
"getScriptPubKey",
"(",
")",
";",
"if",
"(",
"ScriptPattern",
".",
"isWitnessCommitment",
"(",
"scriptPubKey",
")",
")",
"return",
"ScriptPattern",
".",
"extractWitnessCommitmentHash",
"(",
"scriptPubKey",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Loops the outputs of a coinbase transaction to locate the witness commitment. | [
"Loops",
"the",
"outputs",
"of",
"a",
"coinbase",
"transaction",
"to",
"locate",
"the",
"witness",
"commitment",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L1627-L1635 |
23,430 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Transaction.java | Transaction.estimateLockTime | public Date estimateLockTime(AbstractBlockChain chain) {
if (lockTime < LOCKTIME_THRESHOLD)
return chain.estimateBlockTime((int)getLockTime());
else
return new Date(getLockTime()*1000);
} | java | public Date estimateLockTime(AbstractBlockChain chain) {
if (lockTime < LOCKTIME_THRESHOLD)
return chain.estimateBlockTime((int)getLockTime());
else
return new Date(getLockTime()*1000);
} | [
"public",
"Date",
"estimateLockTime",
"(",
"AbstractBlockChain",
"chain",
")",
"{",
"if",
"(",
"lockTime",
"<",
"LOCKTIME_THRESHOLD",
")",
"return",
"chain",
".",
"estimateBlockTime",
"(",
"(",
"int",
")",
"getLockTime",
"(",
")",
")",
";",
"else",
"return",
"new",
"Date",
"(",
"getLockTime",
"(",
")",
"*",
"1000",
")",
";",
"}"
] | Returns either the lock time as a date, if it was specified in seconds, or an estimate based on the time in
the current head block if it was specified as a block time. | [
"Returns",
"either",
"the",
"lock",
"time",
"as",
"a",
"date",
"if",
"it",
"was",
"specified",
"in",
"seconds",
"or",
"an",
"estimate",
"based",
"on",
"the",
"time",
"in",
"the",
"current",
"head",
"block",
"if",
"it",
"was",
"specified",
"as",
"a",
"block",
"time",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Transaction.java#L1749-L1754 |
23,431 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/StoredPaymentChannelClientStates.java | StoredPaymentChannelClientStates.getBalanceForServer | public Coin getBalanceForServer(Sha256Hash id) {
Coin balance = Coin.ZERO;
lock.lock();
try {
Set<StoredClientChannel> setChannels = mapChannels.get(id);
for (StoredClientChannel channel : setChannels) {
synchronized (channel) {
if (channel.close != null) continue;
balance = balance.add(channel.valueToMe);
}
}
return balance;
} finally {
lock.unlock();
}
} | java | public Coin getBalanceForServer(Sha256Hash id) {
Coin balance = Coin.ZERO;
lock.lock();
try {
Set<StoredClientChannel> setChannels = mapChannels.get(id);
for (StoredClientChannel channel : setChannels) {
synchronized (channel) {
if (channel.close != null) continue;
balance = balance.add(channel.valueToMe);
}
}
return balance;
} finally {
lock.unlock();
}
} | [
"public",
"Coin",
"getBalanceForServer",
"(",
"Sha256Hash",
"id",
")",
"{",
"Coin",
"balance",
"=",
"Coin",
".",
"ZERO",
";",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"Set",
"<",
"StoredClientChannel",
">",
"setChannels",
"=",
"mapChannels",
".",
"get",
"(",
"id",
")",
";",
"for",
"(",
"StoredClientChannel",
"channel",
":",
"setChannels",
")",
"{",
"synchronized",
"(",
"channel",
")",
"{",
"if",
"(",
"channel",
".",
"close",
"!=",
"null",
")",
"continue",
";",
"balance",
"=",
"balance",
".",
"add",
"(",
"channel",
".",
"valueToMe",
")",
";",
"}",
"}",
"return",
"balance",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Returns the outstanding amount of money sent back to us for all channels to this server added together. | [
"Returns",
"the",
"outstanding",
"amount",
"of",
"money",
"sent",
"back",
"to",
"us",
"for",
"all",
"channels",
"to",
"this",
"server",
"added",
"together",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/StoredPaymentChannelClientStates.java#L97-L112 |
23,432 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/StoredPaymentChannelClientStates.java | StoredPaymentChannelClientStates.getSecondsUntilExpiry | public long getSecondsUntilExpiry(Sha256Hash id) {
lock.lock();
try {
final Set<StoredClientChannel> setChannels = mapChannels.get(id);
final long nowSeconds = Utils.currentTimeSeconds();
int earliestTime = Integer.MAX_VALUE;
for (StoredClientChannel channel : setChannels) {
synchronized (channel) {
if (channel.expiryTimeSeconds() > nowSeconds)
earliestTime = Math.min(earliestTime, (int) channel.expiryTimeSeconds());
}
}
return earliestTime == Integer.MAX_VALUE ? 0 : earliestTime - nowSeconds;
} finally {
lock.unlock();
}
} | java | public long getSecondsUntilExpiry(Sha256Hash id) {
lock.lock();
try {
final Set<StoredClientChannel> setChannels = mapChannels.get(id);
final long nowSeconds = Utils.currentTimeSeconds();
int earliestTime = Integer.MAX_VALUE;
for (StoredClientChannel channel : setChannels) {
synchronized (channel) {
if (channel.expiryTimeSeconds() > nowSeconds)
earliestTime = Math.min(earliestTime, (int) channel.expiryTimeSeconds());
}
}
return earliestTime == Integer.MAX_VALUE ? 0 : earliestTime - nowSeconds;
} finally {
lock.unlock();
}
} | [
"public",
"long",
"getSecondsUntilExpiry",
"(",
"Sha256Hash",
"id",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"final",
"Set",
"<",
"StoredClientChannel",
">",
"setChannels",
"=",
"mapChannels",
".",
"get",
"(",
"id",
")",
";",
"final",
"long",
"nowSeconds",
"=",
"Utils",
".",
"currentTimeSeconds",
"(",
")",
";",
"int",
"earliestTime",
"=",
"Integer",
".",
"MAX_VALUE",
";",
"for",
"(",
"StoredClientChannel",
"channel",
":",
"setChannels",
")",
"{",
"synchronized",
"(",
"channel",
")",
"{",
"if",
"(",
"channel",
".",
"expiryTimeSeconds",
"(",
")",
">",
"nowSeconds",
")",
"earliestTime",
"=",
"Math",
".",
"min",
"(",
"earliestTime",
",",
"(",
"int",
")",
"channel",
".",
"expiryTimeSeconds",
"(",
")",
")",
";",
"}",
"}",
"return",
"earliestTime",
"==",
"Integer",
".",
"MAX_VALUE",
"?",
"0",
":",
"earliestTime",
"-",
"nowSeconds",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Returns the number of seconds from now until this servers next channel will expire, or zero if no unexpired
channels found. | [
"Returns",
"the",
"number",
"of",
"seconds",
"from",
"now",
"until",
"this",
"servers",
"next",
"channel",
"will",
"expire",
"or",
"zero",
"if",
"no",
"unexpired",
"channels",
"found",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/StoredPaymentChannelClientStates.java#L118-L134 |
23,433 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/StoredPaymentChannelClientStates.java | StoredPaymentChannelClientStates.getChannel | @Nullable
public StoredClientChannel getChannel(Sha256Hash id, Sha256Hash contractHash) {
lock.lock();
try {
Set<StoredClientChannel> setChannels = mapChannels.get(id);
for (StoredClientChannel channel : setChannels) {
if (channel.contract.getTxId().equals(contractHash))
return channel;
}
return null;
} finally {
lock.unlock();
}
} | java | @Nullable
public StoredClientChannel getChannel(Sha256Hash id, Sha256Hash contractHash) {
lock.lock();
try {
Set<StoredClientChannel> setChannels = mapChannels.get(id);
for (StoredClientChannel channel : setChannels) {
if (channel.contract.getTxId().equals(contractHash))
return channel;
}
return null;
} finally {
lock.unlock();
}
} | [
"@",
"Nullable",
"public",
"StoredClientChannel",
"getChannel",
"(",
"Sha256Hash",
"id",
",",
"Sha256Hash",
"contractHash",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"Set",
"<",
"StoredClientChannel",
">",
"setChannels",
"=",
"mapChannels",
".",
"get",
"(",
"id",
")",
";",
"for",
"(",
"StoredClientChannel",
"channel",
":",
"setChannels",
")",
"{",
"if",
"(",
"channel",
".",
"contract",
".",
"getTxId",
"(",
")",
".",
"equals",
"(",
"contractHash",
")",
")",
"return",
"channel",
";",
"}",
"return",
"null",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Finds a channel with the given id and contract hash and returns it, or returns null. | [
"Finds",
"a",
"channel",
"with",
"the",
"given",
"id",
"and",
"contract",
"hash",
"and",
"returns",
"it",
"or",
"returns",
"null",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/StoredPaymentChannelClientStates.java#L169-L182 |
23,434 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/StoredPaymentChannelClientStates.java | StoredPaymentChannelClientStates.getAnnouncePeerGroup | private TransactionBroadcaster getAnnouncePeerGroup() {
try {
return announcePeerGroupFuture.get(MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
String err = "Transaction broadcaster not set";
log.error(err);
throw new RuntimeException(err, e);
}
} | java | private TransactionBroadcaster getAnnouncePeerGroup() {
try {
return announcePeerGroupFuture.get(MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
String err = "Transaction broadcaster not set";
log.error(err);
throw new RuntimeException(err, e);
}
} | [
"private",
"TransactionBroadcaster",
"getAnnouncePeerGroup",
"(",
")",
"{",
"try",
"{",
"return",
"announcePeerGroupFuture",
".",
"get",
"(",
"MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET",
",",
"TimeUnit",
".",
"SECONDS",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"TimeoutException",
"e",
")",
"{",
"String",
"err",
"=",
"\"Transaction broadcaster not set\"",
";",
"log",
".",
"error",
"(",
"err",
")",
";",
"throw",
"new",
"RuntimeException",
"(",
"err",
",",
"e",
")",
";",
"}",
"}"
] | If the peer group has not been set for MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET seconds, then
the programmer probably forgot to set it and we should throw exception. | [
"If",
"the",
"peer",
"group",
"has",
"not",
"been",
"set",
"for",
"MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET",
"seconds",
"then",
"the",
"programmer",
"probably",
"forgot",
"to",
"set",
"it",
"and",
"we",
"should",
"throw",
"exception",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/StoredPaymentChannelClientStates.java#L245-L257 |
23,435 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/WalletFiles.java | WalletFiles.saveNow | public void saveNow() throws IOException {
// Can be called by any thread. However the wallet is locked whilst saving, so we can have two saves in flight
// but they will serialize (using different temp files).
if (executor.isShutdown())
return;
Date lastBlockSeenTime = wallet.getLastBlockSeenTime();
log.info("Saving wallet; last seen block is height {}, date {}, hash {}", wallet.getLastBlockSeenHeight(),
lastBlockSeenTime != null ? Utils.dateTimeFormat(lastBlockSeenTime) : "unknown",
wallet.getLastBlockSeenHash());
saveNowInternal();
} | java | public void saveNow() throws IOException {
// Can be called by any thread. However the wallet is locked whilst saving, so we can have two saves in flight
// but they will serialize (using different temp files).
if (executor.isShutdown())
return;
Date lastBlockSeenTime = wallet.getLastBlockSeenTime();
log.info("Saving wallet; last seen block is height {}, date {}, hash {}", wallet.getLastBlockSeenHeight(),
lastBlockSeenTime != null ? Utils.dateTimeFormat(lastBlockSeenTime) : "unknown",
wallet.getLastBlockSeenHash());
saveNowInternal();
} | [
"public",
"void",
"saveNow",
"(",
")",
"throws",
"IOException",
"{",
"// Can be called by any thread. However the wallet is locked whilst saving, so we can have two saves in flight",
"// but they will serialize (using different temp files).",
"if",
"(",
"executor",
".",
"isShutdown",
"(",
")",
")",
"return",
";",
"Date",
"lastBlockSeenTime",
"=",
"wallet",
".",
"getLastBlockSeenTime",
"(",
")",
";",
"log",
".",
"info",
"(",
"\"Saving wallet; last seen block is height {}, date {}, hash {}\"",
",",
"wallet",
".",
"getLastBlockSeenHeight",
"(",
")",
",",
"lastBlockSeenTime",
"!=",
"null",
"?",
"Utils",
".",
"dateTimeFormat",
"(",
"lastBlockSeenTime",
")",
":",
"\"unknown\"",
",",
"wallet",
".",
"getLastBlockSeenHash",
"(",
")",
")",
";",
"saveNowInternal",
"(",
")",
";",
"}"
] | Actually write the wallet file to disk, using an atomic rename when possible. Runs on the current thread. | [
"Actually",
"write",
"the",
"wallet",
"file",
"to",
"disk",
"using",
"an",
"atomic",
"rename",
"when",
"possible",
".",
"Runs",
"on",
"the",
"current",
"thread",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/WalletFiles.java#L118-L128 |
23,436 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/WalletFiles.java | WalletFiles.saveLater | public void saveLater() {
if (executor.isShutdown() || savePending.getAndSet(true))
return; // Already pending.
executor.schedule(saver, delay, delayTimeUnit);
} | java | public void saveLater() {
if (executor.isShutdown() || savePending.getAndSet(true))
return; // Already pending.
executor.schedule(saver, delay, delayTimeUnit);
} | [
"public",
"void",
"saveLater",
"(",
")",
"{",
"if",
"(",
"executor",
".",
"isShutdown",
"(",
")",
"||",
"savePending",
".",
"getAndSet",
"(",
"true",
")",
")",
"return",
";",
"// Already pending.",
"executor",
".",
"schedule",
"(",
"saver",
",",
"delay",
",",
"delayTimeUnit",
")",
";",
"}"
] | Queues up a save in the background. Useful for not very important wallet changes. | [
"Queues",
"up",
"a",
"save",
"in",
"the",
"background",
".",
"Useful",
"for",
"not",
"very",
"important",
"wallet",
"changes",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/WalletFiles.java#L145-L149 |
23,437 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/WalletFiles.java | WalletFiles.shutdownAndWait | public void shutdownAndWait() {
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); // forever
} catch (InterruptedException x) {
throw new RuntimeException(x);
}
} | java | public void shutdownAndWait() {
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); // forever
} catch (InterruptedException x) {
throw new RuntimeException(x);
}
} | [
"public",
"void",
"shutdownAndWait",
"(",
")",
"{",
"executor",
".",
"shutdown",
"(",
")",
";",
"try",
"{",
"executor",
".",
"awaitTermination",
"(",
"Long",
".",
"MAX_VALUE",
",",
"TimeUnit",
".",
"DAYS",
")",
";",
"// forever",
"}",
"catch",
"(",
"InterruptedException",
"x",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"x",
")",
";",
"}",
"}"
] | Shut down auto-saving. | [
"Shut",
"down",
"auto",
"-",
"saving",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/WalletFiles.java#L152-L159 |
23,438 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java | KeyChainGroup.createBasic | public static KeyChainGroup createBasic(NetworkParameters params) {
return new KeyChainGroup(params, new BasicKeyChain(), null, -1, -1, null, null);
} | java | public static KeyChainGroup createBasic(NetworkParameters params) {
return new KeyChainGroup(params, new BasicKeyChain(), null, -1, -1, null, null);
} | [
"public",
"static",
"KeyChainGroup",
"createBasic",
"(",
"NetworkParameters",
"params",
")",
"{",
"return",
"new",
"KeyChainGroup",
"(",
"params",
",",
"new",
"BasicKeyChain",
"(",
")",
",",
"null",
",",
"-",
"1",
",",
"-",
"1",
",",
"null",
",",
"null",
")",
";",
"}"
] | Creates a keychain group with just a basic chain. No deterministic chains will be created automatically. | [
"Creates",
"a",
"keychain",
"group",
"with",
"just",
"a",
"basic",
"chain",
".",
"No",
"deterministic",
"chains",
"will",
"be",
"created",
"automatically",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java#L198-L200 |
23,439 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java | KeyChainGroup.mergeActiveKeyChains | public final void mergeActiveKeyChains(KeyChainGroup from, long keyRotationTimeSecs) {
checkArgument(isEncrypted() == from.isEncrypted(), "encrypted and non-encrypted keychains cannot be mixed");
for (DeterministicKeyChain chain : from.getActiveKeyChains(keyRotationTimeSecs))
addAndActivateHDChain(chain);
} | java | public final void mergeActiveKeyChains(KeyChainGroup from, long keyRotationTimeSecs) {
checkArgument(isEncrypted() == from.isEncrypted(), "encrypted and non-encrypted keychains cannot be mixed");
for (DeterministicKeyChain chain : from.getActiveKeyChains(keyRotationTimeSecs))
addAndActivateHDChain(chain);
} | [
"public",
"final",
"void",
"mergeActiveKeyChains",
"(",
"KeyChainGroup",
"from",
",",
"long",
"keyRotationTimeSecs",
")",
"{",
"checkArgument",
"(",
"isEncrypted",
"(",
")",
"==",
"from",
".",
"isEncrypted",
"(",
")",
",",
"\"encrypted and non-encrypted keychains cannot be mixed\"",
")",
";",
"for",
"(",
"DeterministicKeyChain",
"chain",
":",
"from",
".",
"getActiveKeyChains",
"(",
"keyRotationTimeSecs",
")",
")",
"addAndActivateHDChain",
"(",
"chain",
")",
";",
"}"
] | Merge all active chains from the given keychain group into this keychain group. | [
"Merge",
"all",
"active",
"chains",
"from",
"the",
"given",
"keychain",
"group",
"into",
"this",
"keychain",
"group",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java#L435-L439 |
23,440 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java | KeyChainGroup.importKeysAndEncrypt | public int importKeysAndEncrypt(final List<ECKey> keys, KeyParameter aesKey) {
// TODO: Firstly check if the aes key can decrypt any of the existing keys successfully.
checkState(keyCrypter != null, "Not encrypted");
LinkedList<ECKey> encryptedKeys = Lists.newLinkedList();
for (ECKey key : keys) {
if (key.isEncrypted())
throw new IllegalArgumentException("Cannot provide already encrypted keys");
encryptedKeys.add(key.encrypt(keyCrypter, aesKey));
}
return importKeys(encryptedKeys);
} | java | public int importKeysAndEncrypt(final List<ECKey> keys, KeyParameter aesKey) {
// TODO: Firstly check if the aes key can decrypt any of the existing keys successfully.
checkState(keyCrypter != null, "Not encrypted");
LinkedList<ECKey> encryptedKeys = Lists.newLinkedList();
for (ECKey key : keys) {
if (key.isEncrypted())
throw new IllegalArgumentException("Cannot provide already encrypted keys");
encryptedKeys.add(key.encrypt(keyCrypter, aesKey));
}
return importKeys(encryptedKeys);
} | [
"public",
"int",
"importKeysAndEncrypt",
"(",
"final",
"List",
"<",
"ECKey",
">",
"keys",
",",
"KeyParameter",
"aesKey",
")",
"{",
"// TODO: Firstly check if the aes key can decrypt any of the existing keys successfully.",
"checkState",
"(",
"keyCrypter",
"!=",
"null",
",",
"\"Not encrypted\"",
")",
";",
"LinkedList",
"<",
"ECKey",
">",
"encryptedKeys",
"=",
"Lists",
".",
"newLinkedList",
"(",
")",
";",
"for",
"(",
"ECKey",
"key",
":",
"keys",
")",
"{",
"if",
"(",
"key",
".",
"isEncrypted",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Cannot provide already encrypted keys\"",
")",
";",
"encryptedKeys",
".",
"add",
"(",
"key",
".",
"encrypt",
"(",
"keyCrypter",
",",
"aesKey",
")",
")",
";",
"}",
"return",
"importKeys",
"(",
"encryptedKeys",
")",
";",
"}"
] | Imports the given unencrypted keys into the basic chain, encrypting them along the way with the given key. | [
"Imports",
"the",
"given",
"unencrypted",
"keys",
"into",
"the",
"basic",
"chain",
"encrypting",
"them",
"along",
"the",
"way",
"with",
"the",
"given",
"key",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java#L490-L500 |
23,441 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java | KeyChainGroup.maybeMarkCurrentAddressAsUsed | private void maybeMarkCurrentAddressAsUsed(LegacyAddress address) {
checkArgument(address.getOutputScriptType() == ScriptType.P2SH);
for (Map.Entry<KeyChain.KeyPurpose, Address> entry : currentAddresses.entrySet()) {
if (entry.getValue() != null && entry.getValue().equals(address)) {
log.info("Marking P2SH address as used: {}", address);
currentAddresses.put(entry.getKey(), freshAddress(entry.getKey()));
return;
}
}
} | java | private void maybeMarkCurrentAddressAsUsed(LegacyAddress address) {
checkArgument(address.getOutputScriptType() == ScriptType.P2SH);
for (Map.Entry<KeyChain.KeyPurpose, Address> entry : currentAddresses.entrySet()) {
if (entry.getValue() != null && entry.getValue().equals(address)) {
log.info("Marking P2SH address as used: {}", address);
currentAddresses.put(entry.getKey(), freshAddress(entry.getKey()));
return;
}
}
} | [
"private",
"void",
"maybeMarkCurrentAddressAsUsed",
"(",
"LegacyAddress",
"address",
")",
"{",
"checkArgument",
"(",
"address",
".",
"getOutputScriptType",
"(",
")",
"==",
"ScriptType",
".",
"P2SH",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"KeyChain",
".",
"KeyPurpose",
",",
"Address",
">",
"entry",
":",
"currentAddresses",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"entry",
".",
"getValue",
"(",
")",
"!=",
"null",
"&&",
"entry",
".",
"getValue",
"(",
")",
".",
"equals",
"(",
"address",
")",
")",
"{",
"log",
".",
"info",
"(",
"\"Marking P2SH address as used: {}\"",
",",
"address",
")",
";",
"currentAddresses",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"freshAddress",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
")",
";",
"return",
";",
"}",
"}",
"}"
] | If the given P2SH address is "current", advance it to a new one. | [
"If",
"the",
"given",
"P2SH",
"address",
"is",
"current",
"advance",
"it",
"to",
"a",
"new",
"one",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java#L568-L577 |
23,442 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java | KeyChainGroup.maybeMarkCurrentKeyAsUsed | private void maybeMarkCurrentKeyAsUsed(DeterministicKey key) {
// It's OK for currentKeys to be empty here: it means we're a married wallet and the key may be a part of a
// rotating chain.
for (Map.Entry<KeyChain.KeyPurpose, DeterministicKey> entry : currentKeys.entrySet()) {
if (entry.getValue() != null && entry.getValue().equals(key)) {
log.info("Marking key as used: {}", key);
currentKeys.put(entry.getKey(), freshKey(entry.getKey()));
return;
}
}
} | java | private void maybeMarkCurrentKeyAsUsed(DeterministicKey key) {
// It's OK for currentKeys to be empty here: it means we're a married wallet and the key may be a part of a
// rotating chain.
for (Map.Entry<KeyChain.KeyPurpose, DeterministicKey> entry : currentKeys.entrySet()) {
if (entry.getValue() != null && entry.getValue().equals(key)) {
log.info("Marking key as used: {}", key);
currentKeys.put(entry.getKey(), freshKey(entry.getKey()));
return;
}
}
} | [
"private",
"void",
"maybeMarkCurrentKeyAsUsed",
"(",
"DeterministicKey",
"key",
")",
"{",
"// It's OK for currentKeys to be empty here: it means we're a married wallet and the key may be a part of a",
"// rotating chain.",
"for",
"(",
"Map",
".",
"Entry",
"<",
"KeyChain",
".",
"KeyPurpose",
",",
"DeterministicKey",
">",
"entry",
":",
"currentKeys",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"entry",
".",
"getValue",
"(",
")",
"!=",
"null",
"&&",
"entry",
".",
"getValue",
"(",
")",
".",
"equals",
"(",
"key",
")",
")",
"{",
"log",
".",
"info",
"(",
"\"Marking key as used: {}\"",
",",
"key",
")",
";",
"currentKeys",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"freshKey",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
")",
";",
"return",
";",
"}",
"}",
"}"
] | If the given key is "current", advance the current key to a new one. | [
"If",
"the",
"given",
"key",
"is",
"current",
"advance",
"the",
"current",
"key",
"to",
"a",
"new",
"one",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java#L580-L590 |
23,443 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java | KeyChainGroup.numKeys | public int numKeys() {
int result = basic.numKeys();
if (chains != null)
for (DeterministicKeyChain chain : chains)
result += chain.numKeys();
return result;
} | java | public int numKeys() {
int result = basic.numKeys();
if (chains != null)
for (DeterministicKeyChain chain : chains)
result += chain.numKeys();
return result;
} | [
"public",
"int",
"numKeys",
"(",
")",
"{",
"int",
"result",
"=",
"basic",
".",
"numKeys",
"(",
")",
";",
"if",
"(",
"chains",
"!=",
"null",
")",
"for",
"(",
"DeterministicKeyChain",
"chain",
":",
"chains",
")",
"result",
"+=",
"chain",
".",
"numKeys",
"(",
")",
";",
"return",
"result",
";",
"}"
] | Returns the number of keys managed by this group, including the lookahead buffers. | [
"Returns",
"the",
"number",
"of",
"keys",
"managed",
"by",
"this",
"group",
"including",
"the",
"lookahead",
"buffers",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java#L632-L638 |
23,444 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java | KeyChainGroup.removeImportedKey | public boolean removeImportedKey(ECKey key) {
checkNotNull(key);
checkArgument(!(key instanceof DeterministicKey));
return basic.removeKey(key);
} | java | public boolean removeImportedKey(ECKey key) {
checkNotNull(key);
checkArgument(!(key instanceof DeterministicKey));
return basic.removeKey(key);
} | [
"public",
"boolean",
"removeImportedKey",
"(",
"ECKey",
"key",
")",
"{",
"checkNotNull",
"(",
"key",
")",
";",
"checkArgument",
"(",
"!",
"(",
"key",
"instanceof",
"DeterministicKey",
")",
")",
";",
"return",
"basic",
".",
"removeKey",
"(",
"key",
")",
";",
"}"
] | Removes a key that was imported into the basic key chain. You cannot remove deterministic keys.
@throws java.lang.IllegalArgumentException if the key is deterministic. | [
"Removes",
"a",
"key",
"that",
"was",
"imported",
"into",
"the",
"basic",
"key",
"chain",
".",
"You",
"cannot",
"remove",
"deterministic",
"keys",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/KeyChainGroup.java#L644-L648 |
23,445 | bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/WalletPasswordController.java | WalletPasswordController.setTargetTime | public static void setTargetTime(Duration targetTime) {
ByteString bytes = ByteString.copyFrom(Longs.toByteArray(targetTime.toMillis()));
Main.bitcoin.wallet().setTag(TAG, bytes);
} | java | public static void setTargetTime(Duration targetTime) {
ByteString bytes = ByteString.copyFrom(Longs.toByteArray(targetTime.toMillis()));
Main.bitcoin.wallet().setTag(TAG, bytes);
} | [
"public",
"static",
"void",
"setTargetTime",
"(",
"Duration",
"targetTime",
")",
"{",
"ByteString",
"bytes",
"=",
"ByteString",
".",
"copyFrom",
"(",
"Longs",
".",
"toByteArray",
"(",
"targetTime",
".",
"toMillis",
"(",
")",
")",
")",
";",
"Main",
".",
"bitcoin",
".",
"wallet",
"(",
")",
".",
"setTag",
"(",
"TAG",
",",
"bytes",
")",
";",
"}"
] | Writes the given time to the wallet as a tag so we can find it again in this class. | [
"Writes",
"the",
"given",
"time",
"to",
"the",
"wallet",
"as",
"a",
"tag",
"so",
"we",
"can",
"find",
"it",
"again",
"in",
"this",
"class",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/WalletPasswordController.java#L114-L117 |
23,446 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/DeterministicKey.java | DeterministicKey.ascertainParentFingerprint | private int ascertainParentFingerprint(DeterministicKey parentKey, int parentFingerprint)
throws IllegalArgumentException {
if (parentFingerprint != 0) {
if (parent != null)
checkArgument(parent.getFingerprint() == parentFingerprint,
"parent fingerprint mismatch",
Integer.toHexString(parent.getFingerprint()), Integer.toHexString(parentFingerprint));
return parentFingerprint;
} else return 0;
} | java | private int ascertainParentFingerprint(DeterministicKey parentKey, int parentFingerprint)
throws IllegalArgumentException {
if (parentFingerprint != 0) {
if (parent != null)
checkArgument(parent.getFingerprint() == parentFingerprint,
"parent fingerprint mismatch",
Integer.toHexString(parent.getFingerprint()), Integer.toHexString(parentFingerprint));
return parentFingerprint;
} else return 0;
} | [
"private",
"int",
"ascertainParentFingerprint",
"(",
"DeterministicKey",
"parentKey",
",",
"int",
"parentFingerprint",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"parentFingerprint",
"!=",
"0",
")",
"{",
"if",
"(",
"parent",
"!=",
"null",
")",
"checkArgument",
"(",
"parent",
".",
"getFingerprint",
"(",
")",
"==",
"parentFingerprint",
",",
"\"parent fingerprint mismatch\"",
",",
"Integer",
".",
"toHexString",
"(",
"parent",
".",
"getFingerprint",
"(",
")",
")",
",",
"Integer",
".",
"toHexString",
"(",
"parentFingerprint",
")",
")",
";",
"return",
"parentFingerprint",
";",
"}",
"else",
"return",
"0",
";",
"}"
] | 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. | [
"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",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/DeterministicKey.java#L118-L127 |
23,447 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/DeterministicKey.java | DeterministicKey.getPrivKeyBytes33 | public byte[] getPrivKeyBytes33() {
byte[] bytes33 = new byte[33];
byte[] priv = getPrivKeyBytes();
System.arraycopy(priv, 0, bytes33, 33 - priv.length, priv.length);
return bytes33;
} | java | public byte[] getPrivKeyBytes33() {
byte[] bytes33 = new byte[33];
byte[] priv = getPrivKeyBytes();
System.arraycopy(priv, 0, bytes33, 33 - priv.length, priv.length);
return bytes33;
} | [
"public",
"byte",
"[",
"]",
"getPrivKeyBytes33",
"(",
")",
"{",
"byte",
"[",
"]",
"bytes33",
"=",
"new",
"byte",
"[",
"33",
"]",
";",
"byte",
"[",
"]",
"priv",
"=",
"getPrivKeyBytes",
"(",
")",
";",
"System",
".",
"arraycopy",
"(",
"priv",
",",
"0",
",",
"bytes33",
",",
"33",
"-",
"priv",
".",
"length",
",",
"priv",
".",
"length",
")",
";",
"return",
"bytes33",
";",
"}"
] | Returns private key bytes, padded with zeros to 33 bytes.
@throws java.lang.IllegalStateException if the private key bytes are missing. | [
"Returns",
"private",
"key",
"bytes",
"padded",
"with",
"zeros",
"to",
"33",
"bytes",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/DeterministicKey.java#L248-L253 |
23,448 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/DeterministicKey.java | DeterministicKey.findOrDeriveEncryptedPrivateKey | private BigInteger findOrDeriveEncryptedPrivateKey(KeyCrypter keyCrypter, KeyParameter 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 new BigInteger(1, 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);
} | java | private BigInteger findOrDeriveEncryptedPrivateKey(KeyCrypter keyCrypter, KeyParameter 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 new BigInteger(1, 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",
"BigInteger",
"findOrDeriveEncryptedPrivateKey",
"(",
"KeyCrypter",
"keyCrypter",
",",
"KeyParameter",
"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",
"new",
"BigInteger",
"(",
"1",
",",
"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",
")",
";",
"}"
] | to decrypt and re-derive. | [
"to",
"decrypt",
"and",
"re",
"-",
"derive",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/DeterministicKey.java#L393-L415 |
23,449 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/DeterministicKey.java | DeterministicKey.getPrivKey | @Override
public BigInteger getPrivKey() {
final BigInteger key = findOrDerivePrivateKey();
checkState(key != null, "Private key bytes not available");
return key;
} | java | @Override
public BigInteger getPrivKey() {
final BigInteger key = findOrDerivePrivateKey();
checkState(key != null, "Private key bytes not available");
return key;
} | [
"@",
"Override",
"public",
"BigInteger",
"getPrivKey",
"(",
")",
"{",
"final",
"BigInteger",
"key",
"=",
"findOrDerivePrivateKey",
"(",
")",
";",
"checkState",
"(",
"key",
"!=",
"null",
",",
"\"Private key bytes not available\"",
")",
";",
"return",
"key",
";",
"}"
] | 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. | [
"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",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/DeterministicKey.java#L465-L470 |
23,450 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/DeterministicKey.java | DeterministicKey.deserializeB58 | public static DeterministicKey deserializeB58(String base58, NetworkParameters params) {
return deserializeB58(null, base58, params);
} | java | public static DeterministicKey deserializeB58(String base58, NetworkParameters params) {
return deserializeB58(null, base58, params);
} | [
"public",
"static",
"DeterministicKey",
"deserializeB58",
"(",
"String",
"base58",
",",
"NetworkParameters",
"params",
")",
"{",
"return",
"deserializeB58",
"(",
"null",
",",
"base58",
",",
"params",
")",
";",
"}"
] | Deserialize a base-58-encoded HD Key with no parent | [
"Deserialize",
"a",
"base",
"-",
"58",
"-",
"encoded",
"HD",
"Key",
"with",
"no",
"parent"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/DeterministicKey.java#L520-L522 |
23,451 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BlockFileLoader.java | BlockFileLoader.getReferenceClientBlockFileList | public static List<File> getReferenceClientBlockFileList(File blocksDir) {
checkArgument(blocksDir.isDirectory(), "%s is not a directory", blocksDir);
List<File> list = new LinkedList<>();
for (int i = 0; true; i++) {
File file = new File(blocksDir, String.format(Locale.US, "blk%05d.dat", i));
if (!file.exists())
break;
list.add(file);
}
return list;
} | java | public static List<File> getReferenceClientBlockFileList(File blocksDir) {
checkArgument(blocksDir.isDirectory(), "%s is not a directory", blocksDir);
List<File> list = new LinkedList<>();
for (int i = 0; true; i++) {
File file = new File(blocksDir, String.format(Locale.US, "blk%05d.dat", i));
if (!file.exists())
break;
list.add(file);
}
return list;
} | [
"public",
"static",
"List",
"<",
"File",
">",
"getReferenceClientBlockFileList",
"(",
"File",
"blocksDir",
")",
"{",
"checkArgument",
"(",
"blocksDir",
".",
"isDirectory",
"(",
")",
",",
"\"%s is not a directory\"",
",",
"blocksDir",
")",
";",
"List",
"<",
"File",
">",
"list",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"true",
";",
"i",
"++",
")",
"{",
"File",
"file",
"=",
"new",
"File",
"(",
"blocksDir",
",",
"String",
".",
"format",
"(",
"Locale",
".",
"US",
",",
"\"blk%05d.dat\"",
",",
"i",
")",
")",
";",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"break",
";",
"list",
".",
"add",
"(",
"file",
")",
";",
"}",
"return",
"list",
";",
"}"
] | Gets the list of files which contain blocks from Bitcoin Core. | [
"Gets",
"the",
"list",
"of",
"files",
"which",
"contain",
"blocks",
"from",
"Bitcoin",
"Core",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BlockFileLoader.java#L57-L67 |
23,452 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/StateMachine.java | StateMachine.checkState | public synchronized void checkState(State requiredState) throws IllegalStateException {
if (requiredState != currentState) {
throw new IllegalStateException(String.format(Locale.US,
"Expected state %s, but in state %s", requiredState, currentState));
}
} | java | public synchronized void checkState(State requiredState) throws IllegalStateException {
if (requiredState != currentState) {
throw new IllegalStateException(String.format(Locale.US,
"Expected state %s, but in state %s", requiredState, currentState));
}
} | [
"public",
"synchronized",
"void",
"checkState",
"(",
"State",
"requiredState",
")",
"throws",
"IllegalStateException",
"{",
"if",
"(",
"requiredState",
"!=",
"currentState",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"String",
".",
"format",
"(",
"Locale",
".",
"US",
",",
"\"Expected state %s, but in state %s\"",
",",
"requiredState",
",",
"currentState",
")",
")",
";",
"}",
"}"
] | Checks that the machine is in the given state. Throws if it isn't.
@param requiredState | [
"Checks",
"that",
"the",
"machine",
"is",
"in",
"the",
"given",
"state",
".",
"Throws",
"if",
"it",
"isn",
"t",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/StateMachine.java#L44-L49 |
23,453 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/StateMachine.java | StateMachine.checkState | public synchronized void checkState(State... requiredStates) throws IllegalStateException {
for (State requiredState : requiredStates) {
if (requiredState.equals(currentState)) {
return;
}
}
throw new IllegalStateException(String.format(Locale.US,
"Expected states %s, but in state %s", Lists.newArrayList(requiredStates), currentState));
} | java | public synchronized void checkState(State... requiredStates) throws IllegalStateException {
for (State requiredState : requiredStates) {
if (requiredState.equals(currentState)) {
return;
}
}
throw new IllegalStateException(String.format(Locale.US,
"Expected states %s, but in state %s", Lists.newArrayList(requiredStates), currentState));
} | [
"public",
"synchronized",
"void",
"checkState",
"(",
"State",
"...",
"requiredStates",
")",
"throws",
"IllegalStateException",
"{",
"for",
"(",
"State",
"requiredState",
":",
"requiredStates",
")",
"{",
"if",
"(",
"requiredState",
".",
"equals",
"(",
"currentState",
")",
")",
"{",
"return",
";",
"}",
"}",
"throw",
"new",
"IllegalStateException",
"(",
"String",
".",
"format",
"(",
"Locale",
".",
"US",
",",
"\"Expected states %s, but in state %s\"",
",",
"Lists",
".",
"newArrayList",
"(",
"requiredStates",
")",
",",
"currentState",
")",
")",
";",
"}"
] | Checks that the machine is in one of the given states. Throws if it isn't.
@param requiredStates | [
"Checks",
"that",
"the",
"machine",
"is",
"in",
"one",
"of",
"the",
"given",
"states",
".",
"Throws",
"if",
"it",
"isn",
"t",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/StateMachine.java#L55-L63 |
23,454 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/StateMachine.java | StateMachine.transition | public synchronized void transition(State newState) throws IllegalStateException {
if (transitions.containsEntry(currentState, newState)) {
currentState = newState;
} else {
throw new IllegalStateException(String.format(Locale.US,
"Attempted invalid transition from %s to %s", currentState, newState));
}
} | java | public synchronized void transition(State newState) throws IllegalStateException {
if (transitions.containsEntry(currentState, newState)) {
currentState = newState;
} else {
throw new IllegalStateException(String.format(Locale.US,
"Attempted invalid transition from %s to %s", currentState, newState));
}
} | [
"public",
"synchronized",
"void",
"transition",
"(",
"State",
"newState",
")",
"throws",
"IllegalStateException",
"{",
"if",
"(",
"transitions",
".",
"containsEntry",
"(",
"currentState",
",",
"newState",
")",
")",
"{",
"currentState",
"=",
"newState",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"String",
".",
"format",
"(",
"Locale",
".",
"US",
",",
"\"Attempted invalid transition from %s to %s\"",
",",
"currentState",
",",
"newState",
")",
")",
";",
"}",
"}"
] | Transitions to a new state, provided that the required transition exists
@param newState
@throws IllegalStateException If no state transition exists from oldState to newState | [
"Transitions",
"to",
"a",
"new",
"state",
"provided",
"that",
"the",
"required",
"transition",
"exists"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/StateMachine.java#L70-L77 |
23,455 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/BloomFilter.java | BloomFilter.getFalsePositiveRate | public double getFalsePositiveRate(int elements) {
return pow(1 - pow(E, -1.0 * (hashFuncs * elements) / (data.length * 8)), hashFuncs);
} | java | public double getFalsePositiveRate(int elements) {
return pow(1 - pow(E, -1.0 * (hashFuncs * elements) / (data.length * 8)), hashFuncs);
} | [
"public",
"double",
"getFalsePositiveRate",
"(",
"int",
"elements",
")",
"{",
"return",
"pow",
"(",
"1",
"-",
"pow",
"(",
"E",
",",
"-",
"1.0",
"*",
"(",
"hashFuncs",
"*",
"elements",
")",
"/",
"(",
"data",
".",
"length",
"*",
"8",
")",
")",
",",
"hashFuncs",
")",
";",
"}"
] | Returns the theoretical false positive rate of this filter if were to contain the given number of elements. | [
"Returns",
"the",
"theoretical",
"false",
"positive",
"rate",
"of",
"this",
"filter",
"if",
"were",
"to",
"contain",
"the",
"given",
"number",
"of",
"elements",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BloomFilter.java#L129-L131 |
23,456 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/BloomFilter.java | BloomFilter.contains | public synchronized boolean contains(byte[] object) {
for (int i = 0; i < hashFuncs; i++) {
if (!Utils.checkBitLE(data, murmurHash3(data, nTweak, i, object)))
return false;
}
return true;
} | java | public synchronized boolean contains(byte[] object) {
for (int i = 0; i < hashFuncs; i++) {
if (!Utils.checkBitLE(data, murmurHash3(data, nTweak, i, object)))
return false;
}
return true;
} | [
"public",
"synchronized",
"boolean",
"contains",
"(",
"byte",
"[",
"]",
"object",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"hashFuncs",
";",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"Utils",
".",
"checkBitLE",
"(",
"data",
",",
"murmurHash3",
"(",
"data",
",",
"nTweak",
",",
"i",
",",
"object",
")",
")",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Returns true if the given object matches the filter either because it was inserted, or because we have a
false-positive. | [
"Returns",
"true",
"if",
"the",
"given",
"object",
"matches",
"the",
"filter",
"either",
"because",
"it",
"was",
"inserted",
"or",
"because",
"we",
"have",
"a",
"false",
"-",
"positive",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BloomFilter.java#L230-L236 |
23,457 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/BloomFilter.java | BloomFilter.insert | public synchronized void insert(byte[] object) {
for (int i = 0; i < hashFuncs; i++)
Utils.setBitLE(data, murmurHash3(data, nTweak, i, object));
} | java | public synchronized void insert(byte[] object) {
for (int i = 0; i < hashFuncs; i++)
Utils.setBitLE(data, murmurHash3(data, nTweak, i, object));
} | [
"public",
"synchronized",
"void",
"insert",
"(",
"byte",
"[",
"]",
"object",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"hashFuncs",
";",
"i",
"++",
")",
"Utils",
".",
"setBitLE",
"(",
"data",
",",
"murmurHash3",
"(",
"data",
",",
"nTweak",
",",
"i",
",",
"object",
")",
")",
";",
"}"
] | Insert the given arbitrary data into the filter | [
"Insert",
"the",
"given",
"arbitrary",
"data",
"into",
"the",
"filter"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BloomFilter.java#L239-L242 |
23,458 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/BloomFilter.java | BloomFilter.merge | public synchronized void merge(BloomFilter filter) {
if (!this.matchesAll() && !filter.matchesAll()) {
checkArgument(filter.data.length == this.data.length &&
filter.hashFuncs == this.hashFuncs &&
filter.nTweak == this.nTweak);
for (int i = 0; i < data.length; i++)
this.data[i] |= filter.data[i];
} else {
this.data = new byte[] {(byte) 0xff};
}
} | java | public synchronized void merge(BloomFilter filter) {
if (!this.matchesAll() && !filter.matchesAll()) {
checkArgument(filter.data.length == this.data.length &&
filter.hashFuncs == this.hashFuncs &&
filter.nTweak == this.nTweak);
for (int i = 0; i < data.length; i++)
this.data[i] |= filter.data[i];
} else {
this.data = new byte[] {(byte) 0xff};
}
} | [
"public",
"synchronized",
"void",
"merge",
"(",
"BloomFilter",
"filter",
")",
"{",
"if",
"(",
"!",
"this",
".",
"matchesAll",
"(",
")",
"&&",
"!",
"filter",
".",
"matchesAll",
"(",
")",
")",
"{",
"checkArgument",
"(",
"filter",
".",
"data",
".",
"length",
"==",
"this",
".",
"data",
".",
"length",
"&&",
"filter",
".",
"hashFuncs",
"==",
"this",
".",
"hashFuncs",
"&&",
"filter",
".",
"nTweak",
"==",
"this",
".",
"nTweak",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"length",
";",
"i",
"++",
")",
"this",
".",
"data",
"[",
"i",
"]",
"|=",
"filter",
".",
"data",
"[",
"i",
"]",
";",
"}",
"else",
"{",
"this",
".",
"data",
"=",
"new",
"byte",
"[",
"]",
"{",
"(",
"byte",
")",
"0xff",
"}",
";",
"}",
"}"
] | Copies filter into this. Filter must have the same size, hash function count and nTweak or an
IllegalArgumentException will be thrown. | [
"Copies",
"filter",
"into",
"this",
".",
"Filter",
"must",
"have",
"the",
"same",
"size",
"hash",
"function",
"count",
"and",
"nTweak",
"or",
"an",
"IllegalArgumentException",
"will",
"be",
"thrown",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BloomFilter.java#L270-L280 |
23,459 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/BloomFilter.java | BloomFilter.getUpdateFlag | public synchronized BloomUpdate getUpdateFlag() {
if (nFlags == 0)
return BloomUpdate.UPDATE_NONE;
else if (nFlags == 1)
return BloomUpdate.UPDATE_ALL;
else if (nFlags == 2)
return BloomUpdate.UPDATE_P2PUBKEY_ONLY;
else
throw new IllegalStateException("Unknown flag combination");
} | java | public synchronized BloomUpdate getUpdateFlag() {
if (nFlags == 0)
return BloomUpdate.UPDATE_NONE;
else if (nFlags == 1)
return BloomUpdate.UPDATE_ALL;
else if (nFlags == 2)
return BloomUpdate.UPDATE_P2PUBKEY_ONLY;
else
throw new IllegalStateException("Unknown flag combination");
} | [
"public",
"synchronized",
"BloomUpdate",
"getUpdateFlag",
"(",
")",
"{",
"if",
"(",
"nFlags",
"==",
"0",
")",
"return",
"BloomUpdate",
".",
"UPDATE_NONE",
";",
"else",
"if",
"(",
"nFlags",
"==",
"1",
")",
"return",
"BloomUpdate",
".",
"UPDATE_ALL",
";",
"else",
"if",
"(",
"nFlags",
"==",
"2",
")",
"return",
"BloomUpdate",
".",
"UPDATE_P2PUBKEY_ONLY",
";",
"else",
"throw",
"new",
"IllegalStateException",
"(",
"\"Unknown flag combination\"",
")",
";",
"}"
] | The update flag controls how application of the filter to a block modifies the filter. See the enum javadocs
for information on what occurs and when. | [
"The",
"update",
"flag",
"controls",
"how",
"application",
"of",
"the",
"filter",
"to",
"a",
"block",
"modifies",
"the",
"filter",
".",
"See",
"the",
"enum",
"javadocs",
"for",
"information",
"on",
"what",
"occurs",
"and",
"when",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BloomFilter.java#L297-L306 |
23,460 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/BloomFilter.java | BloomFilter.applyAndUpdate | public synchronized FilteredBlock applyAndUpdate(Block block) {
List<Transaction> txns = block.getTransactions();
List<Sha256Hash> txHashes = new ArrayList<>(txns.size());
List<Transaction> matched = Lists.newArrayList();
byte[] bits = new byte[(int) Math.ceil(txns.size() / 8.0)];
for (int i = 0; i < txns.size(); i++) {
Transaction tx = txns.get(i);
txHashes.add(tx.getTxId());
if (applyAndUpdate(tx)) {
Utils.setBitLE(bits, i);
matched.add(tx);
}
}
PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(block.getParams(), bits, txHashes);
FilteredBlock filteredBlock = new FilteredBlock(block.getParams(), block.cloneAsHeader(), pmt);
for (Transaction transaction : matched)
filteredBlock.provideTransaction(transaction);
return filteredBlock;
} | java | public synchronized FilteredBlock applyAndUpdate(Block block) {
List<Transaction> txns = block.getTransactions();
List<Sha256Hash> txHashes = new ArrayList<>(txns.size());
List<Transaction> matched = Lists.newArrayList();
byte[] bits = new byte[(int) Math.ceil(txns.size() / 8.0)];
for (int i = 0; i < txns.size(); i++) {
Transaction tx = txns.get(i);
txHashes.add(tx.getTxId());
if (applyAndUpdate(tx)) {
Utils.setBitLE(bits, i);
matched.add(tx);
}
}
PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(block.getParams(), bits, txHashes);
FilteredBlock filteredBlock = new FilteredBlock(block.getParams(), block.cloneAsHeader(), pmt);
for (Transaction transaction : matched)
filteredBlock.provideTransaction(transaction);
return filteredBlock;
} | [
"public",
"synchronized",
"FilteredBlock",
"applyAndUpdate",
"(",
"Block",
"block",
")",
"{",
"List",
"<",
"Transaction",
">",
"txns",
"=",
"block",
".",
"getTransactions",
"(",
")",
";",
"List",
"<",
"Sha256Hash",
">",
"txHashes",
"=",
"new",
"ArrayList",
"<>",
"(",
"txns",
".",
"size",
"(",
")",
")",
";",
"List",
"<",
"Transaction",
">",
"matched",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"byte",
"[",
"]",
"bits",
"=",
"new",
"byte",
"[",
"(",
"int",
")",
"Math",
".",
"ceil",
"(",
"txns",
".",
"size",
"(",
")",
"/",
"8.0",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"txns",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"Transaction",
"tx",
"=",
"txns",
".",
"get",
"(",
"i",
")",
";",
"txHashes",
".",
"add",
"(",
"tx",
".",
"getTxId",
"(",
")",
")",
";",
"if",
"(",
"applyAndUpdate",
"(",
"tx",
")",
")",
"{",
"Utils",
".",
"setBitLE",
"(",
"bits",
",",
"i",
")",
";",
"matched",
".",
"add",
"(",
"tx",
")",
";",
"}",
"}",
"PartialMerkleTree",
"pmt",
"=",
"PartialMerkleTree",
".",
"buildFromLeaves",
"(",
"block",
".",
"getParams",
"(",
")",
",",
"bits",
",",
"txHashes",
")",
";",
"FilteredBlock",
"filteredBlock",
"=",
"new",
"FilteredBlock",
"(",
"block",
".",
"getParams",
"(",
")",
",",
"block",
".",
"cloneAsHeader",
"(",
")",
",",
"pmt",
")",
";",
"for",
"(",
"Transaction",
"transaction",
":",
"matched",
")",
"filteredBlock",
".",
"provideTransaction",
"(",
"transaction",
")",
";",
"return",
"filteredBlock",
";",
"}"
] | Creates a new FilteredBlock from the given Block, using this filter to select transactions. Matches can cause the
filter to be updated with the matched element, this ensures that when a filter is applied to a block, spends of
matched transactions are also matched. However it means this filter can be mutated by the operation. The returned
filtered block already has the matched transactions associated with it. | [
"Creates",
"a",
"new",
"FilteredBlock",
"from",
"the",
"given",
"Block",
"using",
"this",
"filter",
"to",
"select",
"transactions",
".",
"Matches",
"can",
"cause",
"the",
"filter",
"to",
"be",
"updated",
"with",
"the",
"matched",
"element",
"this",
"ensures",
"that",
"when",
"a",
"filter",
"is",
"applied",
"to",
"a",
"block",
"spends",
"of",
"matched",
"transactions",
"are",
"also",
"matched",
".",
"However",
"it",
"means",
"this",
"filter",
"can",
"be",
"mutated",
"by",
"the",
"operation",
".",
"The",
"returned",
"filtered",
"block",
"already",
"has",
"the",
"matched",
"transactions",
"associated",
"with",
"it",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/BloomFilter.java#L314-L332 |
23,461 | bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/Main.java | Main.overlayUI | public <T> OverlayUI<T> overlayUI(String name) {
try {
checkGuiThread();
// Load the UI from disk.
URL location = GuiUtils.getResource(name);
FXMLLoader loader = new FXMLLoader(location);
Pane ui = loader.load();
T controller = loader.getController();
OverlayUI<T> pair = new OverlayUI<T>(ui, controller);
// Auto-magically set the overlayUI member, if it's there.
try {
if (controller != null)
controller.getClass().getField("overlayUI").set(controller, pair);
} catch (IllegalAccessException | NoSuchFieldException ignored) {
ignored.printStackTrace();
}
pair.show();
return pair;
} catch (IOException e) {
throw new RuntimeException(e); // Can't happen.
}
} | java | public <T> OverlayUI<T> overlayUI(String name) {
try {
checkGuiThread();
// Load the UI from disk.
URL location = GuiUtils.getResource(name);
FXMLLoader loader = new FXMLLoader(location);
Pane ui = loader.load();
T controller = loader.getController();
OverlayUI<T> pair = new OverlayUI<T>(ui, controller);
// Auto-magically set the overlayUI member, if it's there.
try {
if (controller != null)
controller.getClass().getField("overlayUI").set(controller, pair);
} catch (IllegalAccessException | NoSuchFieldException ignored) {
ignored.printStackTrace();
}
pair.show();
return pair;
} catch (IOException e) {
throw new RuntimeException(e); // Can't happen.
}
} | [
"public",
"<",
"T",
">",
"OverlayUI",
"<",
"T",
">",
"overlayUI",
"(",
"String",
"name",
")",
"{",
"try",
"{",
"checkGuiThread",
"(",
")",
";",
"// Load the UI from disk.",
"URL",
"location",
"=",
"GuiUtils",
".",
"getResource",
"(",
"name",
")",
";",
"FXMLLoader",
"loader",
"=",
"new",
"FXMLLoader",
"(",
"location",
")",
";",
"Pane",
"ui",
"=",
"loader",
".",
"load",
"(",
")",
";",
"T",
"controller",
"=",
"loader",
".",
"getController",
"(",
")",
";",
"OverlayUI",
"<",
"T",
">",
"pair",
"=",
"new",
"OverlayUI",
"<",
"T",
">",
"(",
"ui",
",",
"controller",
")",
";",
"// Auto-magically set the overlayUI member, if it's there.",
"try",
"{",
"if",
"(",
"controller",
"!=",
"null",
")",
"controller",
".",
"getClass",
"(",
")",
".",
"getField",
"(",
"\"overlayUI\"",
")",
".",
"set",
"(",
"controller",
",",
"pair",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"|",
"NoSuchFieldException",
"ignored",
")",
"{",
"ignored",
".",
"printStackTrace",
"(",
")",
";",
"}",
"pair",
".",
"show",
"(",
")",
";",
"return",
"pair",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"// Can't happen.",
"}",
"}"
] | Loads the FXML file with the given name, blurs out the main UI and puts this one on top. | [
"Loads",
"the",
"FXML",
"file",
"with",
"the",
"given",
"name",
"blurs",
"out",
"the",
"main",
"UI",
"and",
"puts",
"this",
"one",
"on",
"top",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/Main.java#L226-L247 |
23,462 | bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/utils/GuiUtils.java | GuiUtils.handleCrashesOnThisThread | public static void handleCrashesOnThisThread() {
Thread.currentThread().setUncaughtExceptionHandler((thread, exception) -> {
GuiUtils.crashAlert(Throwables.getRootCause(exception));
});
} | java | public static void handleCrashesOnThisThread() {
Thread.currentThread().setUncaughtExceptionHandler((thread, exception) -> {
GuiUtils.crashAlert(Throwables.getRootCause(exception));
});
} | [
"public",
"static",
"void",
"handleCrashesOnThisThread",
"(",
")",
"{",
"Thread",
".",
"currentThread",
"(",
")",
".",
"setUncaughtExceptionHandler",
"(",
"(",
"thread",
",",
"exception",
")",
"->",
"{",
"GuiUtils",
".",
"crashAlert",
"(",
"Throwables",
".",
"getRootCause",
"(",
"exception",
")",
")",
";",
"}",
")",
";",
"}"
] | Show a GUI alert box for any unhandled exceptions that propagate out of this thread. | [
"Show",
"a",
"GUI",
"alert",
"box",
"for",
"any",
"unhandled",
"exceptions",
"that",
"propagate",
"out",
"of",
"this",
"thread",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/utils/GuiUtils.java#L73-L77 |
23,463 | bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/utils/GuiUtils.java | GuiUtils.getResource | public static URL getResource(String name) {
if (false)
return unchecked(() -> new URL("file:///your/path/here/src/main/wallettemplate/" + name));
else
return MainController.class.getResource(name);
} | java | public static URL getResource(String name) {
if (false)
return unchecked(() -> new URL("file:///your/path/here/src/main/wallettemplate/" + name));
else
return MainController.class.getResource(name);
} | [
"public",
"static",
"URL",
"getResource",
"(",
"String",
"name",
")",
"{",
"if",
"(",
"false",
")",
"return",
"unchecked",
"(",
"(",
")",
"->",
"new",
"URL",
"(",
"\"file:///your/path/here/src/main/wallettemplate/\"",
"+",
"name",
")",
")",
";",
"else",
"return",
"MainController",
".",
"class",
".",
"getResource",
"(",
"name",
")",
";",
"}"
] | A useful helper for development purposes. Used as a switch for loading files from local disk, allowing live
editing whilst the app runs without rebuilds. | [
"A",
"useful",
"helper",
"for",
"development",
"purposes",
".",
"Used",
"as",
"a",
"switch",
"for",
"loading",
"files",
"from",
"local",
"disk",
"allowing",
"live",
"editing",
"whilst",
"the",
"app",
"runs",
"without",
"rebuilds",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/utils/GuiUtils.java#L177-L182 |
23,464 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/store/LevelDBFullPrunedBlockStore.java | LevelDBFullPrunedBlockStore.dumpStats | void dumpStats() {
long wallTimeNanos = totalStopwatch.elapsed(TimeUnit.NANOSECONDS);
long dbtime = 0;
for (String name : methodCalls.keySet()) {
long calls = methodCalls.get(name);
long time = methodTotalTime.get(name);
dbtime += time;
long average = time / calls;
double proportion = (time + 0.0) / (wallTimeNanos + 0.0);
log.info(name + " c:" + calls + " r:" + time + " a:" + average + " p:" + String.format("%.2f", proportion));
}
double dbproportion = (dbtime + 0.0) / (wallTimeNanos + 0.0);
double hitrate = (hit + 0.0) / (hit + miss + 0.0);
log.info("Cache size:" + utxoCache.size() + " hit:" + hit + " miss:" + miss + " rate:"
+ String.format("%.2f", hitrate));
bloom.printStat();
log.info("hasTxOut call:" + hasCall + " True:" + hasTrue + " False:" + hasFalse);
log.info("Wall:" + totalStopwatch + " percent:" + String.format("%.2f", dbproportion));
String stats = db.getProperty("leveldb.stats");
System.out.println(stats);
} | java | void dumpStats() {
long wallTimeNanos = totalStopwatch.elapsed(TimeUnit.NANOSECONDS);
long dbtime = 0;
for (String name : methodCalls.keySet()) {
long calls = methodCalls.get(name);
long time = methodTotalTime.get(name);
dbtime += time;
long average = time / calls;
double proportion = (time + 0.0) / (wallTimeNanos + 0.0);
log.info(name + " c:" + calls + " r:" + time + " a:" + average + " p:" + String.format("%.2f", proportion));
}
double dbproportion = (dbtime + 0.0) / (wallTimeNanos + 0.0);
double hitrate = (hit + 0.0) / (hit + miss + 0.0);
log.info("Cache size:" + utxoCache.size() + " hit:" + hit + " miss:" + miss + " rate:"
+ String.format("%.2f", hitrate));
bloom.printStat();
log.info("hasTxOut call:" + hasCall + " True:" + hasTrue + " False:" + hasFalse);
log.info("Wall:" + totalStopwatch + " percent:" + String.format("%.2f", dbproportion));
String stats = db.getProperty("leveldb.stats");
System.out.println(stats);
} | [
"void",
"dumpStats",
"(",
")",
"{",
"long",
"wallTimeNanos",
"=",
"totalStopwatch",
".",
"elapsed",
"(",
"TimeUnit",
".",
"NANOSECONDS",
")",
";",
"long",
"dbtime",
"=",
"0",
";",
"for",
"(",
"String",
"name",
":",
"methodCalls",
".",
"keySet",
"(",
")",
")",
"{",
"long",
"calls",
"=",
"methodCalls",
".",
"get",
"(",
"name",
")",
";",
"long",
"time",
"=",
"methodTotalTime",
".",
"get",
"(",
"name",
")",
";",
"dbtime",
"+=",
"time",
";",
"long",
"average",
"=",
"time",
"/",
"calls",
";",
"double",
"proportion",
"=",
"(",
"time",
"+",
"0.0",
")",
"/",
"(",
"wallTimeNanos",
"+",
"0.0",
")",
";",
"log",
".",
"info",
"(",
"name",
"+",
"\" c:\"",
"+",
"calls",
"+",
"\" r:\"",
"+",
"time",
"+",
"\" a:\"",
"+",
"average",
"+",
"\" p:\"",
"+",
"String",
".",
"format",
"(",
"\"%.2f\"",
",",
"proportion",
")",
")",
";",
"}",
"double",
"dbproportion",
"=",
"(",
"dbtime",
"+",
"0.0",
")",
"/",
"(",
"wallTimeNanos",
"+",
"0.0",
")",
";",
"double",
"hitrate",
"=",
"(",
"hit",
"+",
"0.0",
")",
"/",
"(",
"hit",
"+",
"miss",
"+",
"0.0",
")",
";",
"log",
".",
"info",
"(",
"\"Cache size:\"",
"+",
"utxoCache",
".",
"size",
"(",
")",
"+",
"\" hit:\"",
"+",
"hit",
"+",
"\" miss:\"",
"+",
"miss",
"+",
"\" rate:\"",
"+",
"String",
".",
"format",
"(",
"\"%.2f\"",
",",
"hitrate",
")",
")",
";",
"bloom",
".",
"printStat",
"(",
")",
";",
"log",
".",
"info",
"(",
"\"hasTxOut call:\"",
"+",
"hasCall",
"+",
"\" True:\"",
"+",
"hasTrue",
"+",
"\" False:\"",
"+",
"hasFalse",
")",
";",
"log",
".",
"info",
"(",
"\"Wall:\"",
"+",
"totalStopwatch",
"+",
"\" percent:\"",
"+",
"String",
".",
"format",
"(",
"\"%.2f\"",
",",
"dbproportion",
")",
")",
";",
"String",
"stats",
"=",
"db",
".",
"getProperty",
"(",
"\"leveldb.stats\"",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"stats",
")",
";",
"}"
] | and cache hit rates etc.. | [
"and",
"cache",
"hit",
"rates",
"etc",
".."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/store/LevelDBFullPrunedBlockStore.java#L365-L386 |
23,465 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.negativeSign | public MonetaryFormat negativeSign(char negativeSign) {
checkArgument(!Character.isDigit(negativeSign));
checkArgument(negativeSign > 0);
if (negativeSign == this.negativeSign)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | java | public MonetaryFormat negativeSign(char negativeSign) {
checkArgument(!Character.isDigit(negativeSign));
checkArgument(negativeSign > 0);
if (negativeSign == this.negativeSign)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | [
"public",
"MonetaryFormat",
"negativeSign",
"(",
"char",
"negativeSign",
")",
"{",
"checkArgument",
"(",
"!",
"Character",
".",
"isDigit",
"(",
"negativeSign",
")",
")",
";",
"checkArgument",
"(",
"negativeSign",
">",
"0",
")",
";",
"if",
"(",
"negativeSign",
"==",
"this",
".",
"negativeSign",
")",
"return",
"this",
";",
"else",
"return",
"new",
"MonetaryFormat",
"(",
"negativeSign",
",",
"positiveSign",
",",
"zeroDigit",
",",
"decimalMark",
",",
"minDecimals",
",",
"decimalGroups",
",",
"shift",
",",
"roundingMode",
",",
"codes",
",",
"codeSeparator",
",",
"codePrefixed",
")",
";",
"}"
] | Set character to prefix negative values. | [
"Set",
"character",
"to",
"prefix",
"negative",
"values",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L89-L97 |
23,466 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.positiveSign | public MonetaryFormat positiveSign(char positiveSign) {
checkArgument(!Character.isDigit(positiveSign));
if (positiveSign == this.positiveSign)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | java | public MonetaryFormat positiveSign(char positiveSign) {
checkArgument(!Character.isDigit(positiveSign));
if (positiveSign == this.positiveSign)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | [
"public",
"MonetaryFormat",
"positiveSign",
"(",
"char",
"positiveSign",
")",
"{",
"checkArgument",
"(",
"!",
"Character",
".",
"isDigit",
"(",
"positiveSign",
")",
")",
";",
"if",
"(",
"positiveSign",
"==",
"this",
".",
"positiveSign",
")",
"return",
"this",
";",
"else",
"return",
"new",
"MonetaryFormat",
"(",
"negativeSign",
",",
"positiveSign",
",",
"zeroDigit",
",",
"decimalMark",
",",
"minDecimals",
",",
"decimalGroups",
",",
"shift",
",",
"roundingMode",
",",
"codes",
",",
"codeSeparator",
",",
"codePrefixed",
")",
";",
"}"
] | Set character to prefix positive values. A zero value means no sign is used in this case. For parsing, a missing
sign will always be interpreted as if the positive sign was used. | [
"Set",
"character",
"to",
"prefix",
"positive",
"values",
".",
"A",
"zero",
"value",
"means",
"no",
"sign",
"is",
"used",
"in",
"this",
"case",
".",
"For",
"parsing",
"a",
"missing",
"sign",
"will",
"always",
"be",
"interpreted",
"as",
"if",
"the",
"positive",
"sign",
"was",
"used",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L103-L110 |
23,467 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.digits | public MonetaryFormat digits(char zeroDigit) {
if (zeroDigit == this.zeroDigit)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | java | public MonetaryFormat digits(char zeroDigit) {
if (zeroDigit == this.zeroDigit)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | [
"public",
"MonetaryFormat",
"digits",
"(",
"char",
"zeroDigit",
")",
"{",
"if",
"(",
"zeroDigit",
"==",
"this",
".",
"zeroDigit",
")",
"return",
"this",
";",
"else",
"return",
"new",
"MonetaryFormat",
"(",
"negativeSign",
",",
"positiveSign",
",",
"zeroDigit",
",",
"decimalMark",
",",
"minDecimals",
",",
"decimalGroups",
",",
"shift",
",",
"roundingMode",
",",
"codes",
",",
"codeSeparator",
",",
"codePrefixed",
")",
";",
"}"
] | Set character range to use for representing digits. It starts with the specified character representing zero. | [
"Set",
"character",
"range",
"to",
"use",
"for",
"representing",
"digits",
".",
"It",
"starts",
"with",
"the",
"specified",
"character",
"representing",
"zero",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L115-L121 |
23,468 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.decimalMark | public MonetaryFormat decimalMark(char decimalMark) {
checkArgument(!Character.isDigit(decimalMark));
checkArgument(decimalMark > 0);
if (decimalMark == this.decimalMark)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | java | public MonetaryFormat decimalMark(char decimalMark) {
checkArgument(!Character.isDigit(decimalMark));
checkArgument(decimalMark > 0);
if (decimalMark == this.decimalMark)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | [
"public",
"MonetaryFormat",
"decimalMark",
"(",
"char",
"decimalMark",
")",
"{",
"checkArgument",
"(",
"!",
"Character",
".",
"isDigit",
"(",
"decimalMark",
")",
")",
";",
"checkArgument",
"(",
"decimalMark",
">",
"0",
")",
";",
"if",
"(",
"decimalMark",
"==",
"this",
".",
"decimalMark",
")",
"return",
"this",
";",
"else",
"return",
"new",
"MonetaryFormat",
"(",
"negativeSign",
",",
"positiveSign",
",",
"zeroDigit",
",",
"decimalMark",
",",
"minDecimals",
",",
"decimalGroups",
",",
"shift",
",",
"roundingMode",
",",
"codes",
",",
"codeSeparator",
",",
"codePrefixed",
")",
";",
"}"
] | Set character to use as the decimal mark. If the formatted value does not have any decimals, no decimal mark is
used either. | [
"Set",
"character",
"to",
"use",
"as",
"the",
"decimal",
"mark",
".",
"If",
"the",
"formatted",
"value",
"does",
"not",
"have",
"any",
"decimals",
"no",
"decimal",
"mark",
"is",
"used",
"either",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L127-L135 |
23,469 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.shift | public MonetaryFormat shift(int shift) {
if (shift == this.shift)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | java | public MonetaryFormat shift(int shift) {
if (shift == this.shift)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | [
"public",
"MonetaryFormat",
"shift",
"(",
"int",
"shift",
")",
"{",
"if",
"(",
"shift",
"==",
"this",
".",
"shift",
")",
"return",
"this",
";",
"else",
"return",
"new",
"MonetaryFormat",
"(",
"negativeSign",
",",
"positiveSign",
",",
"zeroDigit",
",",
"decimalMark",
",",
"minDecimals",
",",
"decimalGroups",
",",
"shift",
",",
"roundingMode",
",",
"codes",
",",
"codeSeparator",
",",
"codePrefixed",
")",
";",
"}"
] | Set number of digits to shift the decimal separator to the right, coming from the standard BTC notation that was
common pre-2014. Note this will change the currency code if enabled. | [
"Set",
"number",
"of",
"digits",
"to",
"shift",
"the",
"decimal",
"separator",
"to",
"the",
"right",
"coming",
"from",
"the",
"standard",
"BTC",
"notation",
"that",
"was",
"common",
"pre",
"-",
"2014",
".",
"Note",
"this",
"will",
"change",
"the",
"currency",
"code",
"if",
"enabled",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L204-L210 |
23,470 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.roundingMode | public MonetaryFormat roundingMode(RoundingMode roundingMode) {
if (roundingMode == this.roundingMode)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | java | public MonetaryFormat roundingMode(RoundingMode roundingMode) {
if (roundingMode == this.roundingMode)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | [
"public",
"MonetaryFormat",
"roundingMode",
"(",
"RoundingMode",
"roundingMode",
")",
"{",
"if",
"(",
"roundingMode",
"==",
"this",
".",
"roundingMode",
")",
"return",
"this",
";",
"else",
"return",
"new",
"MonetaryFormat",
"(",
"negativeSign",
",",
"positiveSign",
",",
"zeroDigit",
",",
"decimalMark",
",",
"minDecimals",
",",
"decimalGroups",
",",
"shift",
",",
"roundingMode",
",",
"codes",
",",
"codeSeparator",
",",
"codePrefixed",
")",
";",
"}"
] | Set rounding mode to use when it becomes necessary. | [
"Set",
"rounding",
"mode",
"to",
"use",
"when",
"it",
"becomes",
"necessary",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L215-L221 |
23,471 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.noCode | public MonetaryFormat noCode() {
if (codes == null)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, null, codeSeparator, codePrefixed);
} | java | public MonetaryFormat noCode() {
if (codes == null)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, null, codeSeparator, codePrefixed);
} | [
"public",
"MonetaryFormat",
"noCode",
"(",
")",
"{",
"if",
"(",
"codes",
"==",
"null",
")",
"return",
"this",
";",
"else",
"return",
"new",
"MonetaryFormat",
"(",
"negativeSign",
",",
"positiveSign",
",",
"zeroDigit",
",",
"decimalMark",
",",
"minDecimals",
",",
"decimalGroups",
",",
"shift",
",",
"roundingMode",
",",
"null",
",",
"codeSeparator",
",",
"codePrefixed",
")",
";",
"}"
] | Don't display currency code when formatting. This configuration is not relevant for parsing. | [
"Don",
"t",
"display",
"currency",
"code",
"when",
"formatting",
".",
"This",
"configuration",
"is",
"not",
"relevant",
"for",
"parsing",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L226-L232 |
23,472 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.code | public MonetaryFormat code(int codeShift, String code) {
checkArgument(codeShift >= 0);
final String[] codes = null == this.codes
? new String[MAX_DECIMALS]
: Arrays.copyOf(this.codes, this.codes.length);
codes[codeShift] = code;
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | java | public MonetaryFormat code(int codeShift, String code) {
checkArgument(codeShift >= 0);
final String[] codes = null == this.codes
? new String[MAX_DECIMALS]
: Arrays.copyOf(this.codes, this.codes.length);
codes[codeShift] = code;
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | [
"public",
"MonetaryFormat",
"code",
"(",
"int",
"codeShift",
",",
"String",
"code",
")",
"{",
"checkArgument",
"(",
"codeShift",
">=",
"0",
")",
";",
"final",
"String",
"[",
"]",
"codes",
"=",
"null",
"==",
"this",
".",
"codes",
"?",
"new",
"String",
"[",
"MAX_DECIMALS",
"]",
":",
"Arrays",
".",
"copyOf",
"(",
"this",
".",
"codes",
",",
"this",
".",
"codes",
".",
"length",
")",
";",
"codes",
"[",
"codeShift",
"]",
"=",
"code",
";",
"return",
"new",
"MonetaryFormat",
"(",
"negativeSign",
",",
"positiveSign",
",",
"zeroDigit",
",",
"decimalMark",
",",
"minDecimals",
",",
"decimalGroups",
",",
"shift",
",",
"roundingMode",
",",
"codes",
",",
"codeSeparator",
",",
"codePrefixed",
")",
";",
"}"
] | Configure currency code for given decimal separator shift. This configuration is not relevant for parsing.
@param codeShift
decimal separator shift, see {@link #shift}
@param code
currency code | [
"Configure",
"currency",
"code",
"for",
"given",
"decimal",
"separator",
"shift",
".",
"This",
"configuration",
"is",
"not",
"relevant",
"for",
"parsing",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L242-L251 |
23,473 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.codeSeparator | public MonetaryFormat codeSeparator(char codeSeparator) {
checkArgument(!Character.isDigit(codeSeparator));
checkArgument(codeSeparator > 0);
if (codeSeparator == this.codeSeparator)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | java | public MonetaryFormat codeSeparator(char codeSeparator) {
checkArgument(!Character.isDigit(codeSeparator));
checkArgument(codeSeparator > 0);
if (codeSeparator == this.codeSeparator)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, codePrefixed);
} | [
"public",
"MonetaryFormat",
"codeSeparator",
"(",
"char",
"codeSeparator",
")",
"{",
"checkArgument",
"(",
"!",
"Character",
".",
"isDigit",
"(",
"codeSeparator",
")",
")",
";",
"checkArgument",
"(",
"codeSeparator",
">",
"0",
")",
";",
"if",
"(",
"codeSeparator",
"==",
"this",
".",
"codeSeparator",
")",
"return",
"this",
";",
"else",
"return",
"new",
"MonetaryFormat",
"(",
"negativeSign",
",",
"positiveSign",
",",
"zeroDigit",
",",
"decimalMark",
",",
"minDecimals",
",",
"decimalGroups",
",",
"shift",
",",
"roundingMode",
",",
"codes",
",",
"codeSeparator",
",",
"codePrefixed",
")",
";",
"}"
] | Separator between currency code and formatted value. This configuration is not relevant for parsing. | [
"Separator",
"between",
"currency",
"code",
"and",
"formatted",
"value",
".",
"This",
"configuration",
"is",
"not",
"relevant",
"for",
"parsing",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L256-L264 |
23,474 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.prefixCode | public MonetaryFormat prefixCode() {
if (codePrefixed)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, true);
} | java | public MonetaryFormat prefixCode() {
if (codePrefixed)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, true);
} | [
"public",
"MonetaryFormat",
"prefixCode",
"(",
")",
"{",
"if",
"(",
"codePrefixed",
")",
"return",
"this",
";",
"else",
"return",
"new",
"MonetaryFormat",
"(",
"negativeSign",
",",
"positiveSign",
",",
"zeroDigit",
",",
"decimalMark",
",",
"minDecimals",
",",
"decimalGroups",
",",
"shift",
",",
"roundingMode",
",",
"codes",
",",
"codeSeparator",
",",
"true",
")",
";",
"}"
] | Prefix formatted output by currency code. This configuration is not relevant for parsing. | [
"Prefix",
"formatted",
"output",
"by",
"currency",
"code",
".",
"This",
"configuration",
"is",
"not",
"relevant",
"for",
"parsing",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L269-L275 |
23,475 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.postfixCode | public MonetaryFormat postfixCode() {
if (!codePrefixed)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, false);
} | java | public MonetaryFormat postfixCode() {
if (!codePrefixed)
return this;
else
return new MonetaryFormat(negativeSign, positiveSign, zeroDigit, decimalMark, minDecimals, decimalGroups,
shift, roundingMode, codes, codeSeparator, false);
} | [
"public",
"MonetaryFormat",
"postfixCode",
"(",
")",
"{",
"if",
"(",
"!",
"codePrefixed",
")",
"return",
"this",
";",
"else",
"return",
"new",
"MonetaryFormat",
"(",
"negativeSign",
",",
"positiveSign",
",",
"zeroDigit",
",",
"decimalMark",
",",
"minDecimals",
",",
"decimalGroups",
",",
"shift",
",",
"roundingMode",
",",
"codes",
",",
"codeSeparator",
",",
"false",
")",
";",
"}"
] | Postfix formatted output with currency code. This configuration is not relevant for parsing. | [
"Postfix",
"formatted",
"output",
"with",
"currency",
"code",
".",
"This",
"configuration",
"is",
"not",
"relevant",
"for",
"parsing",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L280-L286 |
23,476 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.format | public CharSequence format(Monetary monetary) {
// preparation
int maxDecimals = minDecimals;
if (decimalGroups != null)
for (int group : decimalGroups)
maxDecimals += group;
int smallestUnitExponent = monetary.smallestUnitExponent();
checkState(maxDecimals <= smallestUnitExponent,
"The maximum possible number of decimals (%s) cannot exceed %s.", maxDecimals, smallestUnitExponent);
// rounding
long satoshis = Math.abs(monetary.getValue());
long precisionDivisor = checkedPow(10, smallestUnitExponent - shift - maxDecimals);
satoshis = checkedMultiply(divide(satoshis, precisionDivisor, roundingMode), precisionDivisor);
// shifting
long shiftDivisor = checkedPow(10, smallestUnitExponent - shift);
long numbers = satoshis / shiftDivisor;
long decimals = satoshis % shiftDivisor;
// formatting
String decimalsStr = String.format(Locale.US, "%0" + (smallestUnitExponent - shift) + "d", decimals);
StringBuilder str = new StringBuilder(decimalsStr);
while (str.length() > minDecimals && str.charAt(str.length() - 1) == '0')
str.setLength(str.length() - 1); // trim trailing zero
int i = minDecimals;
if (decimalGroups != null) {
for (int group : decimalGroups) {
if (str.length() > i && str.length() < i + group) {
while (str.length() < i + group)
str.append('0');
break;
}
i += group;
}
}
if (str.length() > 0)
str.insert(0, decimalMark);
str.insert(0, numbers);
if (monetary.getValue() < 0)
str.insert(0, negativeSign);
else if (positiveSign != 0)
str.insert(0, positiveSign);
if (codes != null) {
if (codePrefixed) {
str.insert(0, codeSeparator);
str.insert(0, code());
} else {
str.append(codeSeparator);
str.append(code());
}
}
// Convert to non-arabic digits.
if (zeroDigit != '0') {
int offset = zeroDigit - '0';
for (int d = 0; d < str.length(); d++) {
char c = str.charAt(d);
if (Character.isDigit(c))
str.setCharAt(d, (char) (c + offset));
}
}
return str;
} | java | public CharSequence format(Monetary monetary) {
// preparation
int maxDecimals = minDecimals;
if (decimalGroups != null)
for (int group : decimalGroups)
maxDecimals += group;
int smallestUnitExponent = monetary.smallestUnitExponent();
checkState(maxDecimals <= smallestUnitExponent,
"The maximum possible number of decimals (%s) cannot exceed %s.", maxDecimals, smallestUnitExponent);
// rounding
long satoshis = Math.abs(monetary.getValue());
long precisionDivisor = checkedPow(10, smallestUnitExponent - shift - maxDecimals);
satoshis = checkedMultiply(divide(satoshis, precisionDivisor, roundingMode), precisionDivisor);
// shifting
long shiftDivisor = checkedPow(10, smallestUnitExponent - shift);
long numbers = satoshis / shiftDivisor;
long decimals = satoshis % shiftDivisor;
// formatting
String decimalsStr = String.format(Locale.US, "%0" + (smallestUnitExponent - shift) + "d", decimals);
StringBuilder str = new StringBuilder(decimalsStr);
while (str.length() > minDecimals && str.charAt(str.length() - 1) == '0')
str.setLength(str.length() - 1); // trim trailing zero
int i = minDecimals;
if (decimalGroups != null) {
for (int group : decimalGroups) {
if (str.length() > i && str.length() < i + group) {
while (str.length() < i + group)
str.append('0');
break;
}
i += group;
}
}
if (str.length() > 0)
str.insert(0, decimalMark);
str.insert(0, numbers);
if (monetary.getValue() < 0)
str.insert(0, negativeSign);
else if (positiveSign != 0)
str.insert(0, positiveSign);
if (codes != null) {
if (codePrefixed) {
str.insert(0, codeSeparator);
str.insert(0, code());
} else {
str.append(codeSeparator);
str.append(code());
}
}
// Convert to non-arabic digits.
if (zeroDigit != '0') {
int offset = zeroDigit - '0';
for (int d = 0; d < str.length(); d++) {
char c = str.charAt(d);
if (Character.isDigit(c))
str.setCharAt(d, (char) (c + offset));
}
}
return str;
} | [
"public",
"CharSequence",
"format",
"(",
"Monetary",
"monetary",
")",
"{",
"// preparation",
"int",
"maxDecimals",
"=",
"minDecimals",
";",
"if",
"(",
"decimalGroups",
"!=",
"null",
")",
"for",
"(",
"int",
"group",
":",
"decimalGroups",
")",
"maxDecimals",
"+=",
"group",
";",
"int",
"smallestUnitExponent",
"=",
"monetary",
".",
"smallestUnitExponent",
"(",
")",
";",
"checkState",
"(",
"maxDecimals",
"<=",
"smallestUnitExponent",
",",
"\"The maximum possible number of decimals (%s) cannot exceed %s.\"",
",",
"maxDecimals",
",",
"smallestUnitExponent",
")",
";",
"// rounding",
"long",
"satoshis",
"=",
"Math",
".",
"abs",
"(",
"monetary",
".",
"getValue",
"(",
")",
")",
";",
"long",
"precisionDivisor",
"=",
"checkedPow",
"(",
"10",
",",
"smallestUnitExponent",
"-",
"shift",
"-",
"maxDecimals",
")",
";",
"satoshis",
"=",
"checkedMultiply",
"(",
"divide",
"(",
"satoshis",
",",
"precisionDivisor",
",",
"roundingMode",
")",
",",
"precisionDivisor",
")",
";",
"// shifting",
"long",
"shiftDivisor",
"=",
"checkedPow",
"(",
"10",
",",
"smallestUnitExponent",
"-",
"shift",
")",
";",
"long",
"numbers",
"=",
"satoshis",
"/",
"shiftDivisor",
";",
"long",
"decimals",
"=",
"satoshis",
"%",
"shiftDivisor",
";",
"// formatting",
"String",
"decimalsStr",
"=",
"String",
".",
"format",
"(",
"Locale",
".",
"US",
",",
"\"%0\"",
"+",
"(",
"smallestUnitExponent",
"-",
"shift",
")",
"+",
"\"d\"",
",",
"decimals",
")",
";",
"StringBuilder",
"str",
"=",
"new",
"StringBuilder",
"(",
"decimalsStr",
")",
";",
"while",
"(",
"str",
".",
"length",
"(",
")",
">",
"minDecimals",
"&&",
"str",
".",
"charAt",
"(",
"str",
".",
"length",
"(",
")",
"-",
"1",
")",
"==",
"'",
"'",
")",
"str",
".",
"setLength",
"(",
"str",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"// trim trailing zero",
"int",
"i",
"=",
"minDecimals",
";",
"if",
"(",
"decimalGroups",
"!=",
"null",
")",
"{",
"for",
"(",
"int",
"group",
":",
"decimalGroups",
")",
"{",
"if",
"(",
"str",
".",
"length",
"(",
")",
">",
"i",
"&&",
"str",
".",
"length",
"(",
")",
"<",
"i",
"+",
"group",
")",
"{",
"while",
"(",
"str",
".",
"length",
"(",
")",
"<",
"i",
"+",
"group",
")",
"str",
".",
"append",
"(",
"'",
"'",
")",
";",
"break",
";",
"}",
"i",
"+=",
"group",
";",
"}",
"}",
"if",
"(",
"str",
".",
"length",
"(",
")",
">",
"0",
")",
"str",
".",
"insert",
"(",
"0",
",",
"decimalMark",
")",
";",
"str",
".",
"insert",
"(",
"0",
",",
"numbers",
")",
";",
"if",
"(",
"monetary",
".",
"getValue",
"(",
")",
"<",
"0",
")",
"str",
".",
"insert",
"(",
"0",
",",
"negativeSign",
")",
";",
"else",
"if",
"(",
"positiveSign",
"!=",
"0",
")",
"str",
".",
"insert",
"(",
"0",
",",
"positiveSign",
")",
";",
"if",
"(",
"codes",
"!=",
"null",
")",
"{",
"if",
"(",
"codePrefixed",
")",
"{",
"str",
".",
"insert",
"(",
"0",
",",
"codeSeparator",
")",
";",
"str",
".",
"insert",
"(",
"0",
",",
"code",
"(",
")",
")",
";",
"}",
"else",
"{",
"str",
".",
"append",
"(",
"codeSeparator",
")",
";",
"str",
".",
"append",
"(",
"code",
"(",
")",
")",
";",
"}",
"}",
"// Convert to non-arabic digits.",
"if",
"(",
"zeroDigit",
"!=",
"'",
"'",
")",
"{",
"int",
"offset",
"=",
"zeroDigit",
"-",
"'",
"'",
";",
"for",
"(",
"int",
"d",
"=",
"0",
";",
"d",
"<",
"str",
".",
"length",
"(",
")",
";",
"d",
"++",
")",
"{",
"char",
"c",
"=",
"str",
".",
"charAt",
"(",
"d",
")",
";",
"if",
"(",
"Character",
".",
"isDigit",
"(",
"c",
")",
")",
"str",
".",
"setCharAt",
"(",
"d",
",",
"(",
"char",
")",
"(",
"c",
"+",
"offset",
")",
")",
";",
"}",
"}",
"return",
"str",
";",
"}"
] | Format the given monetary value to a human readable form. | [
"Format",
"the",
"given",
"monetary",
"value",
"to",
"a",
"human",
"readable",
"form",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L341-L404 |
23,477 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java | MonetaryFormat.code | public String code() {
if (codes == null)
return null;
if (codes[shift] == null)
throw new NumberFormatException("missing code for shift: " + shift);
return codes[shift];
} | java | public String code() {
if (codes == null)
return null;
if (codes[shift] == null)
throw new NumberFormatException("missing code for shift: " + shift);
return codes[shift];
} | [
"public",
"String",
"code",
"(",
")",
"{",
"if",
"(",
"codes",
"==",
"null",
")",
"return",
"null",
";",
"if",
"(",
"codes",
"[",
"shift",
"]",
"==",
"null",
")",
"throw",
"new",
"NumberFormatException",
"(",
"\"missing code for shift: \"",
"+",
"shift",
")",
";",
"return",
"codes",
"[",
"shift",
"]",
";",
"}"
] | Get currency code that will be used for current shift. | [
"Get",
"currency",
"code",
"that",
"will",
"be",
"used",
"for",
"current",
"shift",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/MonetaryFormat.java#L458-L464 |
23,478 | bitcoinj/bitcoinj | wallettemplate/src/main/java/wallettemplate/utils/AppDataDirectory.java | AppDataDirectory.get | public static Path get(String appName) {
final Path applicationDataDirectory = getPath(appName);
try {
Files.createDirectories(applicationDataDirectory);
} catch (IOException ioe) {
throw new RuntimeException("Couldn't find/create AppDataDirectory", ioe);
}
return applicationDataDirectory;
} | java | public static Path get(String appName) {
final Path applicationDataDirectory = getPath(appName);
try {
Files.createDirectories(applicationDataDirectory);
} catch (IOException ioe) {
throw new RuntimeException("Couldn't find/create AppDataDirectory", ioe);
}
return applicationDataDirectory;
} | [
"public",
"static",
"Path",
"get",
"(",
"String",
"appName",
")",
"{",
"final",
"Path",
"applicationDataDirectory",
"=",
"getPath",
"(",
"appName",
")",
";",
"try",
"{",
"Files",
".",
"createDirectories",
"(",
"applicationDataDirectory",
")",
";",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Couldn't find/create AppDataDirectory\"",
",",
"ioe",
")",
";",
"}",
"return",
"applicationDataDirectory",
";",
"}"
] | Get and create if necessary the Path to the application data directory.
@param appName The name of the current application
@return Path to the application data directory | [
"Get",
"and",
"create",
"if",
"necessary",
"the",
"Path",
"to",
"the",
"application",
"data",
"directory",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/wallettemplate/src/main/java/wallettemplate/utils/AppDataDirectory.java#L36-L46 |
23,479 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/HDKeyDerivation.java | HDKeyDerivation.deriveThisOrNextChildKey | public static DeterministicKey deriveThisOrNextChildKey(DeterministicKey parent, int childNumber) {
int nAttempts = 0;
ChildNumber child = new ChildNumber(childNumber);
boolean isHardened = child.isHardened();
while (nAttempts < MAX_CHILD_DERIVATION_ATTEMPTS) {
try {
child = new ChildNumber(child.num() + nAttempts, isHardened);
return deriveChildKey(parent, child);
} catch (HDDerivationException ignore) { }
nAttempts++;
}
throw new HDDerivationException("Maximum number of child derivation attempts reached, this is probably an indication of a bug.");
} | java | public static DeterministicKey deriveThisOrNextChildKey(DeterministicKey parent, int childNumber) {
int nAttempts = 0;
ChildNumber child = new ChildNumber(childNumber);
boolean isHardened = child.isHardened();
while (nAttempts < MAX_CHILD_DERIVATION_ATTEMPTS) {
try {
child = new ChildNumber(child.num() + nAttempts, isHardened);
return deriveChildKey(parent, child);
} catch (HDDerivationException ignore) { }
nAttempts++;
}
throw new HDDerivationException("Maximum number of child derivation attempts reached, this is probably an indication of a bug.");
} | [
"public",
"static",
"DeterministicKey",
"deriveThisOrNextChildKey",
"(",
"DeterministicKey",
"parent",
",",
"int",
"childNumber",
")",
"{",
"int",
"nAttempts",
"=",
"0",
";",
"ChildNumber",
"child",
"=",
"new",
"ChildNumber",
"(",
"childNumber",
")",
";",
"boolean",
"isHardened",
"=",
"child",
".",
"isHardened",
"(",
")",
";",
"while",
"(",
"nAttempts",
"<",
"MAX_CHILD_DERIVATION_ATTEMPTS",
")",
"{",
"try",
"{",
"child",
"=",
"new",
"ChildNumber",
"(",
"child",
".",
"num",
"(",
")",
"+",
"nAttempts",
",",
"isHardened",
")",
";",
"return",
"deriveChildKey",
"(",
"parent",
",",
"child",
")",
";",
"}",
"catch",
"(",
"HDDerivationException",
"ignore",
")",
"{",
"}",
"nAttempts",
"++",
";",
"}",
"throw",
"new",
"HDDerivationException",
"(",
"\"Maximum number of child derivation attempts reached, this is probably an indication of a bug.\"",
")",
";",
"}"
] | Derives a key of the "extended" child number, ie. with the 0x80000000 bit specifying whether to use
hardened derivation or not. If derivation fails, tries a next child. | [
"Derives",
"a",
"key",
"of",
"the",
"extended",
"child",
"number",
"ie",
".",
"with",
"the",
"0x80000000",
"bit",
"specifying",
"whether",
"to",
"use",
"hardened",
"derivation",
"or",
"not",
".",
"If",
"derivation",
"fails",
"tries",
"a",
"next",
"child",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/HDKeyDerivation.java#L121-L134 |
23,480 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/ScriptBuilder.java | ScriptBuilder.op | public ScriptBuilder op(int index, int opcode) {
checkArgument(opcode > OP_PUSHDATA4);
return addChunk(index, new ScriptChunk(opcode, null));
} | java | public ScriptBuilder op(int index, int opcode) {
checkArgument(opcode > OP_PUSHDATA4);
return addChunk(index, new ScriptChunk(opcode, null));
} | [
"public",
"ScriptBuilder",
"op",
"(",
"int",
"index",
",",
"int",
"opcode",
")",
"{",
"checkArgument",
"(",
"opcode",
">",
"OP_PUSHDATA4",
")",
";",
"return",
"addChunk",
"(",
"index",
",",
"new",
"ScriptChunk",
"(",
"opcode",
",",
"null",
")",
")",
";",
"}"
] | Adds the given opcode to the given index in the program | [
"Adds",
"the",
"given",
"opcode",
"to",
"the",
"given",
"index",
"in",
"the",
"program"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java#L80-L83 |
23,481 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/ScriptBuilder.java | ScriptBuilder.number | public ScriptBuilder number(int index, long num) {
if (num == -1) {
return op(index, OP_1NEGATE);
} else if (num >= 0 && num <= 16) {
return smallNum(index, (int) num);
} else {
return bigNum(index, num);
}
} | java | public ScriptBuilder number(int index, long num) {
if (num == -1) {
return op(index, OP_1NEGATE);
} else if (num >= 0 && num <= 16) {
return smallNum(index, (int) num);
} else {
return bigNum(index, num);
}
} | [
"public",
"ScriptBuilder",
"number",
"(",
"int",
"index",
",",
"long",
"num",
")",
"{",
"if",
"(",
"num",
"==",
"-",
"1",
")",
"{",
"return",
"op",
"(",
"index",
",",
"OP_1NEGATE",
")",
";",
"}",
"else",
"if",
"(",
"num",
">=",
"0",
"&&",
"num",
"<=",
"16",
")",
"{",
"return",
"smallNum",
"(",
"index",
",",
"(",
"int",
")",
"num",
")",
";",
"}",
"else",
"{",
"return",
"bigNum",
"(",
"index",
",",
"num",
")",
";",
"}",
"}"
] | Adds the given number to the given index in the program. Automatically
uses shortest encoding possible. | [
"Adds",
"the",
"given",
"number",
"to",
"the",
"given",
"index",
"in",
"the",
"program",
".",
"Automatically",
"uses",
"shortest",
"encoding",
"possible",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java#L130-L138 |
23,482 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/ScriptBuilder.java | ScriptBuilder.smallNum | public ScriptBuilder smallNum(int index, int num) {
checkArgument(num >= 0, "Cannot encode negative numbers with smallNum");
checkArgument(num <= 16, "Cannot encode numbers larger than 16 with smallNum");
return addChunk(index, new ScriptChunk(Script.encodeToOpN(num), null));
} | java | public ScriptBuilder smallNum(int index, int num) {
checkArgument(num >= 0, "Cannot encode negative numbers with smallNum");
checkArgument(num <= 16, "Cannot encode numbers larger than 16 with smallNum");
return addChunk(index, new ScriptChunk(Script.encodeToOpN(num), null));
} | [
"public",
"ScriptBuilder",
"smallNum",
"(",
"int",
"index",
",",
"int",
"num",
")",
"{",
"checkArgument",
"(",
"num",
">=",
"0",
",",
"\"Cannot encode negative numbers with smallNum\"",
")",
";",
"checkArgument",
"(",
"num",
"<=",
"16",
",",
"\"Cannot encode numbers larger than 16 with smallNum\"",
")",
";",
"return",
"addChunk",
"(",
"index",
",",
"new",
"ScriptChunk",
"(",
"Script",
".",
"encodeToOpN",
"(",
"num",
")",
",",
"null",
")",
")",
";",
"}"
] | Adds the given number as a OP_N opcode to the given index in the program.
Only handles values 0-16 inclusive.
@see #number(long) | [
"Adds",
"the",
"given",
"number",
"as",
"a",
"OP_N",
"opcode",
"to",
"the",
"given",
"index",
"in",
"the",
"program",
".",
"Only",
"handles",
"values",
"0",
"-",
"16",
"inclusive",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java#L167-L171 |
23,483 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/ScriptBuilder.java | ScriptBuilder.bigNum | protected ScriptBuilder bigNum(int index, long num) {
final byte[] data;
if (num == 0) {
data = new byte[0];
} else {
Stack<Byte> result = new Stack<>();
final boolean neg = num < 0;
long absvalue = Math.abs(num);
while (absvalue != 0) {
result.push((byte) (absvalue & 0xff));
absvalue >>= 8;
}
if ((result.peek() & 0x80) != 0) {
// The most significant byte is >= 0x80, so push an extra byte that
// contains just the sign of the value.
result.push((byte) (neg ? 0x80 : 0));
} else if (neg) {
// The most significant byte is < 0x80 and the value is negative,
// set the sign bit so it is subtracted and interpreted as a
// negative when converting back to an integral.
result.push((byte) (result.pop() | 0x80));
}
data = new byte[result.size()];
for (int byteIdx = 0; byteIdx < data.length; byteIdx++) {
data[byteIdx] = result.get(byteIdx);
}
}
// At most the encoded value could take up to 8 bytes, so we don't need
// to use OP_PUSHDATA opcodes
return addChunk(index, new ScriptChunk(data.length, data));
} | java | protected ScriptBuilder bigNum(int index, long num) {
final byte[] data;
if (num == 0) {
data = new byte[0];
} else {
Stack<Byte> result = new Stack<>();
final boolean neg = num < 0;
long absvalue = Math.abs(num);
while (absvalue != 0) {
result.push((byte) (absvalue & 0xff));
absvalue >>= 8;
}
if ((result.peek() & 0x80) != 0) {
// The most significant byte is >= 0x80, so push an extra byte that
// contains just the sign of the value.
result.push((byte) (neg ? 0x80 : 0));
} else if (neg) {
// The most significant byte is < 0x80 and the value is negative,
// set the sign bit so it is subtracted and interpreted as a
// negative when converting back to an integral.
result.push((byte) (result.pop() | 0x80));
}
data = new byte[result.size()];
for (int byteIdx = 0; byteIdx < data.length; byteIdx++) {
data[byteIdx] = result.get(byteIdx);
}
}
// At most the encoded value could take up to 8 bytes, so we don't need
// to use OP_PUSHDATA opcodes
return addChunk(index, new ScriptChunk(data.length, data));
} | [
"protected",
"ScriptBuilder",
"bigNum",
"(",
"int",
"index",
",",
"long",
"num",
")",
"{",
"final",
"byte",
"[",
"]",
"data",
";",
"if",
"(",
"num",
"==",
"0",
")",
"{",
"data",
"=",
"new",
"byte",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"Stack",
"<",
"Byte",
">",
"result",
"=",
"new",
"Stack",
"<>",
"(",
")",
";",
"final",
"boolean",
"neg",
"=",
"num",
"<",
"0",
";",
"long",
"absvalue",
"=",
"Math",
".",
"abs",
"(",
"num",
")",
";",
"while",
"(",
"absvalue",
"!=",
"0",
")",
"{",
"result",
".",
"push",
"(",
"(",
"byte",
")",
"(",
"absvalue",
"&",
"0xff",
")",
")",
";",
"absvalue",
">>=",
"8",
";",
"}",
"if",
"(",
"(",
"result",
".",
"peek",
"(",
")",
"&",
"0x80",
")",
"!=",
"0",
")",
"{",
"// The most significant byte is >= 0x80, so push an extra byte that",
"// contains just the sign of the value.",
"result",
".",
"push",
"(",
"(",
"byte",
")",
"(",
"neg",
"?",
"0x80",
":",
"0",
")",
")",
";",
"}",
"else",
"if",
"(",
"neg",
")",
"{",
"// The most significant byte is < 0x80 and the value is negative,",
"// set the sign bit so it is subtracted and interpreted as a",
"// negative when converting back to an integral.",
"result",
".",
"push",
"(",
"(",
"byte",
")",
"(",
"result",
".",
"pop",
"(",
")",
"|",
"0x80",
")",
")",
";",
"}",
"data",
"=",
"new",
"byte",
"[",
"result",
".",
"size",
"(",
")",
"]",
";",
"for",
"(",
"int",
"byteIdx",
"=",
"0",
";",
"byteIdx",
"<",
"data",
".",
"length",
";",
"byteIdx",
"++",
")",
"{",
"data",
"[",
"byteIdx",
"]",
"=",
"result",
".",
"get",
"(",
"byteIdx",
")",
";",
"}",
"}",
"// At most the encoded value could take up to 8 bytes, so we don't need",
"// to use OP_PUSHDATA opcodes",
"return",
"addChunk",
"(",
"index",
",",
"new",
"ScriptChunk",
"(",
"data",
".",
"length",
",",
"data",
")",
")",
";",
"}"
] | Adds the given number as a push data chunk to the given index in the program.
This is intended to use for negative numbers or values greater than 16, and although
it will accept numbers in the range 0-16 inclusive, the encoding would be
considered non-standard.
@see #number(long) | [
"Adds",
"the",
"given",
"number",
"as",
"a",
"push",
"data",
"chunk",
"to",
"the",
"given",
"index",
"in",
"the",
"program",
".",
"This",
"is",
"intended",
"to",
"use",
"for",
"negative",
"numbers",
"or",
"values",
"greater",
"than",
"16",
"and",
"although",
"it",
"will",
"accept",
"numbers",
"in",
"the",
"range",
"0",
"-",
"16",
"inclusive",
"the",
"encoding",
"would",
"be",
"considered",
"non",
"-",
"standard",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java#L181-L216 |
23,484 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/ScriptBuilder.java | ScriptBuilder.createOutputScript | public static Script createOutputScript(Address to) {
if (to instanceof LegacyAddress) {
ScriptType scriptType = to.getOutputScriptType();
if (scriptType == ScriptType.P2PKH)
return createP2PKHOutputScript(to.getHash());
else if (scriptType == ScriptType.P2SH)
return createP2SHOutputScript(to.getHash());
else
throw new IllegalStateException("Cannot handle " + scriptType);
} else if (to instanceof SegwitAddress) {
ScriptBuilder builder = new ScriptBuilder();
// OP_0 <pubKeyHash|scriptHash>
SegwitAddress toSegwit = (SegwitAddress) to;
builder.smallNum(toSegwit.getWitnessVersion());
builder.data(toSegwit.getWitnessProgram());
return builder.build();
} else {
throw new IllegalStateException("Cannot handle " + to);
}
} | java | public static Script createOutputScript(Address to) {
if (to instanceof LegacyAddress) {
ScriptType scriptType = to.getOutputScriptType();
if (scriptType == ScriptType.P2PKH)
return createP2PKHOutputScript(to.getHash());
else if (scriptType == ScriptType.P2SH)
return createP2SHOutputScript(to.getHash());
else
throw new IllegalStateException("Cannot handle " + scriptType);
} else if (to instanceof SegwitAddress) {
ScriptBuilder builder = new ScriptBuilder();
// OP_0 <pubKeyHash|scriptHash>
SegwitAddress toSegwit = (SegwitAddress) to;
builder.smallNum(toSegwit.getWitnessVersion());
builder.data(toSegwit.getWitnessProgram());
return builder.build();
} else {
throw new IllegalStateException("Cannot handle " + to);
}
} | [
"public",
"static",
"Script",
"createOutputScript",
"(",
"Address",
"to",
")",
"{",
"if",
"(",
"to",
"instanceof",
"LegacyAddress",
")",
"{",
"ScriptType",
"scriptType",
"=",
"to",
".",
"getOutputScriptType",
"(",
")",
";",
"if",
"(",
"scriptType",
"==",
"ScriptType",
".",
"P2PKH",
")",
"return",
"createP2PKHOutputScript",
"(",
"to",
".",
"getHash",
"(",
")",
")",
";",
"else",
"if",
"(",
"scriptType",
"==",
"ScriptType",
".",
"P2SH",
")",
"return",
"createP2SHOutputScript",
"(",
"to",
".",
"getHash",
"(",
")",
")",
";",
"else",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot handle \"",
"+",
"scriptType",
")",
";",
"}",
"else",
"if",
"(",
"to",
"instanceof",
"SegwitAddress",
")",
"{",
"ScriptBuilder",
"builder",
"=",
"new",
"ScriptBuilder",
"(",
")",
";",
"// OP_0 <pubKeyHash|scriptHash>",
"SegwitAddress",
"toSegwit",
"=",
"(",
"SegwitAddress",
")",
"to",
";",
"builder",
".",
"smallNum",
"(",
"toSegwit",
".",
"getWitnessVersion",
"(",
")",
")",
";",
"builder",
".",
"data",
"(",
"toSegwit",
".",
"getWitnessProgram",
"(",
")",
")",
";",
"return",
"builder",
".",
"build",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot handle \"",
"+",
"to",
")",
";",
"}",
"}"
] | Creates a scriptPubKey that encodes payment to the given address. | [
"Creates",
"a",
"scriptPubKey",
"that",
"encodes",
"payment",
"to",
"the",
"given",
"address",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java#L263-L282 |
23,485 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/ScriptBuilder.java | ScriptBuilder.createMultiSigInputScript | public static Script createMultiSigInputScript(List<TransactionSignature> signatures) {
List<byte[]> sigs = new ArrayList<>(signatures.size());
for (TransactionSignature signature : signatures) {
sigs.add(signature.encodeToBitcoin());
}
return createMultiSigInputScriptBytes(sigs, null);
} | java | public static Script createMultiSigInputScript(List<TransactionSignature> signatures) {
List<byte[]> sigs = new ArrayList<>(signatures.size());
for (TransactionSignature signature : signatures) {
sigs.add(signature.encodeToBitcoin());
}
return createMultiSigInputScriptBytes(sigs, null);
} | [
"public",
"static",
"Script",
"createMultiSigInputScript",
"(",
"List",
"<",
"TransactionSignature",
">",
"signatures",
")",
"{",
"List",
"<",
"byte",
"[",
"]",
">",
"sigs",
"=",
"new",
"ArrayList",
"<>",
"(",
"signatures",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"TransactionSignature",
"signature",
":",
"signatures",
")",
"{",
"sigs",
".",
"add",
"(",
"signature",
".",
"encodeToBitcoin",
"(",
")",
")",
";",
"}",
"return",
"createMultiSigInputScriptBytes",
"(",
"sigs",
",",
"null",
")",
";",
"}"
] | Create a program that satisfies an OP_CHECKMULTISIG program. | [
"Create",
"a",
"program",
"that",
"satisfies",
"an",
"OP_CHECKMULTISIG",
"program",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/ScriptBuilder.java#L319-L326 |
23,486 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.getCoinInstance | public static BtcFormat getCoinInstance(Locale locale, int scale, int... groups) {
return getInstance(COIN_SCALE, locale, scale, boxAsList(groups));
} | java | public static BtcFormat getCoinInstance(Locale locale, int scale, int... groups) {
return getInstance(COIN_SCALE, locale, scale, boxAsList(groups));
} | [
"public",
"static",
"BtcFormat",
"getCoinInstance",
"(",
"Locale",
"locale",
",",
"int",
"scale",
",",
"int",
"...",
"groups",
")",
"{",
"return",
"getInstance",
"(",
"COIN_SCALE",
",",
"locale",
",",
"scale",
",",
"boxAsList",
"(",
"groups",
")",
")",
";",
"}"
] | Return a newly-constructed instance for the given locale that will format
values in terms of bitcoins, with the given minimum number of fractional
decimal places. Optionally, repeating integer arguments can be passed, each
indicating the size of an additional group of fractional decimal places to be
used as necessary to avoid rounding, to a limiting precision of satoshis. | [
"Return",
"a",
"newly",
"-",
"constructed",
"instance",
"for",
"the",
"given",
"locale",
"that",
"will",
"format",
"values",
"in",
"terms",
"of",
"bitcoins",
"with",
"the",
"given",
"minimum",
"number",
"of",
"fractional",
"decimal",
"places",
".",
"Optionally",
"repeating",
"integer",
"arguments",
"can",
"be",
"passed",
"each",
"indicating",
"the",
"size",
"of",
"an",
"additional",
"group",
"of",
"fractional",
"decimal",
"places",
"to",
"be",
"used",
"as",
"necessary",
"to",
"avoid",
"rounding",
"to",
"a",
"limiting",
"precision",
"of",
"satoshis",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L968-L970 |
23,487 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.getMilliInstance | public static BtcFormat getMilliInstance(int scale, int... groups) {
return getInstance(MILLICOIN_SCALE, defaultLocale(), scale, boxAsList(groups));
} | java | public static BtcFormat getMilliInstance(int scale, int... groups) {
return getInstance(MILLICOIN_SCALE, defaultLocale(), scale, boxAsList(groups));
} | [
"public",
"static",
"BtcFormat",
"getMilliInstance",
"(",
"int",
"scale",
",",
"int",
"...",
"groups",
")",
"{",
"return",
"getInstance",
"(",
"MILLICOIN_SCALE",
",",
"defaultLocale",
"(",
")",
",",
"scale",
",",
"boxAsList",
"(",
"groups",
")",
")",
";",
"}"
] | Return a new millicoin-denominated formatter with the specified fractional decimal
placing. The returned object will format and parse values according to the default
locale, and will format the fractional part of numbers with the given minimum number of
fractional decimal places. Optionally, repeating integer arguments can be passed, each
indicating the size of an additional group of fractional decimal places to be used as
necessary to avoid rounding, to a limiting precision of satoshis. | [
"Return",
"a",
"new",
"millicoin",
"-",
"denominated",
"formatter",
"with",
"the",
"specified",
"fractional",
"decimal",
"placing",
".",
"The",
"returned",
"object",
"will",
"format",
"and",
"parse",
"values",
"according",
"to",
"the",
"default",
"locale",
"and",
"will",
"format",
"the",
"fractional",
"part",
"of",
"numbers",
"with",
"the",
"given",
"minimum",
"number",
"of",
"fractional",
"decimal",
"places",
".",
"Optionally",
"repeating",
"integer",
"arguments",
"can",
"be",
"passed",
"each",
"indicating",
"the",
"size",
"of",
"an",
"additional",
"group",
"of",
"fractional",
"decimal",
"places",
"to",
"be",
"used",
"as",
"necessary",
"to",
"avoid",
"rounding",
"to",
"a",
"limiting",
"precision",
"of",
"satoshis",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L996-L998 |
23,488 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.getMilliInstance | public static BtcFormat getMilliInstance(Locale locale, int scale, int... groups) {
return getInstance(MILLICOIN_SCALE, locale, scale, boxAsList(groups));
} | java | public static BtcFormat getMilliInstance(Locale locale, int scale, int... groups) {
return getInstance(MILLICOIN_SCALE, locale, scale, boxAsList(groups));
} | [
"public",
"static",
"BtcFormat",
"getMilliInstance",
"(",
"Locale",
"locale",
",",
"int",
"scale",
",",
"int",
"...",
"groups",
")",
"{",
"return",
"getInstance",
"(",
"MILLICOIN_SCALE",
",",
"locale",
",",
"scale",
",",
"boxAsList",
"(",
"groups",
")",
")",
";",
"}"
] | Return a new millicoin-denominated formatter for the given locale with the specified
fractional decimal placing. The returned object will format the fractional part of
numbers with the given minimum number of fractional decimal places. Optionally,
repeating integer arguments can be passed, each indicating the size of an additional
group of fractional decimal places to be used as necessary to avoid rounding, to a
limiting precision of satoshis. | [
"Return",
"a",
"new",
"millicoin",
"-",
"denominated",
"formatter",
"for",
"the",
"given",
"locale",
"with",
"the",
"specified",
"fractional",
"decimal",
"placing",
".",
"The",
"returned",
"object",
"will",
"format",
"the",
"fractional",
"part",
"of",
"numbers",
"with",
"the",
"given",
"minimum",
"number",
"of",
"fractional",
"decimal",
"places",
".",
"Optionally",
"repeating",
"integer",
"arguments",
"can",
"be",
"passed",
"each",
"indicating",
"the",
"size",
"of",
"an",
"additional",
"group",
"of",
"fractional",
"decimal",
"places",
"to",
"be",
"used",
"as",
"necessary",
"to",
"avoid",
"rounding",
"to",
"a",
"limiting",
"precision",
"of",
"satoshis",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L1008-L1010 |
23,489 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.getMicroInstance | public static BtcFormat getMicroInstance(int scale, int... groups) {
return getInstance(MICROCOIN_SCALE, defaultLocale(), scale, boxAsList(groups));
} | java | public static BtcFormat getMicroInstance(int scale, int... groups) {
return getInstance(MICROCOIN_SCALE, defaultLocale(), scale, boxAsList(groups));
} | [
"public",
"static",
"BtcFormat",
"getMicroInstance",
"(",
"int",
"scale",
",",
"int",
"...",
"groups",
")",
"{",
"return",
"getInstance",
"(",
"MICROCOIN_SCALE",
",",
"defaultLocale",
"(",
")",
",",
"scale",
",",
"boxAsList",
"(",
"groups",
")",
")",
";",
"}"
] | Return a new microcoin-denominated formatter with the specified fractional decimal
placing. The returned object will format and parse values according to the default
locale, and will format the fractional part of numbers with the given minimum number of
fractional decimal places. Optionally, repeating integer arguments can be passed, each
indicating the size of an additional group of fractional decimal places to be used as
necessary to avoid rounding, to a limiting precision of satoshis. | [
"Return",
"a",
"new",
"microcoin",
"-",
"denominated",
"formatter",
"with",
"the",
"specified",
"fractional",
"decimal",
"placing",
".",
"The",
"returned",
"object",
"will",
"format",
"and",
"parse",
"values",
"according",
"to",
"the",
"default",
"locale",
"and",
"will",
"format",
"the",
"fractional",
"part",
"of",
"numbers",
"with",
"the",
"given",
"minimum",
"number",
"of",
"fractional",
"decimal",
"places",
".",
"Optionally",
"repeating",
"integer",
"arguments",
"can",
"be",
"passed",
"each",
"indicating",
"the",
"size",
"of",
"an",
"additional",
"group",
"of",
"fractional",
"decimal",
"places",
"to",
"be",
"used",
"as",
"necessary",
"to",
"avoid",
"rounding",
"to",
"a",
"limiting",
"precision",
"of",
"satoshis",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L1036-L1038 |
23,490 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.getMicroInstance | public static BtcFormat getMicroInstance(Locale locale, int scale, int... groups) {
return getInstance(MICROCOIN_SCALE, locale, scale, boxAsList(groups));
} | java | public static BtcFormat getMicroInstance(Locale locale, int scale, int... groups) {
return getInstance(MICROCOIN_SCALE, locale, scale, boxAsList(groups));
} | [
"public",
"static",
"BtcFormat",
"getMicroInstance",
"(",
"Locale",
"locale",
",",
"int",
"scale",
",",
"int",
"...",
"groups",
")",
"{",
"return",
"getInstance",
"(",
"MICROCOIN_SCALE",
",",
"locale",
",",
"scale",
",",
"boxAsList",
"(",
"groups",
")",
")",
";",
"}"
] | Return a new microcoin-denominated formatter for the given locale with the specified
fractional decimal placing. The returned object will format the fractional part of
numbers with the given minimum number of fractional decimal places. Optionally,
repeating integer arguments can be passed, each indicating the size of an additional
group of fractional decimal places to be used as necessary to avoid rounding, to a
limiting precision of satoshis. | [
"Return",
"a",
"new",
"microcoin",
"-",
"denominated",
"formatter",
"for",
"the",
"given",
"locale",
"with",
"the",
"specified",
"fractional",
"decimal",
"placing",
".",
"The",
"returned",
"object",
"will",
"format",
"the",
"fractional",
"part",
"of",
"numbers",
"with",
"the",
"given",
"minimum",
"number",
"of",
"fractional",
"decimal",
"places",
".",
"Optionally",
"repeating",
"integer",
"arguments",
"can",
"be",
"passed",
"each",
"indicating",
"the",
"size",
"of",
"an",
"additional",
"group",
"of",
"fractional",
"decimal",
"places",
"to",
"be",
"used",
"as",
"necessary",
"to",
"avoid",
"rounding",
"to",
"a",
"limiting",
"precision",
"of",
"satoshis",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L1048-L1050 |
23,491 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.getInstance | public static BtcFormat getInstance(int scale, int minDecimals, int... groups) {
return getInstance(scale, defaultLocale(), minDecimals, boxAsList(groups));
} | java | public static BtcFormat getInstance(int scale, int minDecimals, int... groups) {
return getInstance(scale, defaultLocale(), minDecimals, boxAsList(groups));
} | [
"public",
"static",
"BtcFormat",
"getInstance",
"(",
"int",
"scale",
",",
"int",
"minDecimals",
",",
"int",
"...",
"groups",
")",
"{",
"return",
"getInstance",
"(",
"scale",
",",
"defaultLocale",
"(",
")",
",",
"minDecimals",
",",
"boxAsList",
"(",
"groups",
")",
")",
";",
"}"
] | Return a new fixed-denomination formatter with the specified fractional decimal
placing. The first argument specifies the denomination as the size of the
shift from coin-denomination in increasingly-precise decimal places. The returned object will format
and parse values according to the default locale, and will format the fractional part of
numbers with the given minimum number of fractional decimal places. Optionally,
repeating integer arguments can be passed, each indicating the size of an additional
group of fractional decimal places to be used as necessary to avoid rounding, to a
limiting precision of satoshis. | [
"Return",
"a",
"new",
"fixed",
"-",
"denomination",
"formatter",
"with",
"the",
"specified",
"fractional",
"decimal",
"placing",
".",
"The",
"first",
"argument",
"specifies",
"the",
"denomination",
"as",
"the",
"size",
"of",
"the",
"shift",
"from",
"coin",
"-",
"denomination",
"in",
"increasingly",
"-",
"precise",
"decimal",
"places",
".",
"The",
"returned",
"object",
"will",
"format",
"and",
"parse",
"values",
"according",
"to",
"the",
"default",
"locale",
"and",
"will",
"format",
"the",
"fractional",
"part",
"of",
"numbers",
"with",
"the",
"given",
"minimum",
"number",
"of",
"fractional",
"decimal",
"places",
".",
"Optionally",
"repeating",
"integer",
"arguments",
"can",
"be",
"passed",
"each",
"indicating",
"the",
"size",
"of",
"an",
"additional",
"group",
"of",
"fractional",
"decimal",
"places",
"to",
"be",
"used",
"as",
"necessary",
"to",
"avoid",
"rounding",
"to",
"a",
"limiting",
"precision",
"of",
"satoshis",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L1062-L1064 |
23,492 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.getInstance | public static BtcFormat getInstance(int scale, Locale locale, int minDecimals, int... groups) {
return getInstance(scale, locale, minDecimals, boxAsList(groups));
} | java | public static BtcFormat getInstance(int scale, Locale locale, int minDecimals, int... groups) {
return getInstance(scale, locale, minDecimals, boxAsList(groups));
} | [
"public",
"static",
"BtcFormat",
"getInstance",
"(",
"int",
"scale",
",",
"Locale",
"locale",
",",
"int",
"minDecimals",
",",
"int",
"...",
"groups",
")",
"{",
"return",
"getInstance",
"(",
"scale",
",",
"locale",
",",
"minDecimals",
",",
"boxAsList",
"(",
"groups",
")",
")",
";",
"}"
] | Return a new fixed-denomination formatter for the given locale, with the specified
fractional decimal placing. The first argument specifies the denomination as the size
of the shift from coin-denomination in increasingly-precise decimal places. The third
parameter is the minimum number of fractional decimal places to use, followed by
optional repeating integer parameters each specifying the size of an additional group of
fractional decimal places to use as necessary to avoid rounding, down to a maximum
precision of satoshis. | [
"Return",
"a",
"new",
"fixed",
"-",
"denomination",
"formatter",
"for",
"the",
"given",
"locale",
"with",
"the",
"specified",
"fractional",
"decimal",
"placing",
".",
"The",
"first",
"argument",
"specifies",
"the",
"denomination",
"as",
"the",
"size",
"of",
"the",
"shift",
"from",
"coin",
"-",
"denomination",
"in",
"increasingly",
"-",
"precise",
"decimal",
"places",
".",
"The",
"third",
"parameter",
"is",
"the",
"minimum",
"number",
"of",
"fractional",
"decimal",
"places",
"to",
"use",
"followed",
"by",
"optional",
"repeating",
"integer",
"parameters",
"each",
"specifying",
"the",
"size",
"of",
"an",
"additional",
"group",
"of",
"fractional",
"decimal",
"places",
"to",
"use",
"as",
"necessary",
"to",
"avoid",
"rounding",
"down",
"to",
"a",
"maximum",
"precision",
"of",
"satoshis",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L1098-L1100 |
23,493 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.setFormatterDigits | private static ImmutableList<Integer> setFormatterDigits(DecimalFormat formatter, int min, int max) {
ImmutableList<Integer> ante = ImmutableList.of(
formatter.getMinimumFractionDigits(),
formatter.getMaximumFractionDigits()
);
formatter.setMinimumFractionDigits(min);
formatter.setMaximumFractionDigits(max);
return ante;
} | java | private static ImmutableList<Integer> setFormatterDigits(DecimalFormat formatter, int min, int max) {
ImmutableList<Integer> ante = ImmutableList.of(
formatter.getMinimumFractionDigits(),
formatter.getMaximumFractionDigits()
);
formatter.setMinimumFractionDigits(min);
formatter.setMaximumFractionDigits(max);
return ante;
} | [
"private",
"static",
"ImmutableList",
"<",
"Integer",
">",
"setFormatterDigits",
"(",
"DecimalFormat",
"formatter",
",",
"int",
"min",
",",
"int",
"max",
")",
"{",
"ImmutableList",
"<",
"Integer",
">",
"ante",
"=",
"ImmutableList",
".",
"of",
"(",
"formatter",
".",
"getMinimumFractionDigits",
"(",
")",
",",
"formatter",
".",
"getMaximumFractionDigits",
"(",
")",
")",
";",
"formatter",
".",
"setMinimumFractionDigits",
"(",
"min",
")",
";",
"formatter",
".",
"setMaximumFractionDigits",
"(",
"max",
")",
";",
"return",
"ante",
";",
"}"
] | Sets the number of fractional decimal places to be displayed on the given
NumberFormat object to the value of the given integer.
@return The minimum and maximum fractional places settings that the
formatter had before this change, as an ImmutableList. | [
"Sets",
"the",
"number",
"of",
"fractional",
"decimal",
"places",
"to",
"be",
"displayed",
"on",
"the",
"given",
"NumberFormat",
"object",
"to",
"the",
"value",
"of",
"the",
"given",
"integer",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L1239-L1247 |
23,494 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.calculateFractionPlaces | private static int calculateFractionPlaces(
BigDecimal unitCount, int scale, int minDecimals, List<Integer> fractionGroups)
{
/* Taking into account BOTH the user's preference for decimal-place groups, AND the prohibition
* against displaying a fractional number of satoshis, determine the maximum possible number of
* fractional decimal places. */
int places = minDecimals;
for (int group : fractionGroups) { places += group; }
int max = Math.min(places, offSatoshis(scale));
places = Math.min(minDecimals,max);
for (int group : fractionGroups) {
/* Compare the value formatted using only this many decimal places to the
* same value using as many places as possible. If there's no difference, then
* there's no reason to continue adding more places. */
if (unitCount.setScale(places, HALF_UP).compareTo(unitCount.setScale(max, HALF_UP)) == 0) break;
places += group;
if (places > max) places = max;
}
return places;
} | java | private static int calculateFractionPlaces(
BigDecimal unitCount, int scale, int minDecimals, List<Integer> fractionGroups)
{
/* Taking into account BOTH the user's preference for decimal-place groups, AND the prohibition
* against displaying a fractional number of satoshis, determine the maximum possible number of
* fractional decimal places. */
int places = minDecimals;
for (int group : fractionGroups) { places += group; }
int max = Math.min(places, offSatoshis(scale));
places = Math.min(minDecimals,max);
for (int group : fractionGroups) {
/* Compare the value formatted using only this many decimal places to the
* same value using as many places as possible. If there's no difference, then
* there's no reason to continue adding more places. */
if (unitCount.setScale(places, HALF_UP).compareTo(unitCount.setScale(max, HALF_UP)) == 0) break;
places += group;
if (places > max) places = max;
}
return places;
} | [
"private",
"static",
"int",
"calculateFractionPlaces",
"(",
"BigDecimal",
"unitCount",
",",
"int",
"scale",
",",
"int",
"minDecimals",
",",
"List",
"<",
"Integer",
">",
"fractionGroups",
")",
"{",
"/* Taking into account BOTH the user's preference for decimal-place groups, AND the prohibition\n * against displaying a fractional number of satoshis, determine the maximum possible number of\n * fractional decimal places. */",
"int",
"places",
"=",
"minDecimals",
";",
"for",
"(",
"int",
"group",
":",
"fractionGroups",
")",
"{",
"places",
"+=",
"group",
";",
"}",
"int",
"max",
"=",
"Math",
".",
"min",
"(",
"places",
",",
"offSatoshis",
"(",
"scale",
")",
")",
";",
"places",
"=",
"Math",
".",
"min",
"(",
"minDecimals",
",",
"max",
")",
";",
"for",
"(",
"int",
"group",
":",
"fractionGroups",
")",
"{",
"/* Compare the value formatted using only this many decimal places to the\n * same value using as many places as possible. If there's no difference, then\n * there's no reason to continue adding more places. */",
"if",
"(",
"unitCount",
".",
"setScale",
"(",
"places",
",",
"HALF_UP",
")",
".",
"compareTo",
"(",
"unitCount",
".",
"setScale",
"(",
"max",
",",
"HALF_UP",
")",
")",
"==",
"0",
")",
"break",
";",
"places",
"+=",
"group",
";",
"if",
"(",
"places",
">",
"max",
")",
"places",
"=",
"max",
";",
"}",
"return",
"places",
";",
"}"
] | Return the number of fractional decimal places to be displayed when formatting
the given number of monetary units of the denomination indicated by the given decimal scale value,
where 0 = coin, 3 = millicoin, and so on.
@param unitCount the number of monetary units to be formatted
@param scale the denomination of those units as the decimal-place shift from coins
@param minDecimals the minimum number of fractional decimal places
@param fractionGroups the sizes of option fractional decimal-place groups | [
"Return",
"the",
"number",
"of",
"fractional",
"decimal",
"places",
"to",
"be",
"displayed",
"when",
"formatting",
"the",
"given",
"number",
"of",
"monetary",
"units",
"of",
"the",
"denomination",
"indicated",
"by",
"the",
"given",
"decimal",
"scale",
"value",
"where",
"0",
"=",
"coin",
"3",
"=",
"millicoin",
"and",
"so",
"on",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L1258-L1278 |
23,495 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.inSatoshis | private static BigInteger inSatoshis(Object qty) {
BigInteger satoshis;
// the value might be bitcoins or satoshis
if (qty instanceof Long || qty instanceof Integer)
satoshis = BigInteger.valueOf(((Number)qty).longValue());
else if (qty instanceof BigInteger)
satoshis = (BigInteger)qty;
else if (qty instanceof BigDecimal)
satoshis = ((BigDecimal)qty).movePointRight(Coin.SMALLEST_UNIT_EXPONENT).
setScale(0,BigDecimal.ROUND_HALF_UP).unscaledValue();
else if (qty instanceof Coin)
satoshis = BigInteger.valueOf(((Coin)qty).value);
else
throw new IllegalArgumentException("Cannot format a " + qty.getClass().getSimpleName() +
" as a Bicoin value");
return satoshis;
} | java | private static BigInteger inSatoshis(Object qty) {
BigInteger satoshis;
// the value might be bitcoins or satoshis
if (qty instanceof Long || qty instanceof Integer)
satoshis = BigInteger.valueOf(((Number)qty).longValue());
else if (qty instanceof BigInteger)
satoshis = (BigInteger)qty;
else if (qty instanceof BigDecimal)
satoshis = ((BigDecimal)qty).movePointRight(Coin.SMALLEST_UNIT_EXPONENT).
setScale(0,BigDecimal.ROUND_HALF_UP).unscaledValue();
else if (qty instanceof Coin)
satoshis = BigInteger.valueOf(((Coin)qty).value);
else
throw new IllegalArgumentException("Cannot format a " + qty.getClass().getSimpleName() +
" as a Bicoin value");
return satoshis;
} | [
"private",
"static",
"BigInteger",
"inSatoshis",
"(",
"Object",
"qty",
")",
"{",
"BigInteger",
"satoshis",
";",
"// the value might be bitcoins or satoshis",
"if",
"(",
"qty",
"instanceof",
"Long",
"||",
"qty",
"instanceof",
"Integer",
")",
"satoshis",
"=",
"BigInteger",
".",
"valueOf",
"(",
"(",
"(",
"Number",
")",
"qty",
")",
".",
"longValue",
"(",
")",
")",
";",
"else",
"if",
"(",
"qty",
"instanceof",
"BigInteger",
")",
"satoshis",
"=",
"(",
"BigInteger",
")",
"qty",
";",
"else",
"if",
"(",
"qty",
"instanceof",
"BigDecimal",
")",
"satoshis",
"=",
"(",
"(",
"BigDecimal",
")",
"qty",
")",
".",
"movePointRight",
"(",
"Coin",
".",
"SMALLEST_UNIT_EXPONENT",
")",
".",
"setScale",
"(",
"0",
",",
"BigDecimal",
".",
"ROUND_HALF_UP",
")",
".",
"unscaledValue",
"(",
")",
";",
"else",
"if",
"(",
"qty",
"instanceof",
"Coin",
")",
"satoshis",
"=",
"BigInteger",
".",
"valueOf",
"(",
"(",
"(",
"Coin",
")",
"qty",
")",
".",
"value",
")",
";",
"else",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Cannot format a \"",
"+",
"qty",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
"+",
"\" as a Bicoin value\"",
")",
";",
"return",
"satoshis",
";",
"}"
] | Takes an object representing a bitcoin quantity of any type the
client is permitted to pass us, and return a BigInteger representing the
number of satoshis having the equivalent value. | [
"Takes",
"an",
"object",
"representing",
"a",
"bitcoin",
"quantity",
"of",
"any",
"type",
"the",
"client",
"is",
"permitted",
"to",
"pass",
"us",
"and",
"return",
"a",
"BigInteger",
"representing",
"the",
"number",
"of",
"satoshis",
"having",
"the",
"equivalent",
"value",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L1284-L1300 |
23,496 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.prefixUnitsIndicator | protected static void prefixUnitsIndicator(DecimalFormat numberFormat, int scale) {
checkState(Thread.holdsLock(numberFormat)); // make sure caller intends to reset before changing
DecimalFormatSymbols fs = numberFormat.getDecimalFormatSymbols();
setSymbolAndCode(numberFormat,
prefixSymbol(fs.getCurrencySymbol(), scale), prefixCode(fs.getInternationalCurrencySymbol(), scale)
);
} | java | protected static void prefixUnitsIndicator(DecimalFormat numberFormat, int scale) {
checkState(Thread.holdsLock(numberFormat)); // make sure caller intends to reset before changing
DecimalFormatSymbols fs = numberFormat.getDecimalFormatSymbols();
setSymbolAndCode(numberFormat,
prefixSymbol(fs.getCurrencySymbol(), scale), prefixCode(fs.getInternationalCurrencySymbol(), scale)
);
} | [
"protected",
"static",
"void",
"prefixUnitsIndicator",
"(",
"DecimalFormat",
"numberFormat",
",",
"int",
"scale",
")",
"{",
"checkState",
"(",
"Thread",
".",
"holdsLock",
"(",
"numberFormat",
")",
")",
";",
"// make sure caller intends to reset before changing",
"DecimalFormatSymbols",
"fs",
"=",
"numberFormat",
".",
"getDecimalFormatSymbols",
"(",
")",
";",
"setSymbolAndCode",
"(",
"numberFormat",
",",
"prefixSymbol",
"(",
"fs",
".",
"getCurrencySymbol",
"(",
")",
",",
"scale",
")",
",",
"prefixCode",
"(",
"fs",
".",
"getInternationalCurrencySymbol",
"(",
")",
",",
"scale",
")",
")",
";",
"}"
] | Set both the currency symbol and code of the underlying, mutable NumberFormat object
according to the given denominational units scale factor. This is for formatting, not parsing.
<p>Set back to zero when you're done formatting otherwise immutability, equals() and
hashCode() will break!
@param scale Number of places the decimal point will be shifted when formatting
a quantity of satoshis. | [
"Set",
"both",
"the",
"currency",
"symbol",
"and",
"code",
"of",
"the",
"underlying",
"mutable",
"NumberFormat",
"object",
"according",
"to",
"the",
"given",
"denominational",
"units",
"scale",
"factor",
".",
"This",
"is",
"for",
"formatting",
"not",
"parsing",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L1384-L1390 |
23,497 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BtcFormat.java | BtcFormat.negify | protected static String negify(String pattern) {
if (pattern.contains(";")) return pattern;
else {
if (pattern.contains("-"))
throw new IllegalStateException("Positive pattern contains negative sign");
// the regex matches everything until the first non-quoted number character
return pattern + ";" + pattern.replaceFirst("^([^#0,.']*('[^']*')?)*", "$0-");
}
} | java | protected static String negify(String pattern) {
if (pattern.contains(";")) return pattern;
else {
if (pattern.contains("-"))
throw new IllegalStateException("Positive pattern contains negative sign");
// the regex matches everything until the first non-quoted number character
return pattern + ";" + pattern.replaceFirst("^([^#0,.']*('[^']*')?)*", "$0-");
}
} | [
"protected",
"static",
"String",
"negify",
"(",
"String",
"pattern",
")",
"{",
"if",
"(",
"pattern",
".",
"contains",
"(",
"\";\"",
")",
")",
"return",
"pattern",
";",
"else",
"{",
"if",
"(",
"pattern",
".",
"contains",
"(",
"\"-\"",
")",
")",
"throw",
"new",
"IllegalStateException",
"(",
"\"Positive pattern contains negative sign\"",
")",
";",
"// the regex matches everything until the first non-quoted number character",
"return",
"pattern",
"+",
"\";\"",
"+",
"pattern",
".",
"replaceFirst",
"(",
"\"^([^#0,.']*('[^']*')?)*\"",
",",
"\"$0-\"",
")",
";",
"}",
"}"
] | Guarantee a formatting pattern has a subpattern for negative values. This method takes
a pattern that may be missing a negative subpattern, and returns the same pattern with
a negative subpattern appended as needed.
<p>This method accommodates an imperfection in the Java formatting code and distributed
locale data. To wit: the subpattern for negative numbers is optional and not all
locales have one. In those cases, {@link DecimalFormat} will indicate numbers
less than zero by adding a negative sign as the first character of the prefix of the
positive subpattern.
<p>We don't like this, since we claim the negative sign applies to the number not the
units, and therefore it ought to be adjacent to the number, displacing the
currency-units indicator if necessary. | [
"Guarantee",
"a",
"formatting",
"pattern",
"has",
"a",
"subpattern",
"for",
"negative",
"values",
".",
"This",
"method",
"takes",
"a",
"pattern",
"that",
"may",
"be",
"missing",
"a",
"negative",
"subpattern",
"and",
"returns",
"the",
"same",
"pattern",
"with",
"a",
"negative",
"subpattern",
"appended",
"as",
"needed",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BtcFormat.java#L1512-L1520 |
23,498 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/StoredServerChannel.java | StoredServerChannel.setConnectedHandler | synchronized PaymentChannelServer setConnectedHandler(PaymentChannelServer connectedHandler, boolean override) {
if (this.connectedHandler != null && !override)
return this.connectedHandler;
this.connectedHandler = connectedHandler;
return connectedHandler;
} | java | synchronized PaymentChannelServer setConnectedHandler(PaymentChannelServer connectedHandler, boolean override) {
if (this.connectedHandler != null && !override)
return this.connectedHandler;
this.connectedHandler = connectedHandler;
return connectedHandler;
} | [
"synchronized",
"PaymentChannelServer",
"setConnectedHandler",
"(",
"PaymentChannelServer",
"connectedHandler",
",",
"boolean",
"override",
")",
"{",
"if",
"(",
"this",
".",
"connectedHandler",
"!=",
"null",
"&&",
"!",
"override",
")",
"return",
"this",
".",
"connectedHandler",
";",
"this",
".",
"connectedHandler",
"=",
"connectedHandler",
";",
"return",
"connectedHandler",
";",
"}"
] | Attempts to connect the given handler to this, returning true if it is the new handler, false if there was
already one attached. | [
"Attempts",
"to",
"connect",
"the",
"given",
"handler",
"to",
"this",
"returning",
"true",
"if",
"it",
"is",
"the",
"new",
"handler",
"false",
"if",
"there",
"was",
"already",
"one",
"attached",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/StoredServerChannel.java#L78-L83 |
23,499 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/DefaultRiskAnalysis.java | DefaultRiskAnalysis.isOutputStandard | public static RuleViolation isOutputStandard(TransactionOutput output) {
if (output.getValue().compareTo(MIN_ANALYSIS_NONDUST_OUTPUT) < 0)
return RuleViolation.DUST;
for (ScriptChunk chunk : output.getScriptPubKey().getChunks()) {
if (chunk.isPushData() && !chunk.isShortestPossiblePushData())
return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
}
return RuleViolation.NONE;
} | java | public static RuleViolation isOutputStandard(TransactionOutput output) {
if (output.getValue().compareTo(MIN_ANALYSIS_NONDUST_OUTPUT) < 0)
return RuleViolation.DUST;
for (ScriptChunk chunk : output.getScriptPubKey().getChunks()) {
if (chunk.isPushData() && !chunk.isShortestPossiblePushData())
return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
}
return RuleViolation.NONE;
} | [
"public",
"static",
"RuleViolation",
"isOutputStandard",
"(",
"TransactionOutput",
"output",
")",
"{",
"if",
"(",
"output",
".",
"getValue",
"(",
")",
".",
"compareTo",
"(",
"MIN_ANALYSIS_NONDUST_OUTPUT",
")",
"<",
"0",
")",
"return",
"RuleViolation",
".",
"DUST",
";",
"for",
"(",
"ScriptChunk",
"chunk",
":",
"output",
".",
"getScriptPubKey",
"(",
")",
".",
"getChunks",
"(",
")",
")",
"{",
"if",
"(",
"chunk",
".",
"isPushData",
"(",
")",
"&&",
"!",
"chunk",
".",
"isShortestPossiblePushData",
"(",
")",
")",
"return",
"RuleViolation",
".",
"SHORTEST_POSSIBLE_PUSHDATA",
";",
"}",
"return",
"RuleViolation",
".",
"NONE",
";",
"}"
] | Checks the output to see if the script violates a standardness rule. Not complete. | [
"Checks",
"the",
"output",
"to",
"see",
"if",
"the",
"script",
"violates",
"a",
"standardness",
"rule",
".",
"Not",
"complete",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/DefaultRiskAnalysis.java#L175-L183 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.