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,300 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/ExchangeRate.java | ExchangeRate.fiatToCoin | public Coin fiatToCoin(Fiat convertFiat) {
checkArgument(convertFiat.currencyCode.equals(fiat.currencyCode), "Currency mismatch: %s vs %s",
convertFiat.currencyCode, fiat.currencyCode);
// Use BigInteger because it's much easier to maintain full precision without overflowing.
final BigInteger converted = BigInteger.valueOf(convertFiat.value).multiply(BigInteger.valueOf(coin.value))
.divide(BigInteger.valueOf(fiat.value));
if (converted.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0
|| converted.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0)
throw new ArithmeticException("Overflow");
try {
return Coin.valueOf(converted.longValue());
} catch (IllegalArgumentException x) {
throw new ArithmeticException("Overflow: " + x.getMessage());
}
} | java | public Coin fiatToCoin(Fiat convertFiat) {
checkArgument(convertFiat.currencyCode.equals(fiat.currencyCode), "Currency mismatch: %s vs %s",
convertFiat.currencyCode, fiat.currencyCode);
// Use BigInteger because it's much easier to maintain full precision without overflowing.
final BigInteger converted = BigInteger.valueOf(convertFiat.value).multiply(BigInteger.valueOf(coin.value))
.divide(BigInteger.valueOf(fiat.value));
if (converted.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0
|| converted.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0)
throw new ArithmeticException("Overflow");
try {
return Coin.valueOf(converted.longValue());
} catch (IllegalArgumentException x) {
throw new ArithmeticException("Overflow: " + x.getMessage());
}
} | [
"public",
"Coin",
"fiatToCoin",
"(",
"Fiat",
"convertFiat",
")",
"{",
"checkArgument",
"(",
"convertFiat",
".",
"currencyCode",
".",
"equals",
"(",
"fiat",
".",
"currencyCode",
")",
",",
"\"Currency mismatch: %s vs %s\"",
",",
"convertFiat",
".",
"currencyCode",
",",
"fiat",
".",
"currencyCode",
")",
";",
"// Use BigInteger because it's much easier to maintain full precision without overflowing.",
"final",
"BigInteger",
"converted",
"=",
"BigInteger",
".",
"valueOf",
"(",
"convertFiat",
".",
"value",
")",
".",
"multiply",
"(",
"BigInteger",
".",
"valueOf",
"(",
"coin",
".",
"value",
")",
")",
".",
"divide",
"(",
"BigInteger",
".",
"valueOf",
"(",
"fiat",
".",
"value",
")",
")",
";",
"if",
"(",
"converted",
".",
"compareTo",
"(",
"BigInteger",
".",
"valueOf",
"(",
"Long",
".",
"MAX_VALUE",
")",
")",
">",
"0",
"||",
"converted",
".",
"compareTo",
"(",
"BigInteger",
".",
"valueOf",
"(",
"Long",
".",
"MIN_VALUE",
")",
")",
"<",
"0",
")",
"throw",
"new",
"ArithmeticException",
"(",
"\"Overflow\"",
")",
";",
"try",
"{",
"return",
"Coin",
".",
"valueOf",
"(",
"converted",
".",
"longValue",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"x",
")",
"{",
"throw",
"new",
"ArithmeticException",
"(",
"\"Overflow: \"",
"+",
"x",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | Convert a fiat amount to a coin amount using this exchange rate.
@throws ArithmeticException if the converted coin amount is too high or too low. | [
"Convert",
"a",
"fiat",
"amount",
"to",
"a",
"coin",
"amount",
"using",
"this",
"exchange",
"rate",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/ExchangeRate.java#L68-L82 |
23,301 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/BIP38PrivateKey.java | BIP38PrivateKey.fromBase58 | public static BIP38PrivateKey fromBase58(NetworkParameters params, String base58) throws AddressFormatException {
byte[] versionAndDataBytes = Base58.decodeChecked(base58);
int version = versionAndDataBytes[0] & 0xFF;
byte[] bytes = Arrays.copyOfRange(versionAndDataBytes, 1, versionAndDataBytes.length);
if (version != 0x01)
throw new AddressFormatException.InvalidPrefix("Mismatched version number: " + version);
if (bytes.length != 38)
throw new AddressFormatException.InvalidDataLength("Wrong number of bytes: " + bytes.length);
boolean hasLotAndSequence = (bytes[1] & 0x04) != 0; // bit 2
boolean compressed = (bytes[1] & 0x20) != 0; // bit 5
if ((bytes[1] & 0x01) != 0) // bit 0
throw new AddressFormatException("Bit 0x01 reserved for future use.");
if ((bytes[1] & 0x02) != 0) // bit 1
throw new AddressFormatException("Bit 0x02 reserved for future use.");
if ((bytes[1] & 0x08) != 0) // bit 3
throw new AddressFormatException("Bit 0x08 reserved for future use.");
if ((bytes[1] & 0x10) != 0) // bit 4
throw new AddressFormatException("Bit 0x10 reserved for future use.");
final int byte0 = bytes[0] & 0xff;
final boolean ecMultiply;
if (byte0 == 0x42) {
// Non-EC-multiplied key
if ((bytes[1] & 0xc0) != 0xc0) // bits 6+7
throw new AddressFormatException("Bits 0x40 and 0x80 must be set for non-EC-multiplied keys.");
ecMultiply = false;
if (hasLotAndSequence)
throw new AddressFormatException("Non-EC-multiplied keys cannot have lot/sequence.");
} else if (byte0 == 0x43) {
// EC-multiplied key
if ((bytes[1] & 0xc0) != 0x00) // bits 6+7
throw new AddressFormatException("Bits 0x40 and 0x80 must be cleared for EC-multiplied keys.");
ecMultiply = true;
} else {
throw new AddressFormatException("Second byte must by 0x42 or 0x43.");
}
byte[] addressHash = Arrays.copyOfRange(bytes, 2, 6);
byte[] content = Arrays.copyOfRange(bytes, 6, 38);
return new BIP38PrivateKey(params, bytes, ecMultiply, compressed, hasLotAndSequence, addressHash, content);
} | java | public static BIP38PrivateKey fromBase58(NetworkParameters params, String base58) throws AddressFormatException {
byte[] versionAndDataBytes = Base58.decodeChecked(base58);
int version = versionAndDataBytes[0] & 0xFF;
byte[] bytes = Arrays.copyOfRange(versionAndDataBytes, 1, versionAndDataBytes.length);
if (version != 0x01)
throw new AddressFormatException.InvalidPrefix("Mismatched version number: " + version);
if (bytes.length != 38)
throw new AddressFormatException.InvalidDataLength("Wrong number of bytes: " + bytes.length);
boolean hasLotAndSequence = (bytes[1] & 0x04) != 0; // bit 2
boolean compressed = (bytes[1] & 0x20) != 0; // bit 5
if ((bytes[1] & 0x01) != 0) // bit 0
throw new AddressFormatException("Bit 0x01 reserved for future use.");
if ((bytes[1] & 0x02) != 0) // bit 1
throw new AddressFormatException("Bit 0x02 reserved for future use.");
if ((bytes[1] & 0x08) != 0) // bit 3
throw new AddressFormatException("Bit 0x08 reserved for future use.");
if ((bytes[1] & 0x10) != 0) // bit 4
throw new AddressFormatException("Bit 0x10 reserved for future use.");
final int byte0 = bytes[0] & 0xff;
final boolean ecMultiply;
if (byte0 == 0x42) {
// Non-EC-multiplied key
if ((bytes[1] & 0xc0) != 0xc0) // bits 6+7
throw new AddressFormatException("Bits 0x40 and 0x80 must be set for non-EC-multiplied keys.");
ecMultiply = false;
if (hasLotAndSequence)
throw new AddressFormatException("Non-EC-multiplied keys cannot have lot/sequence.");
} else if (byte0 == 0x43) {
// EC-multiplied key
if ((bytes[1] & 0xc0) != 0x00) // bits 6+7
throw new AddressFormatException("Bits 0x40 and 0x80 must be cleared for EC-multiplied keys.");
ecMultiply = true;
} else {
throw new AddressFormatException("Second byte must by 0x42 or 0x43.");
}
byte[] addressHash = Arrays.copyOfRange(bytes, 2, 6);
byte[] content = Arrays.copyOfRange(bytes, 6, 38);
return new BIP38PrivateKey(params, bytes, ecMultiply, compressed, hasLotAndSequence, addressHash, content);
} | [
"public",
"static",
"BIP38PrivateKey",
"fromBase58",
"(",
"NetworkParameters",
"params",
",",
"String",
"base58",
")",
"throws",
"AddressFormatException",
"{",
"byte",
"[",
"]",
"versionAndDataBytes",
"=",
"Base58",
".",
"decodeChecked",
"(",
"base58",
")",
";",
"int",
"version",
"=",
"versionAndDataBytes",
"[",
"0",
"]",
"&",
"0xFF",
";",
"byte",
"[",
"]",
"bytes",
"=",
"Arrays",
".",
"copyOfRange",
"(",
"versionAndDataBytes",
",",
"1",
",",
"versionAndDataBytes",
".",
"length",
")",
";",
"if",
"(",
"version",
"!=",
"0x01",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidPrefix",
"(",
"\"Mismatched version number: \"",
"+",
"version",
")",
";",
"if",
"(",
"bytes",
".",
"length",
"!=",
"38",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidDataLength",
"(",
"\"Wrong number of bytes: \"",
"+",
"bytes",
".",
"length",
")",
";",
"boolean",
"hasLotAndSequence",
"=",
"(",
"bytes",
"[",
"1",
"]",
"&",
"0x04",
")",
"!=",
"0",
";",
"// bit 2",
"boolean",
"compressed",
"=",
"(",
"bytes",
"[",
"1",
"]",
"&",
"0x20",
")",
"!=",
"0",
";",
"// bit 5",
"if",
"(",
"(",
"bytes",
"[",
"1",
"]",
"&",
"0x01",
")",
"!=",
"0",
")",
"// bit 0",
"throw",
"new",
"AddressFormatException",
"(",
"\"Bit 0x01 reserved for future use.\"",
")",
";",
"if",
"(",
"(",
"bytes",
"[",
"1",
"]",
"&",
"0x02",
")",
"!=",
"0",
")",
"// bit 1",
"throw",
"new",
"AddressFormatException",
"(",
"\"Bit 0x02 reserved for future use.\"",
")",
";",
"if",
"(",
"(",
"bytes",
"[",
"1",
"]",
"&",
"0x08",
")",
"!=",
"0",
")",
"// bit 3",
"throw",
"new",
"AddressFormatException",
"(",
"\"Bit 0x08 reserved for future use.\"",
")",
";",
"if",
"(",
"(",
"bytes",
"[",
"1",
"]",
"&",
"0x10",
")",
"!=",
"0",
")",
"// bit 4",
"throw",
"new",
"AddressFormatException",
"(",
"\"Bit 0x10 reserved for future use.\"",
")",
";",
"final",
"int",
"byte0",
"=",
"bytes",
"[",
"0",
"]",
"&",
"0xff",
";",
"final",
"boolean",
"ecMultiply",
";",
"if",
"(",
"byte0",
"==",
"0x42",
")",
"{",
"// Non-EC-multiplied key",
"if",
"(",
"(",
"bytes",
"[",
"1",
"]",
"&",
"0xc0",
")",
"!=",
"0xc0",
")",
"// bits 6+7",
"throw",
"new",
"AddressFormatException",
"(",
"\"Bits 0x40 and 0x80 must be set for non-EC-multiplied keys.\"",
")",
";",
"ecMultiply",
"=",
"false",
";",
"if",
"(",
"hasLotAndSequence",
")",
"throw",
"new",
"AddressFormatException",
"(",
"\"Non-EC-multiplied keys cannot have lot/sequence.\"",
")",
";",
"}",
"else",
"if",
"(",
"byte0",
"==",
"0x43",
")",
"{",
"// EC-multiplied key",
"if",
"(",
"(",
"bytes",
"[",
"1",
"]",
"&",
"0xc0",
")",
"!=",
"0x00",
")",
"// bits 6+7",
"throw",
"new",
"AddressFormatException",
"(",
"\"Bits 0x40 and 0x80 must be cleared for EC-multiplied keys.\"",
")",
";",
"ecMultiply",
"=",
"true",
";",
"}",
"else",
"{",
"throw",
"new",
"AddressFormatException",
"(",
"\"Second byte must by 0x42 or 0x43.\"",
")",
";",
"}",
"byte",
"[",
"]",
"addressHash",
"=",
"Arrays",
".",
"copyOfRange",
"(",
"bytes",
",",
"2",
",",
"6",
")",
";",
"byte",
"[",
"]",
"content",
"=",
"Arrays",
".",
"copyOfRange",
"(",
"bytes",
",",
"6",
",",
"38",
")",
";",
"return",
"new",
"BIP38PrivateKey",
"(",
"params",
",",
"bytes",
",",
"ecMultiply",
",",
"compressed",
",",
"hasLotAndSequence",
",",
"addressHash",
",",
"content",
")",
";",
"}"
] | Construct a password-protected private key from its Base58 representation.
@param params
The network parameters of the chain that the key is for.
@param base58
The textual form of the password-protected private key.
@throws AddressFormatException
if the given base58 doesn't parse or the checksum is invalid | [
"Construct",
"a",
"password",
"-",
"protected",
"private",
"key",
"from",
"its",
"Base58",
"representation",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/BIP38PrivateKey.java#L57-L96 |
23,302 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/MarriedKeyChain.java | MarriedKeyChain.freshOutputScript | @Override
public Script freshOutputScript(KeyPurpose purpose) {
DeterministicKey followedKey = getKey(purpose);
ImmutableList.Builder<ECKey> keys = ImmutableList.<ECKey>builder().add(followedKey);
for (DeterministicKeyChain keyChain : followingKeyChains) {
DeterministicKey followingKey = keyChain.getKey(purpose);
checkState(followedKey.getChildNumber().equals(followingKey.getChildNumber()), "Following keychains should be in sync");
keys.add(followingKey);
}
List<ECKey> marriedKeys = keys.build();
Script redeemScript = ScriptBuilder.createRedeemScript(sigsRequiredToSpend, marriedKeys);
return ScriptBuilder.createP2SHOutputScript(redeemScript);
} | java | @Override
public Script freshOutputScript(KeyPurpose purpose) {
DeterministicKey followedKey = getKey(purpose);
ImmutableList.Builder<ECKey> keys = ImmutableList.<ECKey>builder().add(followedKey);
for (DeterministicKeyChain keyChain : followingKeyChains) {
DeterministicKey followingKey = keyChain.getKey(purpose);
checkState(followedKey.getChildNumber().equals(followingKey.getChildNumber()), "Following keychains should be in sync");
keys.add(followingKey);
}
List<ECKey> marriedKeys = keys.build();
Script redeemScript = ScriptBuilder.createRedeemScript(sigsRequiredToSpend, marriedKeys);
return ScriptBuilder.createP2SHOutputScript(redeemScript);
} | [
"@",
"Override",
"public",
"Script",
"freshOutputScript",
"(",
"KeyPurpose",
"purpose",
")",
"{",
"DeterministicKey",
"followedKey",
"=",
"getKey",
"(",
"purpose",
")",
";",
"ImmutableList",
".",
"Builder",
"<",
"ECKey",
">",
"keys",
"=",
"ImmutableList",
".",
"<",
"ECKey",
">",
"builder",
"(",
")",
".",
"add",
"(",
"followedKey",
")",
";",
"for",
"(",
"DeterministicKeyChain",
"keyChain",
":",
"followingKeyChains",
")",
"{",
"DeterministicKey",
"followingKey",
"=",
"keyChain",
".",
"getKey",
"(",
"purpose",
")",
";",
"checkState",
"(",
"followedKey",
".",
"getChildNumber",
"(",
")",
".",
"equals",
"(",
"followingKey",
".",
"getChildNumber",
"(",
")",
")",
",",
"\"Following keychains should be in sync\"",
")",
";",
"keys",
".",
"add",
"(",
"followingKey",
")",
";",
"}",
"List",
"<",
"ECKey",
">",
"marriedKeys",
"=",
"keys",
".",
"build",
"(",
")",
";",
"Script",
"redeemScript",
"=",
"ScriptBuilder",
".",
"createRedeemScript",
"(",
"sigsRequiredToSpend",
",",
"marriedKeys",
")",
";",
"return",
"ScriptBuilder",
".",
"createP2SHOutputScript",
"(",
"redeemScript",
")",
";",
"}"
] | Create a new married key and return the matching output script | [
"Create",
"a",
"new",
"married",
"key",
"and",
"return",
"the",
"matching",
"output",
"script"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/MarriedKeyChain.java#L151-L163 |
23,303 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/MarriedKeyChain.java | MarriedKeyChain.getRedeemData | @Override
public RedeemData getRedeemData(DeterministicKey followedKey) {
List<ECKey> marriedKeys = getMarriedKeysWithFollowed(followedKey);
Script redeemScript = ScriptBuilder.createRedeemScript(sigsRequiredToSpend, marriedKeys);
return RedeemData.of(marriedKeys, redeemScript);
} | java | @Override
public RedeemData getRedeemData(DeterministicKey followedKey) {
List<ECKey> marriedKeys = getMarriedKeysWithFollowed(followedKey);
Script redeemScript = ScriptBuilder.createRedeemScript(sigsRequiredToSpend, marriedKeys);
return RedeemData.of(marriedKeys, redeemScript);
} | [
"@",
"Override",
"public",
"RedeemData",
"getRedeemData",
"(",
"DeterministicKey",
"followedKey",
")",
"{",
"List",
"<",
"ECKey",
">",
"marriedKeys",
"=",
"getMarriedKeysWithFollowed",
"(",
"followedKey",
")",
";",
"Script",
"redeemScript",
"=",
"ScriptBuilder",
".",
"createRedeemScript",
"(",
"sigsRequiredToSpend",
",",
"marriedKeys",
")",
";",
"return",
"RedeemData",
".",
"of",
"(",
"marriedKeys",
",",
"redeemScript",
")",
";",
"}"
] | Get the redeem data for a key in this married chain | [
"Get",
"the",
"redeem",
"data",
"for",
"a",
"key",
"in",
"this",
"married",
"chain"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/MarriedKeyChain.java#L176-L181 |
23,304 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/WalletProtobufSerializer.java | WalletProtobufSerializer.walletToProto | public Protos.Wallet walletToProto(Wallet wallet) {
Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder();
walletBuilder.setNetworkIdentifier(wallet.getNetworkParameters().getId());
if (wallet.getDescription() != null) {
walletBuilder.setDescription(wallet.getDescription());
}
for (WalletTransaction wtx : wallet.getWalletTransactions()) {
Protos.Transaction txProto = makeTxProto(wtx);
walletBuilder.addTransaction(txProto);
}
walletBuilder.addAllKey(wallet.serializeKeyChainGroupToProtobuf());
for (Script script : wallet.getWatchedScripts()) {
Protos.Script protoScript =
Protos.Script.newBuilder()
.setProgram(ByteString.copyFrom(script.getProgram()))
.setCreationTimestamp(script.getCreationTimeSeconds() * 1000)
.build();
walletBuilder.addWatchedScript(protoScript);
}
// Populate the lastSeenBlockHash field.
Sha256Hash lastSeenBlockHash = wallet.getLastBlockSeenHash();
if (lastSeenBlockHash != null) {
walletBuilder.setLastSeenBlockHash(hashToByteString(lastSeenBlockHash));
walletBuilder.setLastSeenBlockHeight(wallet.getLastBlockSeenHeight());
}
if (wallet.getLastBlockSeenTimeSecs() > 0)
walletBuilder.setLastSeenBlockTimeSecs(wallet.getLastBlockSeenTimeSecs());
// Populate the scrypt parameters.
KeyCrypter keyCrypter = wallet.getKeyCrypter();
if (keyCrypter == null) {
// The wallet is unencrypted.
walletBuilder.setEncryptionType(EncryptionType.UNENCRYPTED);
} else {
// The wallet is encrypted.
walletBuilder.setEncryptionType(keyCrypter.getUnderstoodEncryptionType());
if (keyCrypter instanceof KeyCrypterScrypt) {
KeyCrypterScrypt keyCrypterScrypt = (KeyCrypterScrypt) keyCrypter;
walletBuilder.setEncryptionParameters(keyCrypterScrypt.getScryptParameters());
} else {
// Some other form of encryption has been specified that we do not know how to persist.
throw new RuntimeException("The wallet has encryption of type '" + keyCrypter.getUnderstoodEncryptionType() + "' but this WalletProtobufSerializer does not know how to persist this.");
}
}
if (wallet.getKeyRotationTime() != null) {
long timeSecs = wallet.getKeyRotationTime().getTime() / 1000;
walletBuilder.setKeyRotationTime(timeSecs);
}
populateExtensions(wallet, walletBuilder);
for (Map.Entry<String, ByteString> entry : wallet.getTags().entrySet()) {
Protos.Tag.Builder tag = Protos.Tag.newBuilder().setTag(entry.getKey()).setData(entry.getValue());
walletBuilder.addTags(tag);
}
// Populate the wallet version.
walletBuilder.setVersion(wallet.getVersion());
return walletBuilder.build();
} | java | public Protos.Wallet walletToProto(Wallet wallet) {
Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder();
walletBuilder.setNetworkIdentifier(wallet.getNetworkParameters().getId());
if (wallet.getDescription() != null) {
walletBuilder.setDescription(wallet.getDescription());
}
for (WalletTransaction wtx : wallet.getWalletTransactions()) {
Protos.Transaction txProto = makeTxProto(wtx);
walletBuilder.addTransaction(txProto);
}
walletBuilder.addAllKey(wallet.serializeKeyChainGroupToProtobuf());
for (Script script : wallet.getWatchedScripts()) {
Protos.Script protoScript =
Protos.Script.newBuilder()
.setProgram(ByteString.copyFrom(script.getProgram()))
.setCreationTimestamp(script.getCreationTimeSeconds() * 1000)
.build();
walletBuilder.addWatchedScript(protoScript);
}
// Populate the lastSeenBlockHash field.
Sha256Hash lastSeenBlockHash = wallet.getLastBlockSeenHash();
if (lastSeenBlockHash != null) {
walletBuilder.setLastSeenBlockHash(hashToByteString(lastSeenBlockHash));
walletBuilder.setLastSeenBlockHeight(wallet.getLastBlockSeenHeight());
}
if (wallet.getLastBlockSeenTimeSecs() > 0)
walletBuilder.setLastSeenBlockTimeSecs(wallet.getLastBlockSeenTimeSecs());
// Populate the scrypt parameters.
KeyCrypter keyCrypter = wallet.getKeyCrypter();
if (keyCrypter == null) {
// The wallet is unencrypted.
walletBuilder.setEncryptionType(EncryptionType.UNENCRYPTED);
} else {
// The wallet is encrypted.
walletBuilder.setEncryptionType(keyCrypter.getUnderstoodEncryptionType());
if (keyCrypter instanceof KeyCrypterScrypt) {
KeyCrypterScrypt keyCrypterScrypt = (KeyCrypterScrypt) keyCrypter;
walletBuilder.setEncryptionParameters(keyCrypterScrypt.getScryptParameters());
} else {
// Some other form of encryption has been specified that we do not know how to persist.
throw new RuntimeException("The wallet has encryption of type '" + keyCrypter.getUnderstoodEncryptionType() + "' but this WalletProtobufSerializer does not know how to persist this.");
}
}
if (wallet.getKeyRotationTime() != null) {
long timeSecs = wallet.getKeyRotationTime().getTime() / 1000;
walletBuilder.setKeyRotationTime(timeSecs);
}
populateExtensions(wallet, walletBuilder);
for (Map.Entry<String, ByteString> entry : wallet.getTags().entrySet()) {
Protos.Tag.Builder tag = Protos.Tag.newBuilder().setTag(entry.getKey()).setData(entry.getValue());
walletBuilder.addTags(tag);
}
// Populate the wallet version.
walletBuilder.setVersion(wallet.getVersion());
return walletBuilder.build();
} | [
"public",
"Protos",
".",
"Wallet",
"walletToProto",
"(",
"Wallet",
"wallet",
")",
"{",
"Protos",
".",
"Wallet",
".",
"Builder",
"walletBuilder",
"=",
"Protos",
".",
"Wallet",
".",
"newBuilder",
"(",
")",
";",
"walletBuilder",
".",
"setNetworkIdentifier",
"(",
"wallet",
".",
"getNetworkParameters",
"(",
")",
".",
"getId",
"(",
")",
")",
";",
"if",
"(",
"wallet",
".",
"getDescription",
"(",
")",
"!=",
"null",
")",
"{",
"walletBuilder",
".",
"setDescription",
"(",
"wallet",
".",
"getDescription",
"(",
")",
")",
";",
"}",
"for",
"(",
"WalletTransaction",
"wtx",
":",
"wallet",
".",
"getWalletTransactions",
"(",
")",
")",
"{",
"Protos",
".",
"Transaction",
"txProto",
"=",
"makeTxProto",
"(",
"wtx",
")",
";",
"walletBuilder",
".",
"addTransaction",
"(",
"txProto",
")",
";",
"}",
"walletBuilder",
".",
"addAllKey",
"(",
"wallet",
".",
"serializeKeyChainGroupToProtobuf",
"(",
")",
")",
";",
"for",
"(",
"Script",
"script",
":",
"wallet",
".",
"getWatchedScripts",
"(",
")",
")",
"{",
"Protos",
".",
"Script",
"protoScript",
"=",
"Protos",
".",
"Script",
".",
"newBuilder",
"(",
")",
".",
"setProgram",
"(",
"ByteString",
".",
"copyFrom",
"(",
"script",
".",
"getProgram",
"(",
")",
")",
")",
".",
"setCreationTimestamp",
"(",
"script",
".",
"getCreationTimeSeconds",
"(",
")",
"*",
"1000",
")",
".",
"build",
"(",
")",
";",
"walletBuilder",
".",
"addWatchedScript",
"(",
"protoScript",
")",
";",
"}",
"// Populate the lastSeenBlockHash field.",
"Sha256Hash",
"lastSeenBlockHash",
"=",
"wallet",
".",
"getLastBlockSeenHash",
"(",
")",
";",
"if",
"(",
"lastSeenBlockHash",
"!=",
"null",
")",
"{",
"walletBuilder",
".",
"setLastSeenBlockHash",
"(",
"hashToByteString",
"(",
"lastSeenBlockHash",
")",
")",
";",
"walletBuilder",
".",
"setLastSeenBlockHeight",
"(",
"wallet",
".",
"getLastBlockSeenHeight",
"(",
")",
")",
";",
"}",
"if",
"(",
"wallet",
".",
"getLastBlockSeenTimeSecs",
"(",
")",
">",
"0",
")",
"walletBuilder",
".",
"setLastSeenBlockTimeSecs",
"(",
"wallet",
".",
"getLastBlockSeenTimeSecs",
"(",
")",
")",
";",
"// Populate the scrypt parameters.",
"KeyCrypter",
"keyCrypter",
"=",
"wallet",
".",
"getKeyCrypter",
"(",
")",
";",
"if",
"(",
"keyCrypter",
"==",
"null",
")",
"{",
"// The wallet is unencrypted.",
"walletBuilder",
".",
"setEncryptionType",
"(",
"EncryptionType",
".",
"UNENCRYPTED",
")",
";",
"}",
"else",
"{",
"// The wallet is encrypted.",
"walletBuilder",
".",
"setEncryptionType",
"(",
"keyCrypter",
".",
"getUnderstoodEncryptionType",
"(",
")",
")",
";",
"if",
"(",
"keyCrypter",
"instanceof",
"KeyCrypterScrypt",
")",
"{",
"KeyCrypterScrypt",
"keyCrypterScrypt",
"=",
"(",
"KeyCrypterScrypt",
")",
"keyCrypter",
";",
"walletBuilder",
".",
"setEncryptionParameters",
"(",
"keyCrypterScrypt",
".",
"getScryptParameters",
"(",
")",
")",
";",
"}",
"else",
"{",
"// Some other form of encryption has been specified that we do not know how to persist.",
"throw",
"new",
"RuntimeException",
"(",
"\"The wallet has encryption of type '\"",
"+",
"keyCrypter",
".",
"getUnderstoodEncryptionType",
"(",
")",
"+",
"\"' but this WalletProtobufSerializer does not know how to persist this.\"",
")",
";",
"}",
"}",
"if",
"(",
"wallet",
".",
"getKeyRotationTime",
"(",
")",
"!=",
"null",
")",
"{",
"long",
"timeSecs",
"=",
"wallet",
".",
"getKeyRotationTime",
"(",
")",
".",
"getTime",
"(",
")",
"/",
"1000",
";",
"walletBuilder",
".",
"setKeyRotationTime",
"(",
"timeSecs",
")",
";",
"}",
"populateExtensions",
"(",
"wallet",
",",
"walletBuilder",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"ByteString",
">",
"entry",
":",
"wallet",
".",
"getTags",
"(",
")",
".",
"entrySet",
"(",
")",
")",
"{",
"Protos",
".",
"Tag",
".",
"Builder",
"tag",
"=",
"Protos",
".",
"Tag",
".",
"newBuilder",
"(",
")",
".",
"setTag",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
".",
"setData",
"(",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"walletBuilder",
".",
"addTags",
"(",
"tag",
")",
";",
"}",
"// Populate the wallet version.",
"walletBuilder",
".",
"setVersion",
"(",
"wallet",
".",
"getVersion",
"(",
")",
")",
";",
"return",
"walletBuilder",
".",
"build",
"(",
")",
";",
"}"
] | Converts the given wallet to the object representation of the protocol buffers. This can be modified, or
additional data fields set, before serialization takes place. | [
"Converts",
"the",
"given",
"wallet",
"to",
"the",
"object",
"representation",
"of",
"the",
"protocol",
"buffers",
".",
"This",
"can",
"be",
"modified",
"or",
"additional",
"data",
"fields",
"set",
"before",
"serialization",
"takes",
"place",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/WalletProtobufSerializer.java#L175-L241 |
23,305 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/WalletProtobufSerializer.java | WalletProtobufSerializer.isWallet | public static boolean isWallet(InputStream is) {
try {
final CodedInputStream cis = CodedInputStream.newInstance(is);
final int tag = cis.readTag();
final int field = WireFormat.getTagFieldNumber(tag);
if (field != 1) // network_identifier
return false;
final String network = cis.readString();
return NetworkParameters.fromID(network) != null;
} catch (IOException x) {
return false;
}
} | java | public static boolean isWallet(InputStream is) {
try {
final CodedInputStream cis = CodedInputStream.newInstance(is);
final int tag = cis.readTag();
final int field = WireFormat.getTagFieldNumber(tag);
if (field != 1) // network_identifier
return false;
final String network = cis.readString();
return NetworkParameters.fromID(network) != null;
} catch (IOException x) {
return false;
}
} | [
"public",
"static",
"boolean",
"isWallet",
"(",
"InputStream",
"is",
")",
"{",
"try",
"{",
"final",
"CodedInputStream",
"cis",
"=",
"CodedInputStream",
".",
"newInstance",
"(",
"is",
")",
";",
"final",
"int",
"tag",
"=",
"cis",
".",
"readTag",
"(",
")",
";",
"final",
"int",
"field",
"=",
"WireFormat",
".",
"getTagFieldNumber",
"(",
"tag",
")",
";",
"if",
"(",
"field",
"!=",
"1",
")",
"// network_identifier",
"return",
"false",
";",
"final",
"String",
"network",
"=",
"cis",
".",
"readString",
"(",
")",
";",
"return",
"NetworkParameters",
".",
"fromID",
"(",
"network",
")",
"!=",
"null",
";",
"}",
"catch",
"(",
"IOException",
"x",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | Cheap test to see if input stream is a wallet. This checks for a magic value at the beginning of the stream.
@param is
input stream to test
@return true if input stream is a wallet | [
"Cheap",
"test",
"to",
"see",
"if",
"input",
"stream",
"is",
"a",
"wallet",
".",
"This",
"checks",
"for",
"a",
"magic",
"value",
"at",
"the",
"beginning",
"of",
"the",
"stream",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/WalletProtobufSerializer.java#L835-L847 |
23,306 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/store/DatabaseFullPrunedBlockStore.java | DatabaseFullPrunedBlockStore.getCompatibilitySQL | protected List<String> getCompatibilitySQL() {
List<String> sqlStatements = new ArrayList<>();
sqlStatements.add(SELECT_COMPATIBILITY_COINBASE_SQL);
return sqlStatements;
} | java | protected List<String> getCompatibilitySQL() {
List<String> sqlStatements = new ArrayList<>();
sqlStatements.add(SELECT_COMPATIBILITY_COINBASE_SQL);
return sqlStatements;
} | [
"protected",
"List",
"<",
"String",
">",
"getCompatibilitySQL",
"(",
")",
"{",
"List",
"<",
"String",
">",
"sqlStatements",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"sqlStatements",
".",
"add",
"(",
"SELECT_COMPATIBILITY_COINBASE_SQL",
")",
";",
"return",
"sqlStatements",
";",
"}"
] | Get the SQL statements to check if the database is compatible.
@return The SQL prepared statements. | [
"Get",
"the",
"SQL",
"statements",
"to",
"check",
"if",
"the",
"database",
"is",
"compatible",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/store/DatabaseFullPrunedBlockStore.java#L240-L244 |
23,307 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/store/DatabaseFullPrunedBlockStore.java | DatabaseFullPrunedBlockStore.initFromDatabase | private void initFromDatabase() throws SQLException, BlockStoreException {
PreparedStatement ps = conn.get().prepareStatement(getSelectSettingsSQL());
ResultSet rs;
ps.setString(1, CHAIN_HEAD_SETTING);
rs = ps.executeQuery();
if (!rs.next()) {
throw new BlockStoreException("corrupt database block store - no chain head pointer");
}
Sha256Hash hash = Sha256Hash.wrap(rs.getBytes(1));
rs.close();
this.chainHeadBlock = get(hash);
this.chainHeadHash = hash;
if (this.chainHeadBlock == null) {
throw new BlockStoreException("corrupt database block store - head block not found");
}
ps.setString(1, VERIFIED_CHAIN_HEAD_SETTING);
rs = ps.executeQuery();
if (!rs.next()) {
throw new BlockStoreException("corrupt database block store - no verified chain head pointer");
}
hash = Sha256Hash.wrap(rs.getBytes(1));
rs.close();
ps.close();
this.verifiedChainHeadBlock = get(hash);
this.verifiedChainHeadHash = hash;
if (this.verifiedChainHeadBlock == null) {
throw new BlockStoreException("corrupt database block store - verified head block not found");
}
} | java | private void initFromDatabase() throws SQLException, BlockStoreException {
PreparedStatement ps = conn.get().prepareStatement(getSelectSettingsSQL());
ResultSet rs;
ps.setString(1, CHAIN_HEAD_SETTING);
rs = ps.executeQuery();
if (!rs.next()) {
throw new BlockStoreException("corrupt database block store - no chain head pointer");
}
Sha256Hash hash = Sha256Hash.wrap(rs.getBytes(1));
rs.close();
this.chainHeadBlock = get(hash);
this.chainHeadHash = hash;
if (this.chainHeadBlock == null) {
throw new BlockStoreException("corrupt database block store - head block not found");
}
ps.setString(1, VERIFIED_CHAIN_HEAD_SETTING);
rs = ps.executeQuery();
if (!rs.next()) {
throw new BlockStoreException("corrupt database block store - no verified chain head pointer");
}
hash = Sha256Hash.wrap(rs.getBytes(1));
rs.close();
ps.close();
this.verifiedChainHeadBlock = get(hash);
this.verifiedChainHeadHash = hash;
if (this.verifiedChainHeadBlock == null) {
throw new BlockStoreException("corrupt database block store - verified head block not found");
}
} | [
"private",
"void",
"initFromDatabase",
"(",
")",
"throws",
"SQLException",
",",
"BlockStoreException",
"{",
"PreparedStatement",
"ps",
"=",
"conn",
".",
"get",
"(",
")",
".",
"prepareStatement",
"(",
"getSelectSettingsSQL",
"(",
")",
")",
";",
"ResultSet",
"rs",
";",
"ps",
".",
"setString",
"(",
"1",
",",
"CHAIN_HEAD_SETTING",
")",
";",
"rs",
"=",
"ps",
".",
"executeQuery",
"(",
")",
";",
"if",
"(",
"!",
"rs",
".",
"next",
"(",
")",
")",
"{",
"throw",
"new",
"BlockStoreException",
"(",
"\"corrupt database block store - no chain head pointer\"",
")",
";",
"}",
"Sha256Hash",
"hash",
"=",
"Sha256Hash",
".",
"wrap",
"(",
"rs",
".",
"getBytes",
"(",
"1",
")",
")",
";",
"rs",
".",
"close",
"(",
")",
";",
"this",
".",
"chainHeadBlock",
"=",
"get",
"(",
"hash",
")",
";",
"this",
".",
"chainHeadHash",
"=",
"hash",
";",
"if",
"(",
"this",
".",
"chainHeadBlock",
"==",
"null",
")",
"{",
"throw",
"new",
"BlockStoreException",
"(",
"\"corrupt database block store - head block not found\"",
")",
";",
"}",
"ps",
".",
"setString",
"(",
"1",
",",
"VERIFIED_CHAIN_HEAD_SETTING",
")",
";",
"rs",
"=",
"ps",
".",
"executeQuery",
"(",
")",
";",
"if",
"(",
"!",
"rs",
".",
"next",
"(",
")",
")",
"{",
"throw",
"new",
"BlockStoreException",
"(",
"\"corrupt database block store - no verified chain head pointer\"",
")",
";",
"}",
"hash",
"=",
"Sha256Hash",
".",
"wrap",
"(",
"rs",
".",
"getBytes",
"(",
"1",
")",
")",
";",
"rs",
".",
"close",
"(",
")",
";",
"ps",
".",
"close",
"(",
")",
";",
"this",
".",
"verifiedChainHeadBlock",
"=",
"get",
"(",
"hash",
")",
";",
"this",
".",
"verifiedChainHeadHash",
"=",
"hash",
";",
"if",
"(",
"this",
".",
"verifiedChainHeadBlock",
"==",
"null",
")",
"{",
"throw",
"new",
"BlockStoreException",
"(",
"\"corrupt database block store - verified head block not found\"",
")",
";",
"}",
"}"
] | Initialise the store state from the database.
@throws java.sql.SQLException If there is a database error.
@throws BlockStoreException If there is a block store error. | [
"Initialise",
"the",
"store",
"state",
"from",
"the",
"database",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/store/DatabaseFullPrunedBlockStore.java#L575-L603 |
23,308 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/store/DatabaseFullPrunedBlockStore.java | DatabaseFullPrunedBlockStore.resetStore | public void resetStore() throws BlockStoreException {
maybeConnect();
try {
deleteStore();
createTables();
initFromDatabase();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
} | java | public void resetStore() throws BlockStoreException {
maybeConnect();
try {
deleteStore();
createTables();
initFromDatabase();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
} | [
"public",
"void",
"resetStore",
"(",
")",
"throws",
"BlockStoreException",
"{",
"maybeConnect",
"(",
")",
";",
"try",
"{",
"deleteStore",
"(",
")",
";",
"createTables",
"(",
")",
";",
"initFromDatabase",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"ex",
")",
";",
"}",
"}"
] | Resets the store by deleting the contents of the tables and reinitialising them.
@throws BlockStoreException If the tables couldn't be cleared and initialised. | [
"Resets",
"the",
"store",
"by",
"deleting",
"the",
"contents",
"of",
"the",
"tables",
"and",
"reinitialising",
"them",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/store/DatabaseFullPrunedBlockStore.java#L1078-L1087 |
23,309 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/store/DatabaseFullPrunedBlockStore.java | DatabaseFullPrunedBlockStore.deleteStore | public void deleteStore() throws BlockStoreException {
maybeConnect();
try {
Statement s = conn.get().createStatement();
for(String sql : getDropTablesSQL()) {
s.execute(sql);
}
s.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
} | java | public void deleteStore() throws BlockStoreException {
maybeConnect();
try {
Statement s = conn.get().createStatement();
for(String sql : getDropTablesSQL()) {
s.execute(sql);
}
s.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
} | [
"public",
"void",
"deleteStore",
"(",
")",
"throws",
"BlockStoreException",
"{",
"maybeConnect",
"(",
")",
";",
"try",
"{",
"Statement",
"s",
"=",
"conn",
".",
"get",
"(",
")",
".",
"createStatement",
"(",
")",
";",
"for",
"(",
"String",
"sql",
":",
"getDropTablesSQL",
"(",
")",
")",
"{",
"s",
".",
"execute",
"(",
"sql",
")",
";",
"}",
"s",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"ex",
")",
";",
"}",
"}"
] | Deletes the store by deleting the tables within the database.
@throws BlockStoreException If tables couldn't be deleted. | [
"Deletes",
"the",
"store",
"by",
"deleting",
"the",
"tables",
"within",
"the",
"database",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/store/DatabaseFullPrunedBlockStore.java#L1093-L1104 |
23,310 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/store/DatabaseFullPrunedBlockStore.java | DatabaseFullPrunedBlockStore.calculateBalanceForAddress | public BigInteger calculateBalanceForAddress(Address address) throws BlockStoreException {
maybeConnect();
PreparedStatement s = null;
try {
s = conn.get().prepareStatement(getBalanceSelectSQL());
s.setString(1, address.toString());
ResultSet rs = s.executeQuery();
BigInteger balance = BigInteger.ZERO;
if (rs.next()) {
return BigInteger.valueOf(rs.getLong(1));
}
return balance;
} catch (SQLException ex) {
throw new BlockStoreException(ex);
} finally {
if (s != null) {
try {
s.close();
} catch (SQLException e) {
throw new BlockStoreException("Could not close statement");
}
}
}
} | java | public BigInteger calculateBalanceForAddress(Address address) throws BlockStoreException {
maybeConnect();
PreparedStatement s = null;
try {
s = conn.get().prepareStatement(getBalanceSelectSQL());
s.setString(1, address.toString());
ResultSet rs = s.executeQuery();
BigInteger balance = BigInteger.ZERO;
if (rs.next()) {
return BigInteger.valueOf(rs.getLong(1));
}
return balance;
} catch (SQLException ex) {
throw new BlockStoreException(ex);
} finally {
if (s != null) {
try {
s.close();
} catch (SQLException e) {
throw new BlockStoreException("Could not close statement");
}
}
}
} | [
"public",
"BigInteger",
"calculateBalanceForAddress",
"(",
"Address",
"address",
")",
"throws",
"BlockStoreException",
"{",
"maybeConnect",
"(",
")",
";",
"PreparedStatement",
"s",
"=",
"null",
";",
"try",
"{",
"s",
"=",
"conn",
".",
"get",
"(",
")",
".",
"prepareStatement",
"(",
"getBalanceSelectSQL",
"(",
")",
")",
";",
"s",
".",
"setString",
"(",
"1",
",",
"address",
".",
"toString",
"(",
")",
")",
";",
"ResultSet",
"rs",
"=",
"s",
".",
"executeQuery",
"(",
")",
";",
"BigInteger",
"balance",
"=",
"BigInteger",
".",
"ZERO",
";",
"if",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"return",
"BigInteger",
".",
"valueOf",
"(",
"rs",
".",
"getLong",
"(",
"1",
")",
")",
";",
"}",
"return",
"balance",
";",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"throw",
"new",
"BlockStoreException",
"(",
"ex",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"s",
"!=",
"null",
")",
"{",
"try",
"{",
"s",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"e",
")",
"{",
"throw",
"new",
"BlockStoreException",
"(",
"\"Could not close statement\"",
")",
";",
"}",
"}",
"}",
"}"
] | Calculate the balance for a coinbase, to-address, or p2sh address.
<p>The balance {@link DatabaseFullPrunedBlockStore#getBalanceSelectSQL()} returns
the balance (summed) as an number, then use calculateClientSide=false</p>
<p>The balance {@link DatabaseFullPrunedBlockStore#getBalanceSelectSQL()} returns
the all the openoutputs as stored in the DB (binary), then use calculateClientSide=true</p>
@param address The address to calculate the balance of
@return The balance of the address supplied. If the address has not been seen, or there are no outputs open for this
address, the return value is 0.
@throws BlockStoreException If there is an error getting the balance. | [
"Calculate",
"the",
"balance",
"for",
"a",
"coinbase",
"to",
"-",
"address",
"or",
"p2sh",
"address",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/store/DatabaseFullPrunedBlockStore.java#L1120-L1143 |
23,311 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/DeterministicHierarchy.java | DeterministicHierarchy.get | public DeterministicKey get(List<ChildNumber> path, boolean relativePath, boolean create) {
ImmutableList<ChildNumber> absolutePath = relativePath
? ImmutableList.<ChildNumber>builder().addAll(rootPath).addAll(path).build()
: ImmutableList.copyOf(path);
if (!keys.containsKey(absolutePath)) {
if (!create)
throw new IllegalArgumentException(String.format(Locale.US, "No key found for %s path %s.",
relativePath ? "relative" : "absolute", HDUtils.formatPath(path)));
checkArgument(absolutePath.size() > 0, "Can't derive the master key: nothing to derive from.");
DeterministicKey parent = get(absolutePath.subList(0, absolutePath.size() - 1), false, true);
putKey(HDKeyDerivation.deriveChildKey(parent, absolutePath.get(absolutePath.size() - 1)));
}
return keys.get(absolutePath);
} | java | public DeterministicKey get(List<ChildNumber> path, boolean relativePath, boolean create) {
ImmutableList<ChildNumber> absolutePath = relativePath
? ImmutableList.<ChildNumber>builder().addAll(rootPath).addAll(path).build()
: ImmutableList.copyOf(path);
if (!keys.containsKey(absolutePath)) {
if (!create)
throw new IllegalArgumentException(String.format(Locale.US, "No key found for %s path %s.",
relativePath ? "relative" : "absolute", HDUtils.formatPath(path)));
checkArgument(absolutePath.size() > 0, "Can't derive the master key: nothing to derive from.");
DeterministicKey parent = get(absolutePath.subList(0, absolutePath.size() - 1), false, true);
putKey(HDKeyDerivation.deriveChildKey(parent, absolutePath.get(absolutePath.size() - 1)));
}
return keys.get(absolutePath);
} | [
"public",
"DeterministicKey",
"get",
"(",
"List",
"<",
"ChildNumber",
">",
"path",
",",
"boolean",
"relativePath",
",",
"boolean",
"create",
")",
"{",
"ImmutableList",
"<",
"ChildNumber",
">",
"absolutePath",
"=",
"relativePath",
"?",
"ImmutableList",
".",
"<",
"ChildNumber",
">",
"builder",
"(",
")",
".",
"addAll",
"(",
"rootPath",
")",
".",
"addAll",
"(",
"path",
")",
".",
"build",
"(",
")",
":",
"ImmutableList",
".",
"copyOf",
"(",
"path",
")",
";",
"if",
"(",
"!",
"keys",
".",
"containsKey",
"(",
"absolutePath",
")",
")",
"{",
"if",
"(",
"!",
"create",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"format",
"(",
"Locale",
".",
"US",
",",
"\"No key found for %s path %s.\"",
",",
"relativePath",
"?",
"\"relative\"",
":",
"\"absolute\"",
",",
"HDUtils",
".",
"formatPath",
"(",
"path",
")",
")",
")",
";",
"checkArgument",
"(",
"absolutePath",
".",
"size",
"(",
")",
">",
"0",
",",
"\"Can't derive the master key: nothing to derive from.\"",
")",
";",
"DeterministicKey",
"parent",
"=",
"get",
"(",
"absolutePath",
".",
"subList",
"(",
"0",
",",
"absolutePath",
".",
"size",
"(",
")",
"-",
"1",
")",
",",
"false",
",",
"true",
")",
";",
"putKey",
"(",
"HDKeyDerivation",
".",
"deriveChildKey",
"(",
"parent",
",",
"absolutePath",
".",
"get",
"(",
"absolutePath",
".",
"size",
"(",
")",
"-",
"1",
")",
")",
")",
";",
"}",
"return",
"keys",
".",
"get",
"(",
"absolutePath",
")",
";",
"}"
] | Returns a key for the given path, optionally creating it.
@param path the path to the key
@param relativePath whether the path is relative to the root path
@param create whether the key corresponding to path should be created (with any necessary ancestors) if it doesn't exist already
@return next newly created key using the child derivation function
@throws IllegalArgumentException if create is false and the path was not found. | [
"Returns",
"a",
"key",
"for",
"the",
"given",
"path",
"optionally",
"creating",
"it",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/DeterministicHierarchy.java#L83-L96 |
23,312 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Base58.java | Base58.encodeChecked | public static String encodeChecked(int version, byte[] payload) {
if (version < 0 || version > 255)
throw new IllegalArgumentException("Version not in range.");
// A stringified buffer is:
// 1 byte version + data bytes + 4 bytes check code (a truncated hash)
byte[] addressBytes = new byte[1 + payload.length + 4];
addressBytes[0] = (byte) version;
System.arraycopy(payload, 0, addressBytes, 1, payload.length);
byte[] checksum = Sha256Hash.hashTwice(addressBytes, 0, payload.length + 1);
System.arraycopy(checksum, 0, addressBytes, payload.length + 1, 4);
return Base58.encode(addressBytes);
} | java | public static String encodeChecked(int version, byte[] payload) {
if (version < 0 || version > 255)
throw new IllegalArgumentException("Version not in range.");
// A stringified buffer is:
// 1 byte version + data bytes + 4 bytes check code (a truncated hash)
byte[] addressBytes = new byte[1 + payload.length + 4];
addressBytes[0] = (byte) version;
System.arraycopy(payload, 0, addressBytes, 1, payload.length);
byte[] checksum = Sha256Hash.hashTwice(addressBytes, 0, payload.length + 1);
System.arraycopy(checksum, 0, addressBytes, payload.length + 1, 4);
return Base58.encode(addressBytes);
} | [
"public",
"static",
"String",
"encodeChecked",
"(",
"int",
"version",
",",
"byte",
"[",
"]",
"payload",
")",
"{",
"if",
"(",
"version",
"<",
"0",
"||",
"version",
">",
"255",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Version not in range.\"",
")",
";",
"// A stringified buffer is:",
"// 1 byte version + data bytes + 4 bytes check code (a truncated hash)",
"byte",
"[",
"]",
"addressBytes",
"=",
"new",
"byte",
"[",
"1",
"+",
"payload",
".",
"length",
"+",
"4",
"]",
";",
"addressBytes",
"[",
"0",
"]",
"=",
"(",
"byte",
")",
"version",
";",
"System",
".",
"arraycopy",
"(",
"payload",
",",
"0",
",",
"addressBytes",
",",
"1",
",",
"payload",
".",
"length",
")",
";",
"byte",
"[",
"]",
"checksum",
"=",
"Sha256Hash",
".",
"hashTwice",
"(",
"addressBytes",
",",
"0",
",",
"payload",
".",
"length",
"+",
"1",
")",
";",
"System",
".",
"arraycopy",
"(",
"checksum",
",",
"0",
",",
"addressBytes",
",",
"payload",
".",
"length",
"+",
"1",
",",
"4",
")",
";",
"return",
"Base58",
".",
"encode",
"(",
"addressBytes",
")",
";",
"}"
] | Encodes the given version and bytes as a base58 string. A checksum is appended.
@param version the version to encode
@param payload the bytes to encode, e.g. pubkey hash
@return the base58-encoded string | [
"Encodes",
"the",
"given",
"version",
"and",
"bytes",
"as",
"a",
"base58",
"string",
".",
"A",
"checksum",
"is",
"appended",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Base58.java#L101-L113 |
23,313 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Base58.java | Base58.decode | public static byte[] decode(String input) throws AddressFormatException {
if (input.length() == 0) {
return new byte[0];
}
// Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits).
byte[] input58 = new byte[input.length()];
for (int i = 0; i < input.length(); ++i) {
char c = input.charAt(i);
int digit = c < 128 ? INDEXES[c] : -1;
if (digit < 0) {
throw new AddressFormatException.InvalidCharacter(c, i);
}
input58[i] = (byte) digit;
}
// Count leading zeros.
int zeros = 0;
while (zeros < input58.length && input58[zeros] == 0) {
++zeros;
}
// Convert base-58 digits to base-256 digits.
byte[] decoded = new byte[input.length()];
int outputStart = decoded.length;
for (int inputStart = zeros; inputStart < input58.length; ) {
decoded[--outputStart] = divmod(input58, inputStart, 58, 256);
if (input58[inputStart] == 0) {
++inputStart; // optimization - skip leading zeros
}
}
// Ignore extra leading zeroes that were added during the calculation.
while (outputStart < decoded.length && decoded[outputStart] == 0) {
++outputStart;
}
// Return decoded data (including original number of leading zeros).
return Arrays.copyOfRange(decoded, outputStart - zeros, decoded.length);
} | java | public static byte[] decode(String input) throws AddressFormatException {
if (input.length() == 0) {
return new byte[0];
}
// Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits).
byte[] input58 = new byte[input.length()];
for (int i = 0; i < input.length(); ++i) {
char c = input.charAt(i);
int digit = c < 128 ? INDEXES[c] : -1;
if (digit < 0) {
throw new AddressFormatException.InvalidCharacter(c, i);
}
input58[i] = (byte) digit;
}
// Count leading zeros.
int zeros = 0;
while (zeros < input58.length && input58[zeros] == 0) {
++zeros;
}
// Convert base-58 digits to base-256 digits.
byte[] decoded = new byte[input.length()];
int outputStart = decoded.length;
for (int inputStart = zeros; inputStart < input58.length; ) {
decoded[--outputStart] = divmod(input58, inputStart, 58, 256);
if (input58[inputStart] == 0) {
++inputStart; // optimization - skip leading zeros
}
}
// Ignore extra leading zeroes that were added during the calculation.
while (outputStart < decoded.length && decoded[outputStart] == 0) {
++outputStart;
}
// Return decoded data (including original number of leading zeros).
return Arrays.copyOfRange(decoded, outputStart - zeros, decoded.length);
} | [
"public",
"static",
"byte",
"[",
"]",
"decode",
"(",
"String",
"input",
")",
"throws",
"AddressFormatException",
"{",
"if",
"(",
"input",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
"new",
"byte",
"[",
"0",
"]",
";",
"}",
"// Convert the base58-encoded ASCII chars to a base58 byte sequence (base58 digits).",
"byte",
"[",
"]",
"input58",
"=",
"new",
"byte",
"[",
"input",
".",
"length",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"input",
".",
"length",
"(",
")",
";",
"++",
"i",
")",
"{",
"char",
"c",
"=",
"input",
".",
"charAt",
"(",
"i",
")",
";",
"int",
"digit",
"=",
"c",
"<",
"128",
"?",
"INDEXES",
"[",
"c",
"]",
":",
"-",
"1",
";",
"if",
"(",
"digit",
"<",
"0",
")",
"{",
"throw",
"new",
"AddressFormatException",
".",
"InvalidCharacter",
"(",
"c",
",",
"i",
")",
";",
"}",
"input58",
"[",
"i",
"]",
"=",
"(",
"byte",
")",
"digit",
";",
"}",
"// Count leading zeros.",
"int",
"zeros",
"=",
"0",
";",
"while",
"(",
"zeros",
"<",
"input58",
".",
"length",
"&&",
"input58",
"[",
"zeros",
"]",
"==",
"0",
")",
"{",
"++",
"zeros",
";",
"}",
"// Convert base-58 digits to base-256 digits.",
"byte",
"[",
"]",
"decoded",
"=",
"new",
"byte",
"[",
"input",
".",
"length",
"(",
")",
"]",
";",
"int",
"outputStart",
"=",
"decoded",
".",
"length",
";",
"for",
"(",
"int",
"inputStart",
"=",
"zeros",
";",
"inputStart",
"<",
"input58",
".",
"length",
";",
")",
"{",
"decoded",
"[",
"--",
"outputStart",
"]",
"=",
"divmod",
"(",
"input58",
",",
"inputStart",
",",
"58",
",",
"256",
")",
";",
"if",
"(",
"input58",
"[",
"inputStart",
"]",
"==",
"0",
")",
"{",
"++",
"inputStart",
";",
"// optimization - skip leading zeros",
"}",
"}",
"// Ignore extra leading zeroes that were added during the calculation.",
"while",
"(",
"outputStart",
"<",
"decoded",
".",
"length",
"&&",
"decoded",
"[",
"outputStart",
"]",
"==",
"0",
")",
"{",
"++",
"outputStart",
";",
"}",
"// Return decoded data (including original number of leading zeros).",
"return",
"Arrays",
".",
"copyOfRange",
"(",
"decoded",
",",
"outputStart",
"-",
"zeros",
",",
"decoded",
".",
"length",
")",
";",
"}"
] | Decodes the given base58 string into the original data bytes.
@param input the base58-encoded string to decode
@return the decoded data bytes
@throws AddressFormatException if the given string is not a valid base58 string | [
"Decodes",
"the",
"given",
"base58",
"string",
"into",
"the",
"original",
"data",
"bytes",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Base58.java#L122-L156 |
23,314 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Base58.java | Base58.decodeChecked | public static byte[] decodeChecked(String input) throws AddressFormatException {
byte[] decoded = decode(input);
if (decoded.length < 4)
throw new AddressFormatException.InvalidDataLength("Input too short: " + decoded.length);
byte[] data = Arrays.copyOfRange(decoded, 0, decoded.length - 4);
byte[] checksum = Arrays.copyOfRange(decoded, decoded.length - 4, decoded.length);
byte[] actualChecksum = Arrays.copyOfRange(Sha256Hash.hashTwice(data), 0, 4);
if (!Arrays.equals(checksum, actualChecksum))
throw new AddressFormatException.InvalidChecksum();
return data;
} | java | public static byte[] decodeChecked(String input) throws AddressFormatException {
byte[] decoded = decode(input);
if (decoded.length < 4)
throw new AddressFormatException.InvalidDataLength("Input too short: " + decoded.length);
byte[] data = Arrays.copyOfRange(decoded, 0, decoded.length - 4);
byte[] checksum = Arrays.copyOfRange(decoded, decoded.length - 4, decoded.length);
byte[] actualChecksum = Arrays.copyOfRange(Sha256Hash.hashTwice(data), 0, 4);
if (!Arrays.equals(checksum, actualChecksum))
throw new AddressFormatException.InvalidChecksum();
return data;
} | [
"public",
"static",
"byte",
"[",
"]",
"decodeChecked",
"(",
"String",
"input",
")",
"throws",
"AddressFormatException",
"{",
"byte",
"[",
"]",
"decoded",
"=",
"decode",
"(",
"input",
")",
";",
"if",
"(",
"decoded",
".",
"length",
"<",
"4",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidDataLength",
"(",
"\"Input too short: \"",
"+",
"decoded",
".",
"length",
")",
";",
"byte",
"[",
"]",
"data",
"=",
"Arrays",
".",
"copyOfRange",
"(",
"decoded",
",",
"0",
",",
"decoded",
".",
"length",
"-",
"4",
")",
";",
"byte",
"[",
"]",
"checksum",
"=",
"Arrays",
".",
"copyOfRange",
"(",
"decoded",
",",
"decoded",
".",
"length",
"-",
"4",
",",
"decoded",
".",
"length",
")",
";",
"byte",
"[",
"]",
"actualChecksum",
"=",
"Arrays",
".",
"copyOfRange",
"(",
"Sha256Hash",
".",
"hashTwice",
"(",
"data",
")",
",",
"0",
",",
"4",
")",
";",
"if",
"(",
"!",
"Arrays",
".",
"equals",
"(",
"checksum",
",",
"actualChecksum",
")",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidChecksum",
"(",
")",
";",
"return",
"data",
";",
"}"
] | Decodes the given base58 string into the original data bytes, using the checksum in the
last 4 bytes of the decoded data to verify that the rest are correct. The checksum is
removed from the returned data.
@param input the base58-encoded string to decode (which should include the checksum)
@throws AddressFormatException if the input is not base 58 or the checksum does not validate. | [
"Decodes",
"the",
"given",
"base58",
"string",
"into",
"the",
"original",
"data",
"bytes",
"using",
"the",
"checksum",
"in",
"the",
"last",
"4",
"bytes",
"of",
"the",
"decoded",
"data",
"to",
"verify",
"that",
"the",
"rest",
"are",
"correct",
".",
"The",
"checksum",
"is",
"removed",
"from",
"the",
"returned",
"data",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Base58.java#L170-L180 |
23,315 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Base58.java | Base58.divmod | private static byte divmod(byte[] number, int firstDigit, int base, int divisor) {
// this is just long division which accounts for the base of the input digits
int remainder = 0;
for (int i = firstDigit; i < number.length; i++) {
int digit = (int) number[i] & 0xFF;
int temp = remainder * base + digit;
number[i] = (byte) (temp / divisor);
remainder = temp % divisor;
}
return (byte) remainder;
} | java | private static byte divmod(byte[] number, int firstDigit, int base, int divisor) {
// this is just long division which accounts for the base of the input digits
int remainder = 0;
for (int i = firstDigit; i < number.length; i++) {
int digit = (int) number[i] & 0xFF;
int temp = remainder * base + digit;
number[i] = (byte) (temp / divisor);
remainder = temp % divisor;
}
return (byte) remainder;
} | [
"private",
"static",
"byte",
"divmod",
"(",
"byte",
"[",
"]",
"number",
",",
"int",
"firstDigit",
",",
"int",
"base",
",",
"int",
"divisor",
")",
"{",
"// this is just long division which accounts for the base of the input digits",
"int",
"remainder",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"firstDigit",
";",
"i",
"<",
"number",
".",
"length",
";",
"i",
"++",
")",
"{",
"int",
"digit",
"=",
"(",
"int",
")",
"number",
"[",
"i",
"]",
"&",
"0xFF",
";",
"int",
"temp",
"=",
"remainder",
"*",
"base",
"+",
"digit",
";",
"number",
"[",
"i",
"]",
"=",
"(",
"byte",
")",
"(",
"temp",
"/",
"divisor",
")",
";",
"remainder",
"=",
"temp",
"%",
"divisor",
";",
"}",
"return",
"(",
"byte",
")",
"remainder",
";",
"}"
] | Divides a number, represented as an array of bytes each containing a single digit
in the specified base, by the given divisor. The given number is modified in-place
to contain the quotient, and the return value is the remainder.
@param number the number to divide
@param firstDigit the index within the array of the first non-zero digit
(this is used for optimization by skipping the leading zeros)
@param base the base in which the number's digits are represented (up to 256)
@param divisor the number to divide by (up to 256)
@return the remainder of the division operation | [
"Divides",
"a",
"number",
"represented",
"as",
"an",
"array",
"of",
"bytes",
"each",
"containing",
"a",
"single",
"digit",
"in",
"the",
"specified",
"base",
"by",
"the",
"given",
"divisor",
".",
"The",
"given",
"number",
"is",
"modified",
"in",
"-",
"place",
"to",
"contain",
"the",
"quotient",
"and",
"the",
"return",
"value",
"is",
"the",
"remainder",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Base58.java#L194-L204 |
23,316 | bitcoinj/bitcoinj | tools/src/main/java/org/bitcoinj/tools/WalletTool.java | WalletTool.setup | private static void setup() throws BlockStoreException {
if (store != null) return; // Already done.
// Will create a fresh chain if one doesn't exist or there is an issue with this one.
boolean reset = !chainFileName.exists();
if (reset) {
// No chain, so reset the wallet as we will be downloading from scratch.
System.out.println("Chain file is missing so resetting the wallet.");
reset();
}
if (mode == ValidationMode.SPV) {
store = new SPVBlockStore(params, chainFileName);
if (reset) {
try {
CheckpointManager.checkpoint(params, CheckpointManager.openStream(params), store,
wallet.getEarliestKeyCreationTime());
StoredBlock head = store.getChainHead();
System.out.println("Skipped to checkpoint " + head.getHeight() + " at "
+ Utils.dateTimeFormat(head.getHeader().getTimeSeconds() * 1000));
} catch (IOException x) {
System.out.println("Could not load checkpoints: " + x.getMessage());
}
}
chain = new BlockChain(params, wallet, store);
} else if (mode == ValidationMode.FULL) {
store = new H2FullPrunedBlockStore(params, chainFileName.getAbsolutePath(), 5000);
chain = new FullPrunedBlockChain(params, wallet, (FullPrunedBlockStore) store);
}
// This will ensure the wallet is saved when it changes.
wallet.autosaveToFile(walletFile, 5, TimeUnit.SECONDS, null);
if (peerGroup == null) {
peerGroup = new PeerGroup(params, chain);
}
peerGroup.setUserAgent("WalletTool", "1.0");
if (params == RegTestParams.get())
peerGroup.setMinBroadcastConnections(1);
peerGroup.addWallet(wallet);
if (options.has("peers")) {
String peersFlag = (String) options.valueOf("peers");
String[] peerAddrs = peersFlag.split(",");
for (String peer : peerAddrs) {
try {
peerGroup.addAddress(new PeerAddress(params, InetAddress.getByName(peer)));
} catch (UnknownHostException e) {
System.err.println("Could not understand peer domain name/IP address: " + peer + ": " + e.getMessage());
System.exit(1);
}
}
} else {
peerGroup.setRequiredServices(0);
}
} | java | private static void setup() throws BlockStoreException {
if (store != null) return; // Already done.
// Will create a fresh chain if one doesn't exist or there is an issue with this one.
boolean reset = !chainFileName.exists();
if (reset) {
// No chain, so reset the wallet as we will be downloading from scratch.
System.out.println("Chain file is missing so resetting the wallet.");
reset();
}
if (mode == ValidationMode.SPV) {
store = new SPVBlockStore(params, chainFileName);
if (reset) {
try {
CheckpointManager.checkpoint(params, CheckpointManager.openStream(params), store,
wallet.getEarliestKeyCreationTime());
StoredBlock head = store.getChainHead();
System.out.println("Skipped to checkpoint " + head.getHeight() + " at "
+ Utils.dateTimeFormat(head.getHeader().getTimeSeconds() * 1000));
} catch (IOException x) {
System.out.println("Could not load checkpoints: " + x.getMessage());
}
}
chain = new BlockChain(params, wallet, store);
} else if (mode == ValidationMode.FULL) {
store = new H2FullPrunedBlockStore(params, chainFileName.getAbsolutePath(), 5000);
chain = new FullPrunedBlockChain(params, wallet, (FullPrunedBlockStore) store);
}
// This will ensure the wallet is saved when it changes.
wallet.autosaveToFile(walletFile, 5, TimeUnit.SECONDS, null);
if (peerGroup == null) {
peerGroup = new PeerGroup(params, chain);
}
peerGroup.setUserAgent("WalletTool", "1.0");
if (params == RegTestParams.get())
peerGroup.setMinBroadcastConnections(1);
peerGroup.addWallet(wallet);
if (options.has("peers")) {
String peersFlag = (String) options.valueOf("peers");
String[] peerAddrs = peersFlag.split(",");
for (String peer : peerAddrs) {
try {
peerGroup.addAddress(new PeerAddress(params, InetAddress.getByName(peer)));
} catch (UnknownHostException e) {
System.err.println("Could not understand peer domain name/IP address: " + peer + ": " + e.getMessage());
System.exit(1);
}
}
} else {
peerGroup.setRequiredServices(0);
}
} | [
"private",
"static",
"void",
"setup",
"(",
")",
"throws",
"BlockStoreException",
"{",
"if",
"(",
"store",
"!=",
"null",
")",
"return",
";",
"// Already done.",
"// Will create a fresh chain if one doesn't exist or there is an issue with this one.",
"boolean",
"reset",
"=",
"!",
"chainFileName",
".",
"exists",
"(",
")",
";",
"if",
"(",
"reset",
")",
"{",
"// No chain, so reset the wallet as we will be downloading from scratch.",
"System",
".",
"out",
".",
"println",
"(",
"\"Chain file is missing so resetting the wallet.\"",
")",
";",
"reset",
"(",
")",
";",
"}",
"if",
"(",
"mode",
"==",
"ValidationMode",
".",
"SPV",
")",
"{",
"store",
"=",
"new",
"SPVBlockStore",
"(",
"params",
",",
"chainFileName",
")",
";",
"if",
"(",
"reset",
")",
"{",
"try",
"{",
"CheckpointManager",
".",
"checkpoint",
"(",
"params",
",",
"CheckpointManager",
".",
"openStream",
"(",
"params",
")",
",",
"store",
",",
"wallet",
".",
"getEarliestKeyCreationTime",
"(",
")",
")",
";",
"StoredBlock",
"head",
"=",
"store",
".",
"getChainHead",
"(",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"Skipped to checkpoint \"",
"+",
"head",
".",
"getHeight",
"(",
")",
"+",
"\" at \"",
"+",
"Utils",
".",
"dateTimeFormat",
"(",
"head",
".",
"getHeader",
"(",
")",
".",
"getTimeSeconds",
"(",
")",
"*",
"1000",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"x",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"Could not load checkpoints: \"",
"+",
"x",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"chain",
"=",
"new",
"BlockChain",
"(",
"params",
",",
"wallet",
",",
"store",
")",
";",
"}",
"else",
"if",
"(",
"mode",
"==",
"ValidationMode",
".",
"FULL",
")",
"{",
"store",
"=",
"new",
"H2FullPrunedBlockStore",
"(",
"params",
",",
"chainFileName",
".",
"getAbsolutePath",
"(",
")",
",",
"5000",
")",
";",
"chain",
"=",
"new",
"FullPrunedBlockChain",
"(",
"params",
",",
"wallet",
",",
"(",
"FullPrunedBlockStore",
")",
"store",
")",
";",
"}",
"// This will ensure the wallet is saved when it changes.",
"wallet",
".",
"autosaveToFile",
"(",
"walletFile",
",",
"5",
",",
"TimeUnit",
".",
"SECONDS",
",",
"null",
")",
";",
"if",
"(",
"peerGroup",
"==",
"null",
")",
"{",
"peerGroup",
"=",
"new",
"PeerGroup",
"(",
"params",
",",
"chain",
")",
";",
"}",
"peerGroup",
".",
"setUserAgent",
"(",
"\"WalletTool\"",
",",
"\"1.0\"",
")",
";",
"if",
"(",
"params",
"==",
"RegTestParams",
".",
"get",
"(",
")",
")",
"peerGroup",
".",
"setMinBroadcastConnections",
"(",
"1",
")",
";",
"peerGroup",
".",
"addWallet",
"(",
"wallet",
")",
";",
"if",
"(",
"options",
".",
"has",
"(",
"\"peers\"",
")",
")",
"{",
"String",
"peersFlag",
"=",
"(",
"String",
")",
"options",
".",
"valueOf",
"(",
"\"peers\"",
")",
";",
"String",
"[",
"]",
"peerAddrs",
"=",
"peersFlag",
".",
"split",
"(",
"\",\"",
")",
";",
"for",
"(",
"String",
"peer",
":",
"peerAddrs",
")",
"{",
"try",
"{",
"peerGroup",
".",
"addAddress",
"(",
"new",
"PeerAddress",
"(",
"params",
",",
"InetAddress",
".",
"getByName",
"(",
"peer",
")",
")",
")",
";",
"}",
"catch",
"(",
"UnknownHostException",
"e",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"Could not understand peer domain name/IP address: \"",
"+",
"peer",
"+",
"\": \"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"System",
".",
"exit",
"(",
"1",
")",
";",
"}",
"}",
"}",
"else",
"{",
"peerGroup",
".",
"setRequiredServices",
"(",
"0",
")",
";",
"}",
"}"
] | Sets up all objects needed for network communication but does not bring up the peers. | [
"Sets",
"up",
"all",
"objects",
"needed",
"for",
"network",
"communication",
"but",
"does",
"not",
"bring",
"up",
"the",
"peers",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/tools/src/main/java/org/bitcoinj/tools/WalletTool.java#L1251-L1301 |
23,317 | bitcoinj/bitcoinj | tools/src/main/java/org/bitcoinj/tools/WalletTool.java | WalletTool.parseAsHexOrBase58 | private static byte[] parseAsHexOrBase58(String data) {
try {
return Utils.HEX.decode(data);
} catch (Exception e) {
// Didn't decode as hex, try base58.
try {
return Base58.decodeChecked(data);
} catch (AddressFormatException e1) {
return null;
}
}
} | java | private static byte[] parseAsHexOrBase58(String data) {
try {
return Utils.HEX.decode(data);
} catch (Exception e) {
// Didn't decode as hex, try base58.
try {
return Base58.decodeChecked(data);
} catch (AddressFormatException e1) {
return null;
}
}
} | [
"private",
"static",
"byte",
"[",
"]",
"parseAsHexOrBase58",
"(",
"String",
"data",
")",
"{",
"try",
"{",
"return",
"Utils",
".",
"HEX",
".",
"decode",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"// Didn't decode as hex, try base58.",
"try",
"{",
"return",
"Base58",
".",
"decodeChecked",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"AddressFormatException",
"e1",
")",
"{",
"return",
"null",
";",
"}",
"}",
"}"
] | Attempts to parse the given string as arbitrary-length hex or base58 and then return the results, or null if
neither parse was successful. | [
"Attempts",
"to",
"parse",
"the",
"given",
"string",
"as",
"arbitrary",
"-",
"length",
"hex",
"or",
"base58",
"and",
"then",
"return",
"the",
"results",
"or",
"null",
"if",
"neither",
"parse",
"was",
"successful",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/tools/src/main/java/org/bitcoinj/tools/WalletTool.java#L1466-L1477 |
23,318 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/ExponentialBackoff.java | ExponentialBackoff.trackFailure | public void trackFailure() {
retryTime = Utils.currentTimeMillis() + (long)backoff;
backoff = Math.min(backoff * params.multiplier, params.maximum);
} | java | public void trackFailure() {
retryTime = Utils.currentTimeMillis() + (long)backoff;
backoff = Math.min(backoff * params.multiplier, params.maximum);
} | [
"public",
"void",
"trackFailure",
"(",
")",
"{",
"retryTime",
"=",
"Utils",
".",
"currentTimeMillis",
"(",
")",
"+",
"(",
"long",
")",
"backoff",
";",
"backoff",
"=",
"Math",
".",
"min",
"(",
"backoff",
"*",
"params",
".",
"multiplier",
",",
"params",
".",
"maximum",
")",
";",
"}"
] | Track a failure - multiply the back off interval by the multiplier | [
"Track",
"a",
"failure",
"-",
"multiply",
"the",
"back",
"off",
"interval",
"by",
"the",
"multiplier"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/ExponentialBackoff.java#L81-L84 |
23,319 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Bech32.java | Bech32.polymod | private static int polymod(final byte[] values) {
int c = 1;
for (byte v_i: values) {
int c0 = (c >>> 25) & 0xff;
c = ((c & 0x1ffffff) << 5) ^ (v_i & 0xff);
if ((c0 & 1) != 0) c ^= 0x3b6a57b2;
if ((c0 & 2) != 0) c ^= 0x26508e6d;
if ((c0 & 4) != 0) c ^= 0x1ea119fa;
if ((c0 & 8) != 0) c ^= 0x3d4233dd;
if ((c0 & 16) != 0) c ^= 0x2a1462b3;
}
return c;
} | java | private static int polymod(final byte[] values) {
int c = 1;
for (byte v_i: values) {
int c0 = (c >>> 25) & 0xff;
c = ((c & 0x1ffffff) << 5) ^ (v_i & 0xff);
if ((c0 & 1) != 0) c ^= 0x3b6a57b2;
if ((c0 & 2) != 0) c ^= 0x26508e6d;
if ((c0 & 4) != 0) c ^= 0x1ea119fa;
if ((c0 & 8) != 0) c ^= 0x3d4233dd;
if ((c0 & 16) != 0) c ^= 0x2a1462b3;
}
return c;
} | [
"private",
"static",
"int",
"polymod",
"(",
"final",
"byte",
"[",
"]",
"values",
")",
"{",
"int",
"c",
"=",
"1",
";",
"for",
"(",
"byte",
"v_i",
":",
"values",
")",
"{",
"int",
"c0",
"=",
"(",
"c",
">>>",
"25",
")",
"&",
"0xff",
";",
"c",
"=",
"(",
"(",
"c",
"&",
"0x1ffffff",
")",
"<<",
"5",
")",
"^",
"(",
"v_i",
"&",
"0xff",
")",
";",
"if",
"(",
"(",
"c0",
"&",
"1",
")",
"!=",
"0",
")",
"c",
"^=",
"0x3b6a57b2",
";",
"if",
"(",
"(",
"c0",
"&",
"2",
")",
"!=",
"0",
")",
"c",
"^=",
"0x26508e6d",
";",
"if",
"(",
"(",
"c0",
"&",
"4",
")",
"!=",
"0",
")",
"c",
"^=",
"0x1ea119fa",
";",
"if",
"(",
"(",
"c0",
"&",
"8",
")",
"!=",
"0",
")",
"c",
"^=",
"0x3d4233dd",
";",
"if",
"(",
"(",
"c0",
"&",
"16",
")",
"!=",
"0",
")",
"c",
"^=",
"0x2a1462b3",
";",
"}",
"return",
"c",
";",
"}"
] | Find the polynomial with value coefficients mod the generator as 30-bit. | [
"Find",
"the",
"polynomial",
"with",
"value",
"coefficients",
"mod",
"the",
"generator",
"as",
"30",
"-",
"bit",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Bech32.java#L51-L63 |
23,320 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Bech32.java | Bech32.expandHrp | private static byte[] expandHrp(final String hrp) {
int hrpLength = hrp.length();
byte ret[] = new byte[hrpLength * 2 + 1];
for (int i = 0; i < hrpLength; ++i) {
int c = hrp.charAt(i) & 0x7f; // Limit to standard 7-bit ASCII
ret[i] = (byte) ((c >>> 5) & 0x07);
ret[i + hrpLength + 1] = (byte) (c & 0x1f);
}
ret[hrpLength] = 0;
return ret;
} | java | private static byte[] expandHrp(final String hrp) {
int hrpLength = hrp.length();
byte ret[] = new byte[hrpLength * 2 + 1];
for (int i = 0; i < hrpLength; ++i) {
int c = hrp.charAt(i) & 0x7f; // Limit to standard 7-bit ASCII
ret[i] = (byte) ((c >>> 5) & 0x07);
ret[i + hrpLength + 1] = (byte) (c & 0x1f);
}
ret[hrpLength] = 0;
return ret;
} | [
"private",
"static",
"byte",
"[",
"]",
"expandHrp",
"(",
"final",
"String",
"hrp",
")",
"{",
"int",
"hrpLength",
"=",
"hrp",
".",
"length",
"(",
")",
";",
"byte",
"ret",
"[",
"]",
"=",
"new",
"byte",
"[",
"hrpLength",
"*",
"2",
"+",
"1",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"hrpLength",
";",
"++",
"i",
")",
"{",
"int",
"c",
"=",
"hrp",
".",
"charAt",
"(",
"i",
")",
"&",
"0x7f",
";",
"// Limit to standard 7-bit ASCII",
"ret",
"[",
"i",
"]",
"=",
"(",
"byte",
")",
"(",
"(",
"c",
">>>",
"5",
")",
"&",
"0x07",
")",
";",
"ret",
"[",
"i",
"+",
"hrpLength",
"+",
"1",
"]",
"=",
"(",
"byte",
")",
"(",
"c",
"&",
"0x1f",
")",
";",
"}",
"ret",
"[",
"hrpLength",
"]",
"=",
"0",
";",
"return",
"ret",
";",
"}"
] | Expand a HRP for use in checksum computation. | [
"Expand",
"a",
"HRP",
"for",
"use",
"in",
"checksum",
"computation",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Bech32.java#L66-L76 |
23,321 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Bech32.java | Bech32.verifyChecksum | private static boolean verifyChecksum(final String hrp, final byte[] values) {
byte[] hrpExpanded = expandHrp(hrp);
byte[] combined = new byte[hrpExpanded.length + values.length];
System.arraycopy(hrpExpanded, 0, combined, 0, hrpExpanded.length);
System.arraycopy(values, 0, combined, hrpExpanded.length, values.length);
return polymod(combined) == 1;
} | java | private static boolean verifyChecksum(final String hrp, final byte[] values) {
byte[] hrpExpanded = expandHrp(hrp);
byte[] combined = new byte[hrpExpanded.length + values.length];
System.arraycopy(hrpExpanded, 0, combined, 0, hrpExpanded.length);
System.arraycopy(values, 0, combined, hrpExpanded.length, values.length);
return polymod(combined) == 1;
} | [
"private",
"static",
"boolean",
"verifyChecksum",
"(",
"final",
"String",
"hrp",
",",
"final",
"byte",
"[",
"]",
"values",
")",
"{",
"byte",
"[",
"]",
"hrpExpanded",
"=",
"expandHrp",
"(",
"hrp",
")",
";",
"byte",
"[",
"]",
"combined",
"=",
"new",
"byte",
"[",
"hrpExpanded",
".",
"length",
"+",
"values",
".",
"length",
"]",
";",
"System",
".",
"arraycopy",
"(",
"hrpExpanded",
",",
"0",
",",
"combined",
",",
"0",
",",
"hrpExpanded",
".",
"length",
")",
";",
"System",
".",
"arraycopy",
"(",
"values",
",",
"0",
",",
"combined",
",",
"hrpExpanded",
".",
"length",
",",
"values",
".",
"length",
")",
";",
"return",
"polymod",
"(",
"combined",
")",
"==",
"1",
";",
"}"
] | Verify a checksum. | [
"Verify",
"a",
"checksum",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Bech32.java#L79-L85 |
23,322 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Bech32.java | Bech32.createChecksum | private static byte[] createChecksum(final String hrp, final byte[] values) {
byte[] hrpExpanded = expandHrp(hrp);
byte[] enc = new byte[hrpExpanded.length + values.length + 6];
System.arraycopy(hrpExpanded, 0, enc, 0, hrpExpanded.length);
System.arraycopy(values, 0, enc, hrpExpanded.length, values.length);
int mod = polymod(enc) ^ 1;
byte[] ret = new byte[6];
for (int i = 0; i < 6; ++i) {
ret[i] = (byte) ((mod >>> (5 * (5 - i))) & 31);
}
return ret;
} | java | private static byte[] createChecksum(final String hrp, final byte[] values) {
byte[] hrpExpanded = expandHrp(hrp);
byte[] enc = new byte[hrpExpanded.length + values.length + 6];
System.arraycopy(hrpExpanded, 0, enc, 0, hrpExpanded.length);
System.arraycopy(values, 0, enc, hrpExpanded.length, values.length);
int mod = polymod(enc) ^ 1;
byte[] ret = new byte[6];
for (int i = 0; i < 6; ++i) {
ret[i] = (byte) ((mod >>> (5 * (5 - i))) & 31);
}
return ret;
} | [
"private",
"static",
"byte",
"[",
"]",
"createChecksum",
"(",
"final",
"String",
"hrp",
",",
"final",
"byte",
"[",
"]",
"values",
")",
"{",
"byte",
"[",
"]",
"hrpExpanded",
"=",
"expandHrp",
"(",
"hrp",
")",
";",
"byte",
"[",
"]",
"enc",
"=",
"new",
"byte",
"[",
"hrpExpanded",
".",
"length",
"+",
"values",
".",
"length",
"+",
"6",
"]",
";",
"System",
".",
"arraycopy",
"(",
"hrpExpanded",
",",
"0",
",",
"enc",
",",
"0",
",",
"hrpExpanded",
".",
"length",
")",
";",
"System",
".",
"arraycopy",
"(",
"values",
",",
"0",
",",
"enc",
",",
"hrpExpanded",
".",
"length",
",",
"values",
".",
"length",
")",
";",
"int",
"mod",
"=",
"polymod",
"(",
"enc",
")",
"^",
"1",
";",
"byte",
"[",
"]",
"ret",
"=",
"new",
"byte",
"[",
"6",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"6",
";",
"++",
"i",
")",
"{",
"ret",
"[",
"i",
"]",
"=",
"(",
"byte",
")",
"(",
"(",
"mod",
">>>",
"(",
"5",
"*",
"(",
"5",
"-",
"i",
")",
")",
")",
"&",
"31",
")",
";",
"}",
"return",
"ret",
";",
"}"
] | Create a checksum. | [
"Create",
"a",
"checksum",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Bech32.java#L88-L99 |
23,323 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Bech32.java | Bech32.encode | public static String encode(String hrp, final byte[] values) {
checkArgument(hrp.length() >= 1, "Human-readable part is too short");
checkArgument(hrp.length() <= 83, "Human-readable part is too long");
hrp = hrp.toLowerCase(Locale.ROOT);
byte[] checksum = createChecksum(hrp, values);
byte[] combined = new byte[values.length + checksum.length];
System.arraycopy(values, 0, combined, 0, values.length);
System.arraycopy(checksum, 0, combined, values.length, checksum.length);
StringBuilder sb = new StringBuilder(hrp.length() + 1 + combined.length);
sb.append(hrp);
sb.append('1');
for (byte b : combined) {
sb.append(CHARSET.charAt(b));
}
return sb.toString();
} | java | public static String encode(String hrp, final byte[] values) {
checkArgument(hrp.length() >= 1, "Human-readable part is too short");
checkArgument(hrp.length() <= 83, "Human-readable part is too long");
hrp = hrp.toLowerCase(Locale.ROOT);
byte[] checksum = createChecksum(hrp, values);
byte[] combined = new byte[values.length + checksum.length];
System.arraycopy(values, 0, combined, 0, values.length);
System.arraycopy(checksum, 0, combined, values.length, checksum.length);
StringBuilder sb = new StringBuilder(hrp.length() + 1 + combined.length);
sb.append(hrp);
sb.append('1');
for (byte b : combined) {
sb.append(CHARSET.charAt(b));
}
return sb.toString();
} | [
"public",
"static",
"String",
"encode",
"(",
"String",
"hrp",
",",
"final",
"byte",
"[",
"]",
"values",
")",
"{",
"checkArgument",
"(",
"hrp",
".",
"length",
"(",
")",
">=",
"1",
",",
"\"Human-readable part is too short\"",
")",
";",
"checkArgument",
"(",
"hrp",
".",
"length",
"(",
")",
"<=",
"83",
",",
"\"Human-readable part is too long\"",
")",
";",
"hrp",
"=",
"hrp",
".",
"toLowerCase",
"(",
"Locale",
".",
"ROOT",
")",
";",
"byte",
"[",
"]",
"checksum",
"=",
"createChecksum",
"(",
"hrp",
",",
"values",
")",
";",
"byte",
"[",
"]",
"combined",
"=",
"new",
"byte",
"[",
"values",
".",
"length",
"+",
"checksum",
".",
"length",
"]",
";",
"System",
".",
"arraycopy",
"(",
"values",
",",
"0",
",",
"combined",
",",
"0",
",",
"values",
".",
"length",
")",
";",
"System",
".",
"arraycopy",
"(",
"checksum",
",",
"0",
",",
"combined",
",",
"values",
".",
"length",
",",
"checksum",
".",
"length",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"hrp",
".",
"length",
"(",
")",
"+",
"1",
"+",
"combined",
".",
"length",
")",
";",
"sb",
".",
"append",
"(",
"hrp",
")",
";",
"sb",
".",
"append",
"(",
"'",
"'",
")",
";",
"for",
"(",
"byte",
"b",
":",
"combined",
")",
"{",
"sb",
".",
"append",
"(",
"CHARSET",
".",
"charAt",
"(",
"b",
")",
")",
";",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Encode a Bech32 string. | [
"Encode",
"a",
"Bech32",
"string",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Bech32.java#L107-L122 |
23,324 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Bech32.java | Bech32.decode | public static Bech32Data decode(final String str) throws AddressFormatException {
boolean lower = false, upper = false;
if (str.length() < 8)
throw new AddressFormatException.InvalidDataLength("Input too short: " + str.length());
if (str.length() > 90)
throw new AddressFormatException.InvalidDataLength("Input too long: " + str.length());
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (c < 33 || c > 126) throw new AddressFormatException.InvalidCharacter(c, i);
if (c >= 'a' && c <= 'z') {
if (upper)
throw new AddressFormatException.InvalidCharacter(c, i);
lower = true;
}
if (c >= 'A' && c <= 'Z') {
if (lower)
throw new AddressFormatException.InvalidCharacter(c, i);
upper = true;
}
}
final int pos = str.lastIndexOf('1');
if (pos < 1) throw new AddressFormatException.InvalidPrefix("Missing human-readable part");
final int dataPartLength = str.length() - 1 - pos;
if (dataPartLength < 6) throw new AddressFormatException.InvalidDataLength("Data part too short: " + dataPartLength);
byte[] values = new byte[dataPartLength];
for (int i = 0; i < dataPartLength; ++i) {
char c = str.charAt(i + pos + 1);
if (CHARSET_REV[c] == -1) throw new AddressFormatException.InvalidCharacter(c, i + pos + 1);
values[i] = CHARSET_REV[c];
}
String hrp = str.substring(0, pos).toLowerCase(Locale.ROOT);
if (!verifyChecksum(hrp, values)) throw new AddressFormatException.InvalidChecksum();
return new Bech32Data(hrp, Arrays.copyOfRange(values, 0, values.length - 6));
} | java | public static Bech32Data decode(final String str) throws AddressFormatException {
boolean lower = false, upper = false;
if (str.length() < 8)
throw new AddressFormatException.InvalidDataLength("Input too short: " + str.length());
if (str.length() > 90)
throw new AddressFormatException.InvalidDataLength("Input too long: " + str.length());
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (c < 33 || c > 126) throw new AddressFormatException.InvalidCharacter(c, i);
if (c >= 'a' && c <= 'z') {
if (upper)
throw new AddressFormatException.InvalidCharacter(c, i);
lower = true;
}
if (c >= 'A' && c <= 'Z') {
if (lower)
throw new AddressFormatException.InvalidCharacter(c, i);
upper = true;
}
}
final int pos = str.lastIndexOf('1');
if (pos < 1) throw new AddressFormatException.InvalidPrefix("Missing human-readable part");
final int dataPartLength = str.length() - 1 - pos;
if (dataPartLength < 6) throw new AddressFormatException.InvalidDataLength("Data part too short: " + dataPartLength);
byte[] values = new byte[dataPartLength];
for (int i = 0; i < dataPartLength; ++i) {
char c = str.charAt(i + pos + 1);
if (CHARSET_REV[c] == -1) throw new AddressFormatException.InvalidCharacter(c, i + pos + 1);
values[i] = CHARSET_REV[c];
}
String hrp = str.substring(0, pos).toLowerCase(Locale.ROOT);
if (!verifyChecksum(hrp, values)) throw new AddressFormatException.InvalidChecksum();
return new Bech32Data(hrp, Arrays.copyOfRange(values, 0, values.length - 6));
} | [
"public",
"static",
"Bech32Data",
"decode",
"(",
"final",
"String",
"str",
")",
"throws",
"AddressFormatException",
"{",
"boolean",
"lower",
"=",
"false",
",",
"upper",
"=",
"false",
";",
"if",
"(",
"str",
".",
"length",
"(",
")",
"<",
"8",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidDataLength",
"(",
"\"Input too short: \"",
"+",
"str",
".",
"length",
"(",
")",
")",
";",
"if",
"(",
"str",
".",
"length",
"(",
")",
">",
"90",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidDataLength",
"(",
"\"Input too long: \"",
"+",
"str",
".",
"length",
"(",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"str",
".",
"length",
"(",
")",
";",
"++",
"i",
")",
"{",
"char",
"c",
"=",
"str",
".",
"charAt",
"(",
"i",
")",
";",
"if",
"(",
"c",
"<",
"33",
"||",
"c",
">",
"126",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidCharacter",
"(",
"c",
",",
"i",
")",
";",
"if",
"(",
"c",
">=",
"'",
"'",
"&&",
"c",
"<=",
"'",
"'",
")",
"{",
"if",
"(",
"upper",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidCharacter",
"(",
"c",
",",
"i",
")",
";",
"lower",
"=",
"true",
";",
"}",
"if",
"(",
"c",
">=",
"'",
"'",
"&&",
"c",
"<=",
"'",
"'",
")",
"{",
"if",
"(",
"lower",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidCharacter",
"(",
"c",
",",
"i",
")",
";",
"upper",
"=",
"true",
";",
"}",
"}",
"final",
"int",
"pos",
"=",
"str",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"pos",
"<",
"1",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidPrefix",
"(",
"\"Missing human-readable part\"",
")",
";",
"final",
"int",
"dataPartLength",
"=",
"str",
".",
"length",
"(",
")",
"-",
"1",
"-",
"pos",
";",
"if",
"(",
"dataPartLength",
"<",
"6",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidDataLength",
"(",
"\"Data part too short: \"",
"+",
"dataPartLength",
")",
";",
"byte",
"[",
"]",
"values",
"=",
"new",
"byte",
"[",
"dataPartLength",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"dataPartLength",
";",
"++",
"i",
")",
"{",
"char",
"c",
"=",
"str",
".",
"charAt",
"(",
"i",
"+",
"pos",
"+",
"1",
")",
";",
"if",
"(",
"CHARSET_REV",
"[",
"c",
"]",
"==",
"-",
"1",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidCharacter",
"(",
"c",
",",
"i",
"+",
"pos",
"+",
"1",
")",
";",
"values",
"[",
"i",
"]",
"=",
"CHARSET_REV",
"[",
"c",
"]",
";",
"}",
"String",
"hrp",
"=",
"str",
".",
"substring",
"(",
"0",
",",
"pos",
")",
".",
"toLowerCase",
"(",
"Locale",
".",
"ROOT",
")",
";",
"if",
"(",
"!",
"verifyChecksum",
"(",
"hrp",
",",
"values",
")",
")",
"throw",
"new",
"AddressFormatException",
".",
"InvalidChecksum",
"(",
")",
";",
"return",
"new",
"Bech32Data",
"(",
"hrp",
",",
"Arrays",
".",
"copyOfRange",
"(",
"values",
",",
"0",
",",
"values",
".",
"length",
"-",
"6",
")",
")",
";",
"}"
] | Decode a Bech32 string. | [
"Decode",
"a",
"Bech32",
"string",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Bech32.java#L125-L158 |
23,325 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionInput.java | TransactionInput.isCoinBase | public boolean isCoinBase() {
return outpoint.getHash().equals(Sha256Hash.ZERO_HASH) &&
(outpoint.getIndex() & 0xFFFFFFFFL) == 0xFFFFFFFFL; // -1 but all is serialized to the wire as unsigned int.
} | java | public boolean isCoinBase() {
return outpoint.getHash().equals(Sha256Hash.ZERO_HASH) &&
(outpoint.getIndex() & 0xFFFFFFFFL) == 0xFFFFFFFFL; // -1 but all is serialized to the wire as unsigned int.
} | [
"public",
"boolean",
"isCoinBase",
"(",
")",
"{",
"return",
"outpoint",
".",
"getHash",
"(",
")",
".",
"equals",
"(",
"Sha256Hash",
".",
"ZERO_HASH",
")",
"&&",
"(",
"outpoint",
".",
"getIndex",
"(",
")",
"&",
"0xFFFFFFFF",
"L",
")",
"==",
"0xFFFFFFFF",
"L",
";",
"// -1 but all is serialized to the wire as unsigned int.",
"}"
] | Coinbase transactions have special inputs with hashes of zero. If this is such an input, returns true. | [
"Coinbase",
"transactions",
"have",
"special",
"inputs",
"with",
"hashes",
"of",
"zero",
".",
"If",
"this",
"is",
"such",
"an",
"input",
"returns",
"true",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionInput.java#L182-L185 |
23,326 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionInput.java | TransactionInput.setScriptSig | public void setScriptSig(Script scriptSig) {
this.scriptSig = new WeakReference<>(checkNotNull(scriptSig));
// TODO: This should all be cleaned up so we have a consistent internal representation.
setScriptBytes(scriptSig.getProgram());
} | java | public void setScriptSig(Script scriptSig) {
this.scriptSig = new WeakReference<>(checkNotNull(scriptSig));
// TODO: This should all be cleaned up so we have a consistent internal representation.
setScriptBytes(scriptSig.getProgram());
} | [
"public",
"void",
"setScriptSig",
"(",
"Script",
"scriptSig",
")",
"{",
"this",
".",
"scriptSig",
"=",
"new",
"WeakReference",
"<>",
"(",
"checkNotNull",
"(",
"scriptSig",
")",
")",
";",
"// TODO: This should all be cleaned up so we have a consistent internal representation.",
"setScriptBytes",
"(",
"scriptSig",
".",
"getProgram",
"(",
")",
")",
";",
"}"
] | Set the given program as the scriptSig that is supposed to satisfy the connected output script. | [
"Set",
"the",
"given",
"program",
"as",
"the",
"scriptSig",
"that",
"is",
"supposed",
"to",
"satisfy",
"the",
"connected",
"output",
"script",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionInput.java#L203-L207 |
23,327 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionInput.java | TransactionInput.connect | public ConnectionResult connect(Map<Sha256Hash, Transaction> transactions, ConnectMode mode) {
Transaction tx = transactions.get(outpoint.getHash());
if (tx == null) {
return TransactionInput.ConnectionResult.NO_SUCH_TX;
}
return connect(tx, mode);
} | java | public ConnectionResult connect(Map<Sha256Hash, Transaction> transactions, ConnectMode mode) {
Transaction tx = transactions.get(outpoint.getHash());
if (tx == null) {
return TransactionInput.ConnectionResult.NO_SUCH_TX;
}
return connect(tx, mode);
} | [
"public",
"ConnectionResult",
"connect",
"(",
"Map",
"<",
"Sha256Hash",
",",
"Transaction",
">",
"transactions",
",",
"ConnectMode",
"mode",
")",
"{",
"Transaction",
"tx",
"=",
"transactions",
".",
"get",
"(",
"outpoint",
".",
"getHash",
"(",
")",
")",
";",
"if",
"(",
"tx",
"==",
"null",
")",
"{",
"return",
"TransactionInput",
".",
"ConnectionResult",
".",
"NO_SUCH_TX",
";",
"}",
"return",
"connect",
"(",
"tx",
",",
"mode",
")",
";",
"}"
] | Connects this input to the relevant output of the referenced transaction if it's in the given map.
Connecting means updating the internal pointers and spent flags. If the mode is to ABORT_ON_CONFLICT then
the spent output won't be changed, but the outpoint.fromTx pointer will still be updated.
@param transactions Map of txhash to transaction.
@param mode Whether to abort if there's a pre-existing connection or not.
@return NO_SUCH_TX if the prevtx wasn't found, ALREADY_SPENT if there was a conflict, SUCCESS if not. | [
"Connects",
"this",
"input",
"to",
"the",
"relevant",
"output",
"of",
"the",
"referenced",
"transaction",
"if",
"it",
"s",
"in",
"the",
"given",
"map",
".",
"Connecting",
"means",
"updating",
"the",
"internal",
"pointers",
"and",
"spent",
"flags",
".",
"If",
"the",
"mode",
"is",
"to",
"ABORT_ON_CONFLICT",
"then",
"the",
"spent",
"output",
"won",
"t",
"be",
"changed",
"but",
"the",
"outpoint",
".",
"fromTx",
"pointer",
"will",
"still",
"be",
"updated",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionInput.java#L351-L357 |
23,328 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionInput.java | TransactionInput.connect | public ConnectionResult connect(Transaction transaction, ConnectMode mode) {
if (!transaction.getTxId().equals(outpoint.getHash()))
return ConnectionResult.NO_SUCH_TX;
checkElementIndex((int) outpoint.getIndex(), transaction.getOutputs().size(), "Corrupt transaction");
TransactionOutput out = transaction.getOutput((int) outpoint.getIndex());
if (!out.isAvailableForSpending()) {
if (getParentTransaction().equals(outpoint.fromTx)) {
// Already connected.
return ConnectionResult.SUCCESS;
} else if (mode == ConnectMode.DISCONNECT_ON_CONFLICT) {
out.markAsUnspent();
} else if (mode == ConnectMode.ABORT_ON_CONFLICT) {
outpoint.fromTx = out.getParentTransaction();
return TransactionInput.ConnectionResult.ALREADY_SPENT;
}
}
connect(out);
return TransactionInput.ConnectionResult.SUCCESS;
} | java | public ConnectionResult connect(Transaction transaction, ConnectMode mode) {
if (!transaction.getTxId().equals(outpoint.getHash()))
return ConnectionResult.NO_SUCH_TX;
checkElementIndex((int) outpoint.getIndex(), transaction.getOutputs().size(), "Corrupt transaction");
TransactionOutput out = transaction.getOutput((int) outpoint.getIndex());
if (!out.isAvailableForSpending()) {
if (getParentTransaction().equals(outpoint.fromTx)) {
// Already connected.
return ConnectionResult.SUCCESS;
} else if (mode == ConnectMode.DISCONNECT_ON_CONFLICT) {
out.markAsUnspent();
} else if (mode == ConnectMode.ABORT_ON_CONFLICT) {
outpoint.fromTx = out.getParentTransaction();
return TransactionInput.ConnectionResult.ALREADY_SPENT;
}
}
connect(out);
return TransactionInput.ConnectionResult.SUCCESS;
} | [
"public",
"ConnectionResult",
"connect",
"(",
"Transaction",
"transaction",
",",
"ConnectMode",
"mode",
")",
"{",
"if",
"(",
"!",
"transaction",
".",
"getTxId",
"(",
")",
".",
"equals",
"(",
"outpoint",
".",
"getHash",
"(",
")",
")",
")",
"return",
"ConnectionResult",
".",
"NO_SUCH_TX",
";",
"checkElementIndex",
"(",
"(",
"int",
")",
"outpoint",
".",
"getIndex",
"(",
")",
",",
"transaction",
".",
"getOutputs",
"(",
")",
".",
"size",
"(",
")",
",",
"\"Corrupt transaction\"",
")",
";",
"TransactionOutput",
"out",
"=",
"transaction",
".",
"getOutput",
"(",
"(",
"int",
")",
"outpoint",
".",
"getIndex",
"(",
")",
")",
";",
"if",
"(",
"!",
"out",
".",
"isAvailableForSpending",
"(",
")",
")",
"{",
"if",
"(",
"getParentTransaction",
"(",
")",
".",
"equals",
"(",
"outpoint",
".",
"fromTx",
")",
")",
"{",
"// Already connected.",
"return",
"ConnectionResult",
".",
"SUCCESS",
";",
"}",
"else",
"if",
"(",
"mode",
"==",
"ConnectMode",
".",
"DISCONNECT_ON_CONFLICT",
")",
"{",
"out",
".",
"markAsUnspent",
"(",
")",
";",
"}",
"else",
"if",
"(",
"mode",
"==",
"ConnectMode",
".",
"ABORT_ON_CONFLICT",
")",
"{",
"outpoint",
".",
"fromTx",
"=",
"out",
".",
"getParentTransaction",
"(",
")",
";",
"return",
"TransactionInput",
".",
"ConnectionResult",
".",
"ALREADY_SPENT",
";",
"}",
"}",
"connect",
"(",
"out",
")",
";",
"return",
"TransactionInput",
".",
"ConnectionResult",
".",
"SUCCESS",
";",
"}"
] | Connects this input to the relevant output of the referenced transaction.
Connecting means updating the internal pointers and spent flags. If the mode is to ABORT_ON_CONFLICT then
the spent output won't be changed, but the outpoint.fromTx pointer will still be updated.
@param transaction The transaction to try.
@param mode Whether to abort if there's a pre-existing connection or not.
@return NO_SUCH_TX if transaction is not the prevtx, ALREADY_SPENT if there was a conflict, SUCCESS if not. | [
"Connects",
"this",
"input",
"to",
"the",
"relevant",
"output",
"of",
"the",
"referenced",
"transaction",
".",
"Connecting",
"means",
"updating",
"the",
"internal",
"pointers",
"and",
"spent",
"flags",
".",
"If",
"the",
"mode",
"is",
"to",
"ABORT_ON_CONFLICT",
"then",
"the",
"spent",
"output",
"won",
"t",
"be",
"changed",
"but",
"the",
"outpoint",
".",
"fromTx",
"pointer",
"will",
"still",
"be",
"updated",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionInput.java#L368-L386 |
23,329 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionInput.java | TransactionInput.disconnect | public boolean disconnect() {
TransactionOutput connectedOutput;
if (outpoint.fromTx != null) {
// The outpoint is connected using a "standard" wallet, disconnect it.
connectedOutput = outpoint.fromTx.getOutput((int) outpoint.getIndex());
outpoint.fromTx = null;
} else if (outpoint.connectedOutput != null) {
// The outpoint is connected using a UTXO based wallet, disconnect it.
connectedOutput = outpoint.connectedOutput;
outpoint.connectedOutput = null;
} else {
// The outpoint is not connected, do nothing.
return false;
}
if (connectedOutput != null && connectedOutput.getSpentBy() == this) {
// The outpoint was connected to an output, disconnect the output.
connectedOutput.markAsUnspent();
return true;
} else {
return false;
}
} | java | public boolean disconnect() {
TransactionOutput connectedOutput;
if (outpoint.fromTx != null) {
// The outpoint is connected using a "standard" wallet, disconnect it.
connectedOutput = outpoint.fromTx.getOutput((int) outpoint.getIndex());
outpoint.fromTx = null;
} else if (outpoint.connectedOutput != null) {
// The outpoint is connected using a UTXO based wallet, disconnect it.
connectedOutput = outpoint.connectedOutput;
outpoint.connectedOutput = null;
} else {
// The outpoint is not connected, do nothing.
return false;
}
if (connectedOutput != null && connectedOutput.getSpentBy() == this) {
// The outpoint was connected to an output, disconnect the output.
connectedOutput.markAsUnspent();
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"disconnect",
"(",
")",
"{",
"TransactionOutput",
"connectedOutput",
";",
"if",
"(",
"outpoint",
".",
"fromTx",
"!=",
"null",
")",
"{",
"// The outpoint is connected using a \"standard\" wallet, disconnect it.",
"connectedOutput",
"=",
"outpoint",
".",
"fromTx",
".",
"getOutput",
"(",
"(",
"int",
")",
"outpoint",
".",
"getIndex",
"(",
")",
")",
";",
"outpoint",
".",
"fromTx",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"outpoint",
".",
"connectedOutput",
"!=",
"null",
")",
"{",
"// The outpoint is connected using a UTXO based wallet, disconnect it.",
"connectedOutput",
"=",
"outpoint",
".",
"connectedOutput",
";",
"outpoint",
".",
"connectedOutput",
"=",
"null",
";",
"}",
"else",
"{",
"// The outpoint is not connected, do nothing.",
"return",
"false",
";",
"}",
"if",
"(",
"connectedOutput",
"!=",
"null",
"&&",
"connectedOutput",
".",
"getSpentBy",
"(",
")",
"==",
"this",
")",
"{",
"// The outpoint was connected to an output, disconnect the output.",
"connectedOutput",
".",
"markAsUnspent",
"(",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | If this input is connected, check the output is connected back to this input and release it if so, making
it spendable once again.
@return true if the disconnection took place, false if it was not connected. | [
"If",
"this",
"input",
"is",
"connected",
"check",
"the",
"output",
"is",
"connected",
"back",
"to",
"this",
"input",
"and",
"release",
"it",
"if",
"so",
"making",
"it",
"spendable",
"once",
"again",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionInput.java#L401-L423 |
23,330 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionInput.java | TransactionInput.verify | public void verify() throws VerificationException {
final Transaction fromTx = getOutpoint().fromTx;
long spendingIndex = getOutpoint().getIndex();
checkNotNull(fromTx, "Not connected");
final TransactionOutput output = fromTx.getOutput((int) spendingIndex);
verify(output);
} | java | public void verify() throws VerificationException {
final Transaction fromTx = getOutpoint().fromTx;
long spendingIndex = getOutpoint().getIndex();
checkNotNull(fromTx, "Not connected");
final TransactionOutput output = fromTx.getOutput((int) spendingIndex);
verify(output);
} | [
"public",
"void",
"verify",
"(",
")",
"throws",
"VerificationException",
"{",
"final",
"Transaction",
"fromTx",
"=",
"getOutpoint",
"(",
")",
".",
"fromTx",
";",
"long",
"spendingIndex",
"=",
"getOutpoint",
"(",
")",
".",
"getIndex",
"(",
")",
";",
"checkNotNull",
"(",
"fromTx",
",",
"\"Not connected\"",
")",
";",
"final",
"TransactionOutput",
"output",
"=",
"fromTx",
".",
"getOutput",
"(",
"(",
"int",
")",
"spendingIndex",
")",
";",
"verify",
"(",
"output",
")",
";",
"}"
] | For a connected transaction, runs the script against the connected pubkey and verifies they are correct.
@throws ScriptException if the script did not verify.
@throws VerificationException If the outpoint doesn't match the given output. | [
"For",
"a",
"connected",
"transaction",
"runs",
"the",
"script",
"against",
"the",
"connected",
"pubkey",
"and",
"verifies",
"they",
"are",
"correct",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionInput.java#L453-L459 |
23,331 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionInput.java | TransactionInput.verify | public void verify(TransactionOutput output) throws VerificationException {
if (output.parent != null) {
if (!getOutpoint().getHash().equals(output.getParentTransaction().getTxId()))
throw new VerificationException("This input does not refer to the tx containing the output.");
if (getOutpoint().getIndex() != output.getIndex())
throw new VerificationException("This input refers to a different output on the given tx.");
}
Script pubKey = output.getScriptPubKey();
getScriptSig().correctlySpends(getParentTransaction(), getIndex(), getWitness(), getValue(), pubKey,
Script.ALL_VERIFY_FLAGS);
} | java | public void verify(TransactionOutput output) throws VerificationException {
if (output.parent != null) {
if (!getOutpoint().getHash().equals(output.getParentTransaction().getTxId()))
throw new VerificationException("This input does not refer to the tx containing the output.");
if (getOutpoint().getIndex() != output.getIndex())
throw new VerificationException("This input refers to a different output on the given tx.");
}
Script pubKey = output.getScriptPubKey();
getScriptSig().correctlySpends(getParentTransaction(), getIndex(), getWitness(), getValue(), pubKey,
Script.ALL_VERIFY_FLAGS);
} | [
"public",
"void",
"verify",
"(",
"TransactionOutput",
"output",
")",
"throws",
"VerificationException",
"{",
"if",
"(",
"output",
".",
"parent",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"getOutpoint",
"(",
")",
".",
"getHash",
"(",
")",
".",
"equals",
"(",
"output",
".",
"getParentTransaction",
"(",
")",
".",
"getTxId",
"(",
")",
")",
")",
"throw",
"new",
"VerificationException",
"(",
"\"This input does not refer to the tx containing the output.\"",
")",
";",
"if",
"(",
"getOutpoint",
"(",
")",
".",
"getIndex",
"(",
")",
"!=",
"output",
".",
"getIndex",
"(",
")",
")",
"throw",
"new",
"VerificationException",
"(",
"\"This input refers to a different output on the given tx.\"",
")",
";",
"}",
"Script",
"pubKey",
"=",
"output",
".",
"getScriptPubKey",
"(",
")",
";",
"getScriptSig",
"(",
")",
".",
"correctlySpends",
"(",
"getParentTransaction",
"(",
")",
",",
"getIndex",
"(",
")",
",",
"getWitness",
"(",
")",
",",
"getValue",
"(",
")",
",",
"pubKey",
",",
"Script",
".",
"ALL_VERIFY_FLAGS",
")",
";",
"}"
] | Verifies that this input can spend the given output. Note that this input must be a part of a transaction.
Also note that the consistency of the outpoint will be checked, even if this input has not been connected.
@param output the output that this input is supposed to spend.
@throws ScriptException If the script doesn't verify.
@throws VerificationException If the outpoint doesn't match the given output. | [
"Verifies",
"that",
"this",
"input",
"can",
"spend",
"the",
"given",
"output",
".",
"Note",
"that",
"this",
"input",
"must",
"be",
"a",
"part",
"of",
"a",
"transaction",
".",
"Also",
"note",
"that",
"the",
"consistency",
"of",
"the",
"outpoint",
"will",
"be",
"checked",
"even",
"if",
"this",
"input",
"has",
"not",
"been",
"connected",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionInput.java#L469-L479 |
23,332 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/DeterministicSeed.java | DeterministicSeed.getMnemonicString | @Nullable
public String getMnemonicString() {
return mnemonicCode != null ? Utils.SPACE_JOINER.join(mnemonicCode) : null;
} | java | @Nullable
public String getMnemonicString() {
return mnemonicCode != null ? Utils.SPACE_JOINER.join(mnemonicCode) : null;
} | [
"@",
"Nullable",
"public",
"String",
"getMnemonicString",
"(",
")",
"{",
"return",
"mnemonicCode",
"!=",
"null",
"?",
"Utils",
".",
"SPACE_JOINER",
".",
"join",
"(",
"mnemonicCode",
")",
":",
"null",
";",
"}"
] | Get the mnemonic code as string, or null if unknown. | [
"Get",
"the",
"mnemonic",
"code",
"as",
"string",
"or",
"null",
"if",
"unknown",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/DeterministicSeed.java#L251-L254 |
23,333 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionOutPoint.java | TransactionOutPoint.getConnectedOutput | @Nullable
public TransactionOutput getConnectedOutput() {
if (fromTx != null) {
return fromTx.getOutputs().get((int) index);
} else if (connectedOutput != null) {
return connectedOutput;
}
return null;
} | java | @Nullable
public TransactionOutput getConnectedOutput() {
if (fromTx != null) {
return fromTx.getOutputs().get((int) index);
} else if (connectedOutput != null) {
return connectedOutput;
}
return null;
} | [
"@",
"Nullable",
"public",
"TransactionOutput",
"getConnectedOutput",
"(",
")",
"{",
"if",
"(",
"fromTx",
"!=",
"null",
")",
"{",
"return",
"fromTx",
".",
"getOutputs",
"(",
")",
".",
"get",
"(",
"(",
"int",
")",
"index",
")",
";",
"}",
"else",
"if",
"(",
"connectedOutput",
"!=",
"null",
")",
"{",
"return",
"connectedOutput",
";",
"}",
"return",
"null",
";",
"}"
] | An outpoint is a part of a transaction input that points to the output of another transaction. If we have both
sides in memory, and they have been linked together, this returns a pointer to the connected output, or null
if there is no such connection. | [
"An",
"outpoint",
"is",
"a",
"part",
"of",
"a",
"transaction",
"input",
"that",
"points",
"to",
"the",
"output",
"of",
"another",
"transaction",
".",
"If",
"we",
"have",
"both",
"sides",
"in",
"memory",
"and",
"they",
"have",
"been",
"linked",
"together",
"this",
"returns",
"a",
"pointer",
"to",
"the",
"connected",
"output",
"or",
"null",
"if",
"there",
"is",
"no",
"such",
"connection",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionOutPoint.java#L111-L119 |
23,334 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TransactionOutPoint.java | TransactionOutPoint.getConnectedRedeemData | @Nullable
public RedeemData getConnectedRedeemData(KeyBag keyBag) throws ScriptException {
TransactionOutput connectedOutput = getConnectedOutput();
checkNotNull(connectedOutput, "Input is not connected so cannot retrieve key");
Script connectedScript = connectedOutput.getScriptPubKey();
if (ScriptPattern.isP2PKH(connectedScript)) {
byte[] addressBytes = ScriptPattern.extractHashFromP2PKH(connectedScript);
return RedeemData.of(keyBag.findKeyFromPubKeyHash(addressBytes, Script.ScriptType.P2PKH), connectedScript);
} else if (ScriptPattern.isP2WPKH(connectedScript)) {
byte[] addressBytes = ScriptPattern.extractHashFromP2WH(connectedScript);
return RedeemData.of(keyBag.findKeyFromPubKeyHash(addressBytes, Script.ScriptType.P2WPKH), connectedScript);
} else if (ScriptPattern.isP2PK(connectedScript)) {
byte[] pubkeyBytes = ScriptPattern.extractKeyFromP2PK(connectedScript);
return RedeemData.of(keyBag.findKeyFromPubKey(pubkeyBytes), connectedScript);
} else if (ScriptPattern.isP2SH(connectedScript)) {
byte[] scriptHash = ScriptPattern.extractHashFromP2SH(connectedScript);
return keyBag.findRedeemDataFromScriptHash(scriptHash);
} else {
throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Could not understand form of connected output script: " + connectedScript);
}
} | java | @Nullable
public RedeemData getConnectedRedeemData(KeyBag keyBag) throws ScriptException {
TransactionOutput connectedOutput = getConnectedOutput();
checkNotNull(connectedOutput, "Input is not connected so cannot retrieve key");
Script connectedScript = connectedOutput.getScriptPubKey();
if (ScriptPattern.isP2PKH(connectedScript)) {
byte[] addressBytes = ScriptPattern.extractHashFromP2PKH(connectedScript);
return RedeemData.of(keyBag.findKeyFromPubKeyHash(addressBytes, Script.ScriptType.P2PKH), connectedScript);
} else if (ScriptPattern.isP2WPKH(connectedScript)) {
byte[] addressBytes = ScriptPattern.extractHashFromP2WH(connectedScript);
return RedeemData.of(keyBag.findKeyFromPubKeyHash(addressBytes, Script.ScriptType.P2WPKH), connectedScript);
} else if (ScriptPattern.isP2PK(connectedScript)) {
byte[] pubkeyBytes = ScriptPattern.extractKeyFromP2PK(connectedScript);
return RedeemData.of(keyBag.findKeyFromPubKey(pubkeyBytes), connectedScript);
} else if (ScriptPattern.isP2SH(connectedScript)) {
byte[] scriptHash = ScriptPattern.extractHashFromP2SH(connectedScript);
return keyBag.findRedeemDataFromScriptHash(scriptHash);
} else {
throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Could not understand form of connected output script: " + connectedScript);
}
} | [
"@",
"Nullable",
"public",
"RedeemData",
"getConnectedRedeemData",
"(",
"KeyBag",
"keyBag",
")",
"throws",
"ScriptException",
"{",
"TransactionOutput",
"connectedOutput",
"=",
"getConnectedOutput",
"(",
")",
";",
"checkNotNull",
"(",
"connectedOutput",
",",
"\"Input is not connected so cannot retrieve key\"",
")",
";",
"Script",
"connectedScript",
"=",
"connectedOutput",
".",
"getScriptPubKey",
"(",
")",
";",
"if",
"(",
"ScriptPattern",
".",
"isP2PKH",
"(",
"connectedScript",
")",
")",
"{",
"byte",
"[",
"]",
"addressBytes",
"=",
"ScriptPattern",
".",
"extractHashFromP2PKH",
"(",
"connectedScript",
")",
";",
"return",
"RedeemData",
".",
"of",
"(",
"keyBag",
".",
"findKeyFromPubKeyHash",
"(",
"addressBytes",
",",
"Script",
".",
"ScriptType",
".",
"P2PKH",
")",
",",
"connectedScript",
")",
";",
"}",
"else",
"if",
"(",
"ScriptPattern",
".",
"isP2WPKH",
"(",
"connectedScript",
")",
")",
"{",
"byte",
"[",
"]",
"addressBytes",
"=",
"ScriptPattern",
".",
"extractHashFromP2WH",
"(",
"connectedScript",
")",
";",
"return",
"RedeemData",
".",
"of",
"(",
"keyBag",
".",
"findKeyFromPubKeyHash",
"(",
"addressBytes",
",",
"Script",
".",
"ScriptType",
".",
"P2WPKH",
")",
",",
"connectedScript",
")",
";",
"}",
"else",
"if",
"(",
"ScriptPattern",
".",
"isP2PK",
"(",
"connectedScript",
")",
")",
"{",
"byte",
"[",
"]",
"pubkeyBytes",
"=",
"ScriptPattern",
".",
"extractKeyFromP2PK",
"(",
"connectedScript",
")",
";",
"return",
"RedeemData",
".",
"of",
"(",
"keyBag",
".",
"findKeyFromPubKey",
"(",
"pubkeyBytes",
")",
",",
"connectedScript",
")",
";",
"}",
"else",
"if",
"(",
"ScriptPattern",
".",
"isP2SH",
"(",
"connectedScript",
")",
")",
"{",
"byte",
"[",
"]",
"scriptHash",
"=",
"ScriptPattern",
".",
"extractHashFromP2SH",
"(",
"connectedScript",
")",
";",
"return",
"keyBag",
".",
"findRedeemDataFromScriptHash",
"(",
"scriptHash",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"ScriptException",
"(",
"ScriptError",
".",
"SCRIPT_ERR_UNKNOWN_ERROR",
",",
"\"Could not understand form of connected output script: \"",
"+",
"connectedScript",
")",
";",
"}",
"}"
] | Returns the RedeemData identified in the connected output, for either P2PKH, P2WPKH, P2PK
or P2SH scripts.
If the script forms cannot be understood, throws ScriptException.
@return a RedeemData or null if the connected data cannot be found in the wallet. | [
"Returns",
"the",
"RedeemData",
"identified",
"in",
"the",
"connected",
"output",
"for",
"either",
"P2PKH",
"P2WPKH",
"P2PK",
"or",
"P2SH",
"scripts",
".",
"If",
"the",
"script",
"forms",
"cannot",
"be",
"understood",
"throws",
"ScriptException",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TransactionOutPoint.java#L165-L185 |
23,335 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.setMaxConnections | public void setMaxConnections(int maxConnections) {
int adjustment;
lock.lock();
try {
this.maxConnections = maxConnections;
if (!isRunning()) return;
} finally {
lock.unlock();
}
// We may now have too many or too few open connections. Add more or drop some to get to the right amount.
adjustment = maxConnections - channels.getConnectedClientCount();
if (adjustment > 0)
triggerConnections();
if (adjustment < 0)
channels.closeConnections(-adjustment);
} | java | public void setMaxConnections(int maxConnections) {
int adjustment;
lock.lock();
try {
this.maxConnections = maxConnections;
if (!isRunning()) return;
} finally {
lock.unlock();
}
// We may now have too many or too few open connections. Add more or drop some to get to the right amount.
adjustment = maxConnections - channels.getConnectedClientCount();
if (adjustment > 0)
triggerConnections();
if (adjustment < 0)
channels.closeConnections(-adjustment);
} | [
"public",
"void",
"setMaxConnections",
"(",
"int",
"maxConnections",
")",
"{",
"int",
"adjustment",
";",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"this",
".",
"maxConnections",
"=",
"maxConnections",
";",
"if",
"(",
"!",
"isRunning",
"(",
")",
")",
"return",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"// We may now have too many or too few open connections. Add more or drop some to get to the right amount.",
"adjustment",
"=",
"maxConnections",
"-",
"channels",
".",
"getConnectedClientCount",
"(",
")",
";",
"if",
"(",
"adjustment",
">",
"0",
")",
"triggerConnections",
"(",
")",
";",
"if",
"(",
"adjustment",
"<",
"0",
")",
"channels",
".",
"closeConnections",
"(",
"-",
"adjustment",
")",
";",
"}"
] | Adjusts the desired number of connections that we will create to peers. Note that if there are already peers
open and the new value is lower than the current number of peers, those connections will be terminated. Likewise
if there aren't enough current connections to meet the new requested max size, some will be added. | [
"Adjusts",
"the",
"desired",
"number",
"of",
"connections",
"that",
"we",
"will",
"create",
"to",
"peers",
".",
"Note",
"that",
"if",
"there",
"are",
"already",
"peers",
"open",
"and",
"the",
"new",
"value",
"is",
"lower",
"than",
"the",
"current",
"number",
"of",
"peers",
"those",
"connections",
"will",
"be",
"terminated",
".",
"Likewise",
"if",
"there",
"aren",
"t",
"enough",
"current",
"connections",
"to",
"meet",
"the",
"new",
"requested",
"max",
"size",
"some",
"will",
"be",
"added",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L391-L407 |
23,336 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.updateVersionMessageRelayTxesBeforeFilter | private void updateVersionMessageRelayTxesBeforeFilter(VersionMessage ver) {
// We will provide the remote node with a bloom filter (ie they shouldn't relay yet)
// if chain == null || !chain.shouldVerifyTransactions() and a wallet is added and bloom filters are enabled
// Note that the default here means that no tx invs will be received if no wallet is ever added
lock.lock();
try {
boolean spvMode = chain != null && !chain.shouldVerifyTransactions();
boolean willSendFilter = spvMode && peerFilterProviders.size() > 0 && vBloomFilteringEnabled;
ver.relayTxesBeforeFilter = !willSendFilter;
} finally {
lock.unlock();
}
} | java | private void updateVersionMessageRelayTxesBeforeFilter(VersionMessage ver) {
// We will provide the remote node with a bloom filter (ie they shouldn't relay yet)
// if chain == null || !chain.shouldVerifyTransactions() and a wallet is added and bloom filters are enabled
// Note that the default here means that no tx invs will be received if no wallet is ever added
lock.lock();
try {
boolean spvMode = chain != null && !chain.shouldVerifyTransactions();
boolean willSendFilter = spvMode && peerFilterProviders.size() > 0 && vBloomFilteringEnabled;
ver.relayTxesBeforeFilter = !willSendFilter;
} finally {
lock.unlock();
}
} | [
"private",
"void",
"updateVersionMessageRelayTxesBeforeFilter",
"(",
"VersionMessage",
"ver",
")",
"{",
"// We will provide the remote node with a bloom filter (ie they shouldn't relay yet)",
"// if chain == null || !chain.shouldVerifyTransactions() and a wallet is added and bloom filters are enabled",
"// Note that the default here means that no tx invs will be received if no wallet is ever added",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"boolean",
"spvMode",
"=",
"chain",
"!=",
"null",
"&&",
"!",
"chain",
".",
"shouldVerifyTransactions",
"(",
")",
";",
"boolean",
"willSendFilter",
"=",
"spvMode",
"&&",
"peerFilterProviders",
".",
"size",
"(",
")",
">",
"0",
"&&",
"vBloomFilteringEnabled",
";",
"ver",
".",
"relayTxesBeforeFilter",
"=",
"!",
"willSendFilter",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Updates the relayTxesBeforeFilter flag of ver | [
"Updates",
"the",
"relayTxesBeforeFilter",
"flag",
"of",
"ver"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L605-L617 |
23,337 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.addAddress | public void addAddress(PeerAddress peerAddress) {
int newMax;
lock.lock();
try {
if (addInactive(peerAddress)) {
newMax = getMaxConnections() + 1;
setMaxConnections(newMax);
}
} finally {
lock.unlock();
}
} | java | public void addAddress(PeerAddress peerAddress) {
int newMax;
lock.lock();
try {
if (addInactive(peerAddress)) {
newMax = getMaxConnections() + 1;
setMaxConnections(newMax);
}
} finally {
lock.unlock();
}
} | [
"public",
"void",
"addAddress",
"(",
"PeerAddress",
"peerAddress",
")",
"{",
"int",
"newMax",
";",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"addInactive",
"(",
"peerAddress",
")",
")",
"{",
"newMax",
"=",
"getMaxConnections",
"(",
")",
"+",
"1",
";",
"setMaxConnections",
"(",
"newMax",
")",
";",
"}",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Add an address to the list of potential peers to connect to. It won't necessarily be used unless there's a need
to build new connections to reach the max connection count.
@param peerAddress IP/port to use. | [
"Add",
"an",
"address",
"to",
"the",
"list",
"of",
"potential",
"peers",
"to",
"connect",
"to",
".",
"It",
"won",
"t",
"necessarily",
"be",
"used",
"unless",
"there",
"s",
"a",
"need",
"to",
"build",
"new",
"connections",
"to",
"reach",
"the",
"max",
"connection",
"count",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L857-L868 |
23,338 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.addInactive | private boolean addInactive(PeerAddress peerAddress) {
lock.lock();
try {
// Deduplicate
if (backoffMap.containsKey(peerAddress))
return false;
backoffMap.put(peerAddress, new ExponentialBackoff(peerBackoffParams));
inactives.offer(peerAddress);
return true;
} finally {
lock.unlock();
}
} | java | private boolean addInactive(PeerAddress peerAddress) {
lock.lock();
try {
// Deduplicate
if (backoffMap.containsKey(peerAddress))
return false;
backoffMap.put(peerAddress, new ExponentialBackoff(peerBackoffParams));
inactives.offer(peerAddress);
return true;
} finally {
lock.unlock();
}
} | [
"private",
"boolean",
"addInactive",
"(",
"PeerAddress",
"peerAddress",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"// Deduplicate",
"if",
"(",
"backoffMap",
".",
"containsKey",
"(",
"peerAddress",
")",
")",
"return",
"false",
";",
"backoffMap",
".",
"put",
"(",
"peerAddress",
",",
"new",
"ExponentialBackoff",
"(",
"peerBackoffParams",
")",
")",
";",
"inactives",
".",
"offer",
"(",
"peerAddress",
")",
";",
"return",
"true",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Returns true if it was added, false if it was already there. | [
"Returns",
"true",
"if",
"it",
"was",
"added",
"false",
"if",
"it",
"was",
"already",
"there",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L872-L884 |
23,339 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.setRequiredServices | public void setRequiredServices(long requiredServices) {
lock.lock();
try {
this.requiredServices = requiredServices;
peerDiscoverers.clear();
addPeerDiscovery(MultiplexingDiscovery.forServices(params, requiredServices));
} finally {
lock.unlock();
}
} | java | public void setRequiredServices(long requiredServices) {
lock.lock();
try {
this.requiredServices = requiredServices;
peerDiscoverers.clear();
addPeerDiscovery(MultiplexingDiscovery.forServices(params, requiredServices));
} finally {
lock.unlock();
}
} | [
"public",
"void",
"setRequiredServices",
"(",
"long",
"requiredServices",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"this",
".",
"requiredServices",
"=",
"requiredServices",
";",
"peerDiscoverers",
".",
"clear",
"(",
")",
";",
"addPeerDiscovery",
"(",
"MultiplexingDiscovery",
".",
"forServices",
"(",
"params",
",",
"requiredServices",
")",
")",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Convenience for connecting only to peers that can serve specific services. It will configure suitable peer
discoveries.
@param requiredServices Required services as a bitmask, e.g. {@link VersionMessage#NODE_NETWORK}. | [
"Convenience",
"for",
"connecting",
"only",
"to",
"peers",
"that",
"can",
"serve",
"specific",
"services",
".",
"It",
"will",
"configure",
"suitable",
"peer",
"discoveries",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L891-L900 |
23,340 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.addPeerDiscovery | public void addPeerDiscovery(PeerDiscovery peerDiscovery) {
lock.lock();
try {
if (getMaxConnections() == 0)
setMaxConnections(DEFAULT_CONNECTIONS);
peerDiscoverers.add(peerDiscovery);
} finally {
lock.unlock();
}
} | java | public void addPeerDiscovery(PeerDiscovery peerDiscovery) {
lock.lock();
try {
if (getMaxConnections() == 0)
setMaxConnections(DEFAULT_CONNECTIONS);
peerDiscoverers.add(peerDiscovery);
} finally {
lock.unlock();
}
} | [
"public",
"void",
"addPeerDiscovery",
"(",
"PeerDiscovery",
"peerDiscovery",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"getMaxConnections",
"(",
")",
"==",
"0",
")",
"setMaxConnections",
"(",
"DEFAULT_CONNECTIONS",
")",
";",
"peerDiscoverers",
".",
"add",
"(",
"peerDiscovery",
")",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Add addresses from a discovery source to the list of potential peers to connect to. If max connections has not
been configured, or set to zero, then it's set to the default at this point. | [
"Add",
"addresses",
"from",
"a",
"discovery",
"source",
"to",
"the",
"list",
"of",
"potential",
"peers",
"to",
"connect",
"to",
".",
"If",
"max",
"connections",
"has",
"not",
"been",
"configured",
"or",
"set",
"to",
"zero",
"then",
"it",
"s",
"set",
"to",
"the",
"default",
"at",
"this",
"point",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L911-L920 |
23,341 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.discoverPeers | protected int discoverPeers() {
// Don't hold the lock whilst doing peer discovery: it can take a long time and cause high API latency.
checkState(!lock.isHeldByCurrentThread());
int maxPeersToDiscoverCount = this.vMaxPeersToDiscoverCount;
long peerDiscoveryTimeoutMillis = this.vPeerDiscoveryTimeoutMillis;
final Stopwatch watch = Stopwatch.createStarted();
final List<PeerAddress> addressList = Lists.newLinkedList();
for (PeerDiscovery peerDiscovery : peerDiscoverers /* COW */) {
InetSocketAddress[] addresses;
try {
addresses = peerDiscovery.getPeers(requiredServices, peerDiscoveryTimeoutMillis, TimeUnit.MILLISECONDS);
} catch (PeerDiscoveryException e) {
log.warn(e.getMessage());
continue;
}
for (InetSocketAddress address : addresses) addressList.add(new PeerAddress(params, address));
if (addressList.size() >= maxPeersToDiscoverCount) break;
}
if (!addressList.isEmpty()) {
for (PeerAddress address : addressList) {
addInactive(address);
}
final ImmutableSet<PeerAddress> peersDiscoveredSet = ImmutableSet.copyOf(addressList);
for (final ListenerRegistration<PeerDiscoveredEventListener> registration : peerDiscoveredEventListeners /* COW */) {
registration.executor.execute(new Runnable() {
@Override
public void run() {
registration.listener.onPeersDiscovered(peersDiscoveredSet);
}
});
}
}
watch.stop();
log.info("Peer discovery took {} and returned {} items", watch, addressList.size());
return addressList.size();
} | java | protected int discoverPeers() {
// Don't hold the lock whilst doing peer discovery: it can take a long time and cause high API latency.
checkState(!lock.isHeldByCurrentThread());
int maxPeersToDiscoverCount = this.vMaxPeersToDiscoverCount;
long peerDiscoveryTimeoutMillis = this.vPeerDiscoveryTimeoutMillis;
final Stopwatch watch = Stopwatch.createStarted();
final List<PeerAddress> addressList = Lists.newLinkedList();
for (PeerDiscovery peerDiscovery : peerDiscoverers /* COW */) {
InetSocketAddress[] addresses;
try {
addresses = peerDiscovery.getPeers(requiredServices, peerDiscoveryTimeoutMillis, TimeUnit.MILLISECONDS);
} catch (PeerDiscoveryException e) {
log.warn(e.getMessage());
continue;
}
for (InetSocketAddress address : addresses) addressList.add(new PeerAddress(params, address));
if (addressList.size() >= maxPeersToDiscoverCount) break;
}
if (!addressList.isEmpty()) {
for (PeerAddress address : addressList) {
addInactive(address);
}
final ImmutableSet<PeerAddress> peersDiscoveredSet = ImmutableSet.copyOf(addressList);
for (final ListenerRegistration<PeerDiscoveredEventListener> registration : peerDiscoveredEventListeners /* COW */) {
registration.executor.execute(new Runnable() {
@Override
public void run() {
registration.listener.onPeersDiscovered(peersDiscoveredSet);
}
});
}
}
watch.stop();
log.info("Peer discovery took {} and returned {} items", watch, addressList.size());
return addressList.size();
} | [
"protected",
"int",
"discoverPeers",
"(",
")",
"{",
"// Don't hold the lock whilst doing peer discovery: it can take a long time and cause high API latency.",
"checkState",
"(",
"!",
"lock",
".",
"isHeldByCurrentThread",
"(",
")",
")",
";",
"int",
"maxPeersToDiscoverCount",
"=",
"this",
".",
"vMaxPeersToDiscoverCount",
";",
"long",
"peerDiscoveryTimeoutMillis",
"=",
"this",
".",
"vPeerDiscoveryTimeoutMillis",
";",
"final",
"Stopwatch",
"watch",
"=",
"Stopwatch",
".",
"createStarted",
"(",
")",
";",
"final",
"List",
"<",
"PeerAddress",
">",
"addressList",
"=",
"Lists",
".",
"newLinkedList",
"(",
")",
";",
"for",
"(",
"PeerDiscovery",
"peerDiscovery",
":",
"peerDiscoverers",
"/* COW */",
")",
"{",
"InetSocketAddress",
"[",
"]",
"addresses",
";",
"try",
"{",
"addresses",
"=",
"peerDiscovery",
".",
"getPeers",
"(",
"requiredServices",
",",
"peerDiscoveryTimeoutMillis",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"}",
"catch",
"(",
"PeerDiscoveryException",
"e",
")",
"{",
"log",
".",
"warn",
"(",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"continue",
";",
"}",
"for",
"(",
"InetSocketAddress",
"address",
":",
"addresses",
")",
"addressList",
".",
"(",
"new",
"PeerAddress",
"(",
"params",
",",
"address",
")",
")",
";",
"if",
"(",
"addressList",
".",
"size",
"(",
")",
">=",
"maxPeersToDiscoverCount",
")",
"break",
";",
"}",
"if",
"(",
"!",
"addressList",
".",
"isEmpty",
"(",
")",
")",
"{",
"for",
"(",
"PeerAddress",
"address",
":",
"addressList",
")",
"{",
"addInactive",
"(",
"address",
")",
";",
"}",
"final",
"ImmutableSet",
"<",
"PeerAddress",
">",
"peersDiscoveredSet",
"=",
"ImmutableSet",
".",
"copyOf",
"(",
"addressList",
")",
";",
"for",
"(",
"final",
"ListenerRegistration",
"<",
"PeerDiscoveredEventListener",
">",
"registration",
":",
"peerDiscoveredEventListeners",
"/* COW */",
")",
"{",
"registration",
".",
"executor",
".",
"execute",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"registration",
".",
"listener",
".",
"onPeersDiscovered",
"(",
"peersDiscoveredSet",
")",
";",
"}",
"}",
")",
";",
"}",
"}",
"watch",
".",
"stop",
"(",
")",
";",
"log",
".",
"info",
"(",
"\"Peer discovery took {} and returned {} items\"",
",",
"watch",
",",
"addressList",
".",
"size",
"(",
")",
")",
";",
"return",
"addressList",
".",
"size",
"(",
")",
";",
"}"
] | Returns number of discovered peers. | [
"Returns",
"number",
"of",
"discovered",
"peers",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L923-L958 |
23,342 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.startAsync | public ListenableFuture startAsync() {
// This is run in a background thread by the Service implementation.
if (chain == null) {
// Just try to help catch what might be a programming error.
log.warn("Starting up with no attached block chain. Did you forget to pass one to the constructor?");
}
checkState(!vUsedUp, "Cannot start a peer group twice");
vRunning = true;
vUsedUp = true;
executorStartupLatch.countDown();
// We do blocking waits during startup, so run on the executor thread.
return executor.submit(new Runnable() {
@Override
public void run() {
try {
log.info("Starting ...");
channels.startAsync();
channels.awaitRunning();
triggerConnections();
setupPinging();
} catch (Throwable e) {
log.error("Exception when starting up", e); // The executor swallows exceptions :(
}
}
});
} | java | public ListenableFuture startAsync() {
// This is run in a background thread by the Service implementation.
if (chain == null) {
// Just try to help catch what might be a programming error.
log.warn("Starting up with no attached block chain. Did you forget to pass one to the constructor?");
}
checkState(!vUsedUp, "Cannot start a peer group twice");
vRunning = true;
vUsedUp = true;
executorStartupLatch.countDown();
// We do blocking waits during startup, so run on the executor thread.
return executor.submit(new Runnable() {
@Override
public void run() {
try {
log.info("Starting ...");
channels.startAsync();
channels.awaitRunning();
triggerConnections();
setupPinging();
} catch (Throwable e) {
log.error("Exception when starting up", e); // The executor swallows exceptions :(
}
}
});
} | [
"public",
"ListenableFuture",
"startAsync",
"(",
")",
"{",
"// This is run in a background thread by the Service implementation.",
"if",
"(",
"chain",
"==",
"null",
")",
"{",
"// Just try to help catch what might be a programming error.",
"log",
".",
"warn",
"(",
"\"Starting up with no attached block chain. Did you forget to pass one to the constructor?\"",
")",
";",
"}",
"checkState",
"(",
"!",
"vUsedUp",
",",
"\"Cannot start a peer group twice\"",
")",
";",
"vRunning",
"=",
"true",
";",
"vUsedUp",
"=",
"true",
";",
"executorStartupLatch",
".",
"countDown",
"(",
")",
";",
"// We do blocking waits during startup, so run on the executor thread.",
"return",
"executor",
".",
"submit",
"(",
"new",
"Runnable",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"log",
".",
"info",
"(",
"\"Starting ...\"",
")",
";",
"channels",
".",
"startAsync",
"(",
")",
";",
"channels",
".",
"awaitRunning",
"(",
")",
";",
"triggerConnections",
"(",
")",
";",
"setupPinging",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Exception when starting up\"",
",",
"e",
")",
";",
"// The executor swallows exceptions :(",
"}",
"}",
"}",
")",
";",
"}"
] | Starts the PeerGroup and begins network activity.
@return A future that completes when first connection activity has been triggered (note: not first connection made). | [
"Starts",
"the",
"PeerGroup",
"and",
"begins",
"network",
"activity",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L1012-L1037 |
23,343 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.stop | public void stop() {
try {
Stopwatch watch = Stopwatch.createStarted();
stopAsync();
log.info("Awaiting PeerGroup shutdown ...");
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
log.info("... took {}", watch);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} | java | public void stop() {
try {
Stopwatch watch = Stopwatch.createStarted();
stopAsync();
log.info("Awaiting PeerGroup shutdown ...");
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
log.info("... took {}", watch);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} | [
"public",
"void",
"stop",
"(",
")",
"{",
"try",
"{",
"Stopwatch",
"watch",
"=",
"Stopwatch",
".",
"createStarted",
"(",
")",
";",
"stopAsync",
"(",
")",
";",
"log",
".",
"info",
"(",
"\"Awaiting PeerGroup shutdown ...\"",
")",
";",
"executor",
".",
"awaitTermination",
"(",
"Long",
".",
"MAX_VALUE",
",",
"TimeUnit",
".",
"SECONDS",
")",
";",
"log",
".",
"info",
"(",
"\"... took {}\"",
",",
"watch",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] | Does a blocking stop | [
"Does",
"a",
"blocking",
"stop"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L1073-L1083 |
23,344 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.removeWallet | public void removeWallet(Wallet wallet) {
wallets.remove(checkNotNull(wallet));
peerFilterProviders.remove(wallet);
wallet.removeCoinsReceivedEventListener(walletCoinsReceivedEventListener);
wallet.removeKeyChainEventListener(walletKeyEventListener);
wallet.removeScriptsChangeEventListener(walletScriptsEventListener);
wallet.setTransactionBroadcaster(null);
for (Peer peer : peers) {
peer.removeWallet(wallet);
}
} | java | public void removeWallet(Wallet wallet) {
wallets.remove(checkNotNull(wallet));
peerFilterProviders.remove(wallet);
wallet.removeCoinsReceivedEventListener(walletCoinsReceivedEventListener);
wallet.removeKeyChainEventListener(walletKeyEventListener);
wallet.removeScriptsChangeEventListener(walletScriptsEventListener);
wallet.setTransactionBroadcaster(null);
for (Peer peer : peers) {
peer.removeWallet(wallet);
}
} | [
"public",
"void",
"removeWallet",
"(",
"Wallet",
"wallet",
")",
"{",
"wallets",
".",
"remove",
"(",
"checkNotNull",
"(",
"wallet",
")",
")",
";",
"peerFilterProviders",
".",
"remove",
"(",
"wallet",
")",
";",
"wallet",
".",
"removeCoinsReceivedEventListener",
"(",
"walletCoinsReceivedEventListener",
")",
";",
"wallet",
".",
"removeKeyChainEventListener",
"(",
"walletKeyEventListener",
")",
";",
"wallet",
".",
"removeScriptsChangeEventListener",
"(",
"walletScriptsEventListener",
")",
";",
"wallet",
".",
"setTransactionBroadcaster",
"(",
"null",
")",
";",
"for",
"(",
"Peer",
"peer",
":",
"peers",
")",
"{",
"peer",
".",
"removeWallet",
"(",
"wallet",
")",
";",
"}",
"}"
] | Unlinks the given wallet so it no longer receives broadcast transactions or has its transactions announced. | [
"Unlinks",
"the",
"given",
"wallet",
"so",
"it",
"no",
"longer",
"receives",
"broadcast",
"transactions",
"or",
"has",
"its",
"transactions",
"announced",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L1177-L1187 |
23,345 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.connectToLocalHost | @Nullable
public Peer connectToLocalHost() {
lock.lock();
try {
final PeerAddress localhost = PeerAddress.localhost(params);
backoffMap.put(localhost, new ExponentialBackoff(peerBackoffParams));
return connectTo(localhost, true, vConnectTimeoutMillis);
} finally {
lock.unlock();
}
} | java | @Nullable
public Peer connectToLocalHost() {
lock.lock();
try {
final PeerAddress localhost = PeerAddress.localhost(params);
backoffMap.put(localhost, new ExponentialBackoff(peerBackoffParams));
return connectTo(localhost, true, vConnectTimeoutMillis);
} finally {
lock.unlock();
}
} | [
"@",
"Nullable",
"public",
"Peer",
"connectToLocalHost",
"(",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"final",
"PeerAddress",
"localhost",
"=",
"PeerAddress",
".",
"localhost",
"(",
"params",
")",
";",
"backoffMap",
".",
"put",
"(",
"localhost",
",",
"new",
"ExponentialBackoff",
"(",
"peerBackoffParams",
")",
")",
";",
"return",
"connectTo",
"(",
"localhost",
",",
"true",
",",
"vConnectTimeoutMillis",
")",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Helper for forcing a connection to localhost. Useful when using regtest mode. Returns the peer object. | [
"Helper",
"for",
"forcing",
"a",
"connection",
"to",
"localhost",
".",
"Useful",
"when",
"using",
"regtest",
"mode",
".",
"Returns",
"the",
"peer",
"object",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L1322-L1332 |
23,346 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.connectTo | @Nullable @GuardedBy("lock")
protected Peer connectTo(PeerAddress address, boolean incrementMaxConnections, int connectTimeoutMillis) {
checkState(lock.isHeldByCurrentThread());
VersionMessage ver = getVersionMessage().duplicate();
ver.bestHeight = chain == null ? 0 : chain.getBestChainHeight();
ver.time = Utils.currentTimeSeconds();
ver.receivingAddr = address;
ver.receivingAddr.setParent(ver);
Peer peer = createPeer(address, ver);
peer.addConnectedEventListener(Threading.SAME_THREAD, startupListener);
peer.addDisconnectedEventListener(Threading.SAME_THREAD, startupListener);
peer.setMinProtocolVersion(vMinRequiredProtocolVersion);
pendingPeers.add(peer);
try {
log.info("Attempting connection to {} ({} connected, {} pending, {} max)", address,
peers.size(), pendingPeers.size(), maxConnections);
ListenableFuture<SocketAddress> future = channels.openConnection(address.toSocketAddress(), peer);
if (future.isDone())
Uninterruptibles.getUninterruptibly(future);
} catch (ExecutionException e) {
Throwable cause = Throwables.getRootCause(e);
log.warn("Failed to connect to " + address + ": " + cause.getMessage());
handlePeerDeath(peer, cause);
return null;
}
peer.setSocketTimeout(connectTimeoutMillis);
// When the channel has connected and version negotiated successfully, handleNewPeer will end up being called on
// a worker thread.
if (incrementMaxConnections) {
// We don't use setMaxConnections here as that would trigger a recursive attempt to establish a new
// outbound connection.
maxConnections++;
}
return peer;
} | java | @Nullable @GuardedBy("lock")
protected Peer connectTo(PeerAddress address, boolean incrementMaxConnections, int connectTimeoutMillis) {
checkState(lock.isHeldByCurrentThread());
VersionMessage ver = getVersionMessage().duplicate();
ver.bestHeight = chain == null ? 0 : chain.getBestChainHeight();
ver.time = Utils.currentTimeSeconds();
ver.receivingAddr = address;
ver.receivingAddr.setParent(ver);
Peer peer = createPeer(address, ver);
peer.addConnectedEventListener(Threading.SAME_THREAD, startupListener);
peer.addDisconnectedEventListener(Threading.SAME_THREAD, startupListener);
peer.setMinProtocolVersion(vMinRequiredProtocolVersion);
pendingPeers.add(peer);
try {
log.info("Attempting connection to {} ({} connected, {} pending, {} max)", address,
peers.size(), pendingPeers.size(), maxConnections);
ListenableFuture<SocketAddress> future = channels.openConnection(address.toSocketAddress(), peer);
if (future.isDone())
Uninterruptibles.getUninterruptibly(future);
} catch (ExecutionException e) {
Throwable cause = Throwables.getRootCause(e);
log.warn("Failed to connect to " + address + ": " + cause.getMessage());
handlePeerDeath(peer, cause);
return null;
}
peer.setSocketTimeout(connectTimeoutMillis);
// When the channel has connected and version negotiated successfully, handleNewPeer will end up being called on
// a worker thread.
if (incrementMaxConnections) {
// We don't use setMaxConnections here as that would trigger a recursive attempt to establish a new
// outbound connection.
maxConnections++;
}
return peer;
} | [
"@",
"Nullable",
"@",
"GuardedBy",
"(",
"\"lock\"",
")",
"protected",
"Peer",
"connectTo",
"(",
"PeerAddress",
"address",
",",
"boolean",
"incrementMaxConnections",
",",
"int",
"connectTimeoutMillis",
")",
"{",
"checkState",
"(",
"lock",
".",
"isHeldByCurrentThread",
"(",
")",
")",
";",
"VersionMessage",
"ver",
"=",
"getVersionMessage",
"(",
")",
".",
"duplicate",
"(",
")",
";",
"ver",
".",
"bestHeight",
"=",
"chain",
"==",
"null",
"?",
"0",
":",
"chain",
".",
"getBestChainHeight",
"(",
")",
";",
"ver",
".",
"time",
"=",
"Utils",
".",
"currentTimeSeconds",
"(",
")",
";",
"ver",
".",
"receivingAddr",
"=",
"address",
";",
"ver",
".",
"receivingAddr",
".",
"setParent",
"(",
"ver",
")",
";",
"Peer",
"peer",
"=",
"createPeer",
"(",
"address",
",",
"ver",
")",
";",
"peer",
".",
"addConnectedEventListener",
"(",
"Threading",
".",
"SAME_THREAD",
",",
"startupListener",
")",
";",
"peer",
".",
"addDisconnectedEventListener",
"(",
"Threading",
".",
"SAME_THREAD",
",",
"startupListener",
")",
";",
"peer",
".",
"setMinProtocolVersion",
"(",
"vMinRequiredProtocolVersion",
")",
";",
"pendingPeers",
".",
"add",
"(",
"peer",
")",
";",
"try",
"{",
"log",
".",
"info",
"(",
"\"Attempting connection to {} ({} connected, {} pending, {} max)\"",
",",
"address",
",",
"peers",
".",
"size",
"(",
")",
",",
"pendingPeers",
".",
"size",
"(",
")",
",",
"maxConnections",
")",
";",
"ListenableFuture",
"<",
"SocketAddress",
">",
"future",
"=",
"channels",
".",
"openConnection",
"(",
"address",
".",
"toSocketAddress",
"(",
")",
",",
"peer",
")",
";",
"if",
"(",
"future",
".",
"isDone",
"(",
")",
")",
"Uninterruptibles",
".",
"getUninterruptibly",
"(",
"future",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"Throwable",
"cause",
"=",
"Throwables",
".",
"getRootCause",
"(",
"e",
")",
";",
"log",
".",
"warn",
"(",
"\"Failed to connect to \"",
"+",
"address",
"+",
"\": \"",
"+",
"cause",
".",
"getMessage",
"(",
")",
")",
";",
"handlePeerDeath",
"(",
"peer",
",",
"cause",
")",
";",
"return",
"null",
";",
"}",
"peer",
".",
"setSocketTimeout",
"(",
"connectTimeoutMillis",
")",
";",
"// When the channel has connected and version negotiated successfully, handleNewPeer will end up being called on",
"// a worker thread.",
"if",
"(",
"incrementMaxConnections",
")",
"{",
"// We don't use setMaxConnections here as that would trigger a recursive attempt to establish a new",
"// outbound connection.",
"maxConnections",
"++",
";",
"}",
"return",
"peer",
";",
"}"
] | Creates a version message to send, constructs a Peer object and attempts to connect it. Returns the peer on
success or null on failure.
@param address Remote network address
@param incrementMaxConnections Whether to consider this connection an attempt to fill our quota, or something
explicitly requested.
@return Peer or null. | [
"Creates",
"a",
"version",
"message",
"to",
"send",
"constructs",
"a",
"Peer",
"object",
"and",
"attempts",
"to",
"connect",
"it",
".",
"Returns",
"the",
"peer",
"on",
"success",
"or",
"null",
"on",
"failure",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L1342-L1378 |
23,347 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.findPeersOfAtLeastVersion | public List<Peer> findPeersOfAtLeastVersion(long protocolVersion) {
lock.lock();
try {
ArrayList<Peer> results = new ArrayList<>(peers.size());
for (Peer peer : peers)
if (peer.getPeerVersionMessage().clientVersion >= protocolVersion)
results.add(peer);
return results;
} finally {
lock.unlock();
}
} | java | public List<Peer> findPeersOfAtLeastVersion(long protocolVersion) {
lock.lock();
try {
ArrayList<Peer> results = new ArrayList<>(peers.size());
for (Peer peer : peers)
if (peer.getPeerVersionMessage().clientVersion >= protocolVersion)
results.add(peer);
return results;
} finally {
lock.unlock();
}
} | [
"public",
"List",
"<",
"Peer",
">",
"findPeersOfAtLeastVersion",
"(",
"long",
"protocolVersion",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"ArrayList",
"<",
"Peer",
">",
"results",
"=",
"new",
"ArrayList",
"<>",
"(",
"peers",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"Peer",
"peer",
":",
"peers",
")",
"if",
"(",
"peer",
".",
"getPeerVersionMessage",
"(",
")",
".",
"clientVersion",
">=",
"protocolVersion",
")",
"results",
".",
"add",
"(",
"peer",
")",
";",
"return",
"results",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Returns an array list of peers that implement the given protocol version or better. | [
"Returns",
"an",
"array",
"list",
"of",
"peers",
"that",
"implement",
"the",
"given",
"protocol",
"version",
"or",
"better",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L1920-L1931 |
23,348 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PeerGroup.java | PeerGroup.findPeersWithServiceMask | public List<Peer> findPeersWithServiceMask(int mask) {
lock.lock();
try {
ArrayList<Peer> results = new ArrayList<>(peers.size());
for (Peer peer : peers)
if ((peer.getPeerVersionMessage().localServices & mask) == mask)
results.add(peer);
return results;
} finally {
lock.unlock();
}
} | java | public List<Peer> findPeersWithServiceMask(int mask) {
lock.lock();
try {
ArrayList<Peer> results = new ArrayList<>(peers.size());
for (Peer peer : peers)
if ((peer.getPeerVersionMessage().localServices & mask) == mask)
results.add(peer);
return results;
} finally {
lock.unlock();
}
} | [
"public",
"List",
"<",
"Peer",
">",
"findPeersWithServiceMask",
"(",
"int",
"mask",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"ArrayList",
"<",
"Peer",
">",
"results",
"=",
"new",
"ArrayList",
"<>",
"(",
"peers",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"Peer",
"peer",
":",
"peers",
")",
"if",
"(",
"(",
"peer",
".",
"getPeerVersionMessage",
"(",
")",
".",
"localServices",
"&",
"mask",
")",
"==",
"mask",
")",
"results",
".",
"add",
"(",
"peer",
")",
";",
"return",
"results",
";",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Returns an array list of peers that match the requested service bit mask. | [
"Returns",
"an",
"array",
"list",
"of",
"peers",
"that",
"match",
"the",
"requested",
"service",
"bit",
"mask",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PeerGroup.java#L1967-L1978 |
23,349 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Coin.java | Coin.valueOf | public static Coin valueOf(final int coins, final int cents) {
checkArgument(cents < 100);
checkArgument(cents >= 0);
checkArgument(coins >= 0);
final Coin coin = COIN.multiply(coins).add(CENT.multiply(cents));
return coin;
} | java | public static Coin valueOf(final int coins, final int cents) {
checkArgument(cents < 100);
checkArgument(cents >= 0);
checkArgument(coins >= 0);
final Coin coin = COIN.multiply(coins).add(CENT.multiply(cents));
return coin;
} | [
"public",
"static",
"Coin",
"valueOf",
"(",
"final",
"int",
"coins",
",",
"final",
"int",
"cents",
")",
"{",
"checkArgument",
"(",
"cents",
"<",
"100",
")",
";",
"checkArgument",
"(",
"cents",
">=",
"0",
")",
";",
"checkArgument",
"(",
"coins",
">=",
"0",
")",
";",
"final",
"Coin",
"coin",
"=",
"COIN",
".",
"multiply",
"(",
"coins",
")",
".",
"add",
"(",
"CENT",
".",
"multiply",
"(",
"cents",
")",
")",
";",
"return",
"coin",
";",
"}"
] | Convert an amount expressed in the way humans are used to into satoshis. | [
"Convert",
"an",
"amount",
"expressed",
"in",
"the",
"way",
"humans",
"are",
"used",
"to",
"into",
"satoshis",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Coin.java#L109-L115 |
23,350 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/ListenerRegistration.java | ListenerRegistration.removeFromList | public static <T> boolean removeFromList(T listener, List<? extends ListenerRegistration<T>> list) {
checkNotNull(listener);
ListenerRegistration<T> item = null;
for (ListenerRegistration<T> registration : list) {
if (registration.listener == listener) {
item = registration;
break;
}
}
return item != null && list.remove(item);
} | java | public static <T> boolean removeFromList(T listener, List<? extends ListenerRegistration<T>> list) {
checkNotNull(listener);
ListenerRegistration<T> item = null;
for (ListenerRegistration<T> registration : list) {
if (registration.listener == listener) {
item = registration;
break;
}
}
return item != null && list.remove(item);
} | [
"public",
"static",
"<",
"T",
">",
"boolean",
"removeFromList",
"(",
"T",
"listener",
",",
"List",
"<",
"?",
"extends",
"ListenerRegistration",
"<",
"T",
">",
">",
"list",
")",
"{",
"checkNotNull",
"(",
"listener",
")",
";",
"ListenerRegistration",
"<",
"T",
">",
"item",
"=",
"null",
";",
"for",
"(",
"ListenerRegistration",
"<",
"T",
">",
"registration",
":",
"list",
")",
"{",
"if",
"(",
"registration",
".",
"listener",
"==",
"listener",
")",
"{",
"item",
"=",
"registration",
";",
"break",
";",
"}",
"}",
"return",
"item",
"!=",
"null",
"&&",
"list",
".",
"remove",
"(",
"item",
")",
";",
"}"
] | Returns true if the listener was removed, else false. | [
"Returns",
"true",
"if",
"the",
"listener",
"was",
"removed",
"else",
"false",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/ListenerRegistration.java#L37-L48 |
23,351 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/FullPrunedBlockChain.java | FullPrunedBlockChain.disconnectTransactions | @Override
protected void disconnectTransactions(StoredBlock oldBlock) throws PrunedException, BlockStoreException {
checkState(lock.isHeldByCurrentThread());
blockStore.beginDatabaseBatchWrite();
try {
StoredUndoableBlock undoBlock = blockStore.getUndoBlock(oldBlock.getHeader().getHash());
if (undoBlock == null) throw new PrunedException(oldBlock.getHeader().getHash());
TransactionOutputChanges txOutChanges = undoBlock.getTxOutChanges();
for (UTXO out : txOutChanges.txOutsSpent)
blockStore.addUnspentTransactionOutput(out);
for (UTXO out : txOutChanges.txOutsCreated)
blockStore.removeUnspentTransactionOutput(out);
} catch (PrunedException e) {
blockStore.abortDatabaseBatchWrite();
throw e;
} catch (BlockStoreException e) {
blockStore.abortDatabaseBatchWrite();
throw e;
}
} | java | @Override
protected void disconnectTransactions(StoredBlock oldBlock) throws PrunedException, BlockStoreException {
checkState(lock.isHeldByCurrentThread());
blockStore.beginDatabaseBatchWrite();
try {
StoredUndoableBlock undoBlock = blockStore.getUndoBlock(oldBlock.getHeader().getHash());
if (undoBlock == null) throw new PrunedException(oldBlock.getHeader().getHash());
TransactionOutputChanges txOutChanges = undoBlock.getTxOutChanges();
for (UTXO out : txOutChanges.txOutsSpent)
blockStore.addUnspentTransactionOutput(out);
for (UTXO out : txOutChanges.txOutsCreated)
blockStore.removeUnspentTransactionOutput(out);
} catch (PrunedException e) {
blockStore.abortDatabaseBatchWrite();
throw e;
} catch (BlockStoreException e) {
blockStore.abortDatabaseBatchWrite();
throw e;
}
} | [
"@",
"Override",
"protected",
"void",
"disconnectTransactions",
"(",
"StoredBlock",
"oldBlock",
")",
"throws",
"PrunedException",
",",
"BlockStoreException",
"{",
"checkState",
"(",
"lock",
".",
"isHeldByCurrentThread",
"(",
")",
")",
";",
"blockStore",
".",
"beginDatabaseBatchWrite",
"(",
")",
";",
"try",
"{",
"StoredUndoableBlock",
"undoBlock",
"=",
"blockStore",
".",
"getUndoBlock",
"(",
"oldBlock",
".",
"getHeader",
"(",
")",
".",
"getHash",
"(",
")",
")",
";",
"if",
"(",
"undoBlock",
"==",
"null",
")",
"throw",
"new",
"PrunedException",
"(",
"oldBlock",
".",
"getHeader",
"(",
")",
".",
"getHash",
"(",
")",
")",
";",
"TransactionOutputChanges",
"txOutChanges",
"=",
"undoBlock",
".",
"getTxOutChanges",
"(",
")",
";",
"for",
"(",
"UTXO",
"out",
":",
"txOutChanges",
".",
"txOutsSpent",
")",
"blockStore",
".",
"addUnspentTransactionOutput",
"(",
"out",
")",
";",
"for",
"(",
"UTXO",
"out",
":",
"txOutChanges",
".",
"txOutsCreated",
")",
"blockStore",
".",
"removeUnspentTransactionOutput",
"(",
"out",
")",
";",
"}",
"catch",
"(",
"PrunedException",
"e",
")",
"{",
"blockStore",
".",
"abortDatabaseBatchWrite",
"(",
")",
";",
"throw",
"e",
";",
"}",
"catch",
"(",
"BlockStoreException",
"e",
")",
"{",
"blockStore",
".",
"abortDatabaseBatchWrite",
"(",
")",
";",
"throw",
"e",
";",
"}",
"}"
] | This is broken for blocks that do not pass BIP30, so all BIP30-failing blocks which are allowed to fail BIP30
must be checkpointed. | [
"This",
"is",
"broken",
"for",
"blocks",
"that",
"do",
"not",
"pass",
"BIP30",
"so",
"all",
"BIP30",
"-",
"failing",
"blocks",
"which",
"are",
"allowed",
"to",
"fail",
"BIP30",
"must",
"be",
"checkpointed",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/FullPrunedBlockChain.java#L496-L515 |
23,352 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/payments/PaymentSession.java | PaymentSession.getOutputs | public List<PaymentProtocol.Output> getOutputs() {
List<PaymentProtocol.Output> outputs = new ArrayList<>(paymentDetails.getOutputsCount());
for (Protos.Output output : paymentDetails.getOutputsList()) {
Coin amount = output.hasAmount() ? Coin.valueOf(output.getAmount()) : null;
outputs.add(new PaymentProtocol.Output(amount, output.getScript().toByteArray()));
}
return outputs;
} | java | public List<PaymentProtocol.Output> getOutputs() {
List<PaymentProtocol.Output> outputs = new ArrayList<>(paymentDetails.getOutputsCount());
for (Protos.Output output : paymentDetails.getOutputsList()) {
Coin amount = output.hasAmount() ? Coin.valueOf(output.getAmount()) : null;
outputs.add(new PaymentProtocol.Output(amount, output.getScript().toByteArray()));
}
return outputs;
} | [
"public",
"List",
"<",
"PaymentProtocol",
".",
"Output",
">",
"getOutputs",
"(",
")",
"{",
"List",
"<",
"PaymentProtocol",
".",
"Output",
">",
"outputs",
"=",
"new",
"ArrayList",
"<>",
"(",
"paymentDetails",
".",
"getOutputsCount",
"(",
")",
")",
";",
"for",
"(",
"Protos",
".",
"Output",
"output",
":",
"paymentDetails",
".",
"getOutputsList",
"(",
")",
")",
"{",
"Coin",
"amount",
"=",
"output",
".",
"hasAmount",
"(",
")",
"?",
"Coin",
".",
"valueOf",
"(",
"output",
".",
"getAmount",
"(",
")",
")",
":",
"null",
";",
"outputs",
".",
"add",
"(",
"new",
"PaymentProtocol",
".",
"Output",
"(",
"amount",
",",
"output",
".",
"getScript",
"(",
")",
".",
"toByteArray",
"(",
")",
")",
")",
";",
"}",
"return",
"outputs",
";",
"}"
] | Returns the outputs of the payment request. | [
"Returns",
"the",
"outputs",
"of",
"the",
"payment",
"request",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/payments/PaymentSession.java#L226-L233 |
23,353 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TxConfidenceTable.java | TxConfidenceTable.cleanTable | private void cleanTable() {
lock.lock();
try {
Reference<? extends TransactionConfidence> ref;
while ((ref = referenceQueue.poll()) != null) {
// Find which transaction got deleted by the GC.
WeakConfidenceReference txRef = (WeakConfidenceReference) ref;
// And remove the associated map entry so the other bits of memory can also be reclaimed.
table.remove(txRef.hash);
}
} finally {
lock.unlock();
}
} | java | private void cleanTable() {
lock.lock();
try {
Reference<? extends TransactionConfidence> ref;
while ((ref = referenceQueue.poll()) != null) {
// Find which transaction got deleted by the GC.
WeakConfidenceReference txRef = (WeakConfidenceReference) ref;
// And remove the associated map entry so the other bits of memory can also be reclaimed.
table.remove(txRef.hash);
}
} finally {
lock.unlock();
}
} | [
"private",
"void",
"cleanTable",
"(",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"Reference",
"<",
"?",
"extends",
"TransactionConfidence",
">",
"ref",
";",
"while",
"(",
"(",
"ref",
"=",
"referenceQueue",
".",
"poll",
"(",
")",
")",
"!=",
"null",
")",
"{",
"// Find which transaction got deleted by the GC.",
"WeakConfidenceReference",
"txRef",
"=",
"(",
"WeakConfidenceReference",
")",
"ref",
";",
"// And remove the associated map entry so the other bits of memory can also be reclaimed.",
"table",
".",
"remove",
"(",
"txRef",
".",
"hash",
")",
";",
"}",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | If any transactions have expired due to being only weakly reachable through us, go ahead and delete their
table entries - it means we downloaded the transaction and sent it to various event listeners, none of
which bothered to keep a reference. Typically, this is because the transaction does not involve any keys that
are relevant to any of our wallets. | [
"If",
"any",
"transactions",
"have",
"expired",
"due",
"to",
"being",
"only",
"weakly",
"reachable",
"through",
"us",
"go",
"ahead",
"and",
"delete",
"their",
"table",
"entries",
"-",
"it",
"means",
"we",
"downloaded",
"the",
"transaction",
"and",
"sent",
"it",
"to",
"various",
"event",
"listeners",
"none",
"of",
"which",
"bothered",
"to",
"keep",
"a",
"reference",
".",
"Typically",
"this",
"is",
"because",
"the",
"transaction",
"does",
"not",
"involve",
"any",
"keys",
"that",
"are",
"relevant",
"to",
"any",
"of",
"our",
"wallets",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TxConfidenceTable.java#L98-L111 |
23,354 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/TxConfidenceTable.java | TxConfidenceTable.numBroadcastPeers | public int numBroadcastPeers(Sha256Hash txHash) {
lock.lock();
try {
cleanTable();
WeakConfidenceReference entry = table.get(txHash);
if (entry == null) {
return 0; // No such TX known.
} else {
TransactionConfidence confidence = entry.get();
if (confidence == null) {
// Such a TX hash was seen, but nothing seemed to care so we ended up throwing away the data.
table.remove(txHash);
return 0;
} else {
return confidence.numBroadcastPeers();
}
}
} finally {
lock.unlock();
}
} | java | public int numBroadcastPeers(Sha256Hash txHash) {
lock.lock();
try {
cleanTable();
WeakConfidenceReference entry = table.get(txHash);
if (entry == null) {
return 0; // No such TX known.
} else {
TransactionConfidence confidence = entry.get();
if (confidence == null) {
// Such a TX hash was seen, but nothing seemed to care so we ended up throwing away the data.
table.remove(txHash);
return 0;
} else {
return confidence.numBroadcastPeers();
}
}
} finally {
lock.unlock();
}
} | [
"public",
"int",
"numBroadcastPeers",
"(",
"Sha256Hash",
"txHash",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"cleanTable",
"(",
")",
";",
"WeakConfidenceReference",
"entry",
"=",
"table",
".",
"get",
"(",
"txHash",
")",
";",
"if",
"(",
"entry",
"==",
"null",
")",
"{",
"return",
"0",
";",
"// No such TX known.",
"}",
"else",
"{",
"TransactionConfidence",
"confidence",
"=",
"entry",
".",
"get",
"(",
")",
";",
"if",
"(",
"confidence",
"==",
"null",
")",
"{",
"// Such a TX hash was seen, but nothing seemed to care so we ended up throwing away the data.",
"table",
".",
"remove",
"(",
"txHash",
")",
";",
"return",
"0",
";",
"}",
"else",
"{",
"return",
"confidence",
".",
"numBroadcastPeers",
"(",
")",
";",
"}",
"}",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Returns the number of peers that have seen the given hash recently. | [
"Returns",
"the",
"number",
"of",
"peers",
"that",
"have",
"seen",
"the",
"given",
"hash",
"recently",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/TxConfidenceTable.java#L116-L136 |
23,355 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Sha256Hash.java | Sha256Hash.hash | public static byte[] hash(byte[] input, int offset, int length) {
MessageDigest digest = newDigest();
digest.update(input, offset, length);
return digest.digest();
} | java | public static byte[] hash(byte[] input, int offset, int length) {
MessageDigest digest = newDigest();
digest.update(input, offset, length);
return digest.digest();
} | [
"public",
"static",
"byte",
"[",
"]",
"hash",
"(",
"byte",
"[",
"]",
"input",
",",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"MessageDigest",
"digest",
"=",
"newDigest",
"(",
")",
";",
"digest",
".",
"update",
"(",
"input",
",",
"offset",
",",
"length",
")",
";",
"return",
"digest",
".",
"digest",
"(",
")",
";",
"}"
] | Calculates the SHA-256 hash of the given byte range.
@param input the array containing the bytes to hash
@param offset the offset within the array of the bytes to hash
@param length the number of bytes to hash
@return the hash (in big-endian order) | [
"Calculates",
"the",
"SHA",
"-",
"256",
"hash",
"of",
"the",
"given",
"byte",
"range",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Sha256Hash.java#L166-L170 |
23,356 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/Sha256Hash.java | Sha256Hash.hashTwice | public static byte[] hashTwice(byte[] input, int offset, int length) {
MessageDigest digest = newDigest();
digest.update(input, offset, length);
return digest.digest(digest.digest());
} | java | public static byte[] hashTwice(byte[] input, int offset, int length) {
MessageDigest digest = newDigest();
digest.update(input, offset, length);
return digest.digest(digest.digest());
} | [
"public",
"static",
"byte",
"[",
"]",
"hashTwice",
"(",
"byte",
"[",
"]",
"input",
",",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"MessageDigest",
"digest",
"=",
"newDigest",
"(",
")",
";",
"digest",
".",
"update",
"(",
"input",
",",
"offset",
",",
"length",
")",
";",
"return",
"digest",
".",
"digest",
"(",
"digest",
".",
"digest",
"(",
")",
")",
";",
"}"
] | Calculates the SHA-256 hash of the given byte range,
and then hashes the resulting hash again.
@param input the array containing the bytes to hash
@param offset the offset within the array of the bytes to hash
@param length the number of bytes to hash
@return the double-hash (in big-endian order) | [
"Calculates",
"the",
"SHA",
"-",
"256",
"hash",
"of",
"the",
"given",
"byte",
"range",
"and",
"then",
"hashes",
"the",
"resulting",
"hash",
"again",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/Sha256Hash.java#L203-L207 |
23,357 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/InventoryMessage.java | InventoryMessage.with | public static InventoryMessage with(Transaction... txns) {
checkArgument(txns.length > 0);
InventoryMessage result = new InventoryMessage(txns[0].getParams());
for (Transaction tx : txns)
result.addTransaction(tx);
return result;
} | java | public static InventoryMessage with(Transaction... txns) {
checkArgument(txns.length > 0);
InventoryMessage result = new InventoryMessage(txns[0].getParams());
for (Transaction tx : txns)
result.addTransaction(tx);
return result;
} | [
"public",
"static",
"InventoryMessage",
"with",
"(",
"Transaction",
"...",
"txns",
")",
"{",
"checkArgument",
"(",
"txns",
".",
"length",
">",
"0",
")",
";",
"InventoryMessage",
"result",
"=",
"new",
"InventoryMessage",
"(",
"txns",
"[",
"0",
"]",
".",
"getParams",
"(",
")",
")",
";",
"for",
"(",
"Transaction",
"tx",
":",
"txns",
")",
"result",
".",
"addTransaction",
"(",
"tx",
")",
";",
"return",
"result",
";",
"}"
] | Creates a new inv message for the given transactions. | [
"Creates",
"a",
"new",
"inv",
"message",
"for",
"the",
"given",
"transactions",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/InventoryMessage.java#L65-L71 |
23,358 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/net/discovery/SeedPeers.java | SeedPeers.getPeers | @Override
public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException {
if (services != 0)
throw new PeerDiscoveryException("Pre-determined peers cannot be filtered by services: " + services);
try {
return allPeers();
} catch (UnknownHostException e) {
throw new PeerDiscoveryException(e);
}
} | java | @Override
public InetSocketAddress[] getPeers(long services, long timeoutValue, TimeUnit timeoutUnit) throws PeerDiscoveryException {
if (services != 0)
throw new PeerDiscoveryException("Pre-determined peers cannot be filtered by services: " + services);
try {
return allPeers();
} catch (UnknownHostException e) {
throw new PeerDiscoveryException(e);
}
} | [
"@",
"Override",
"public",
"InetSocketAddress",
"[",
"]",
"getPeers",
"(",
"long",
"services",
",",
"long",
"timeoutValue",
",",
"TimeUnit",
"timeoutUnit",
")",
"throws",
"PeerDiscoveryException",
"{",
"if",
"(",
"services",
"!=",
"0",
")",
"throw",
"new",
"PeerDiscoveryException",
"(",
"\"Pre-determined peers cannot be filtered by services: \"",
"+",
"services",
")",
";",
"try",
"{",
"return",
"allPeers",
"(",
")",
";",
"}",
"catch",
"(",
"UnknownHostException",
"e",
")",
"{",
"throw",
"new",
"PeerDiscoveryException",
"(",
"e",
")",
";",
"}",
"}"
] | Returns an array containing all the Bitcoin nodes within the list. | [
"Returns",
"an",
"array",
"containing",
"all",
"the",
"Bitcoin",
"nodes",
"within",
"the",
"list",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/net/discovery/SeedPeers.java#L87-L96 |
23,359 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/StoredBlock.java | StoredBlock.build | public StoredBlock build(Block block) throws VerificationException {
// Stored blocks track total work done in this chain, because the canonical chain is the one that represents
// the largest amount of work done not the tallest.
BigInteger chainWork = this.chainWork.add(block.getWork());
int height = this.height + 1;
return new StoredBlock(block, chainWork, height);
} | java | public StoredBlock build(Block block) throws VerificationException {
// Stored blocks track total work done in this chain, because the canonical chain is the one that represents
// the largest amount of work done not the tallest.
BigInteger chainWork = this.chainWork.add(block.getWork());
int height = this.height + 1;
return new StoredBlock(block, chainWork, height);
} | [
"public",
"StoredBlock",
"build",
"(",
"Block",
"block",
")",
"throws",
"VerificationException",
"{",
"// Stored blocks track total work done in this chain, because the canonical chain is the one that represents",
"// the largest amount of work done not the tallest.",
"BigInteger",
"chainWork",
"=",
"this",
".",
"chainWork",
".",
"add",
"(",
"block",
".",
"getWork",
"(",
")",
")",
";",
"int",
"height",
"=",
"this",
".",
"height",
"+",
"1",
";",
"return",
"new",
"StoredBlock",
"(",
"block",
",",
"chainWork",
",",
"height",
")",
";",
"}"
] | Creates a new StoredBlock, calculating the additional fields by adding to the values in this block. | [
"Creates",
"a",
"new",
"StoredBlock",
"calculating",
"the",
"additional",
"fields",
"by",
"adding",
"to",
"the",
"values",
"in",
"this",
"block",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/StoredBlock.java#L100-L106 |
23,360 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/KeyCrypterScrypt.java | KeyCrypterScrypt.deriveKey | @Override
public KeyParameter deriveKey(CharSequence password) throws KeyCrypterException {
byte[] passwordBytes = null;
try {
passwordBytes = convertToByteArray(password);
byte[] salt = new byte[0];
if ( scryptParameters.getSalt() != null) {
salt = scryptParameters.getSalt().toByteArray();
} else {
// Warn the user that they are not using a salt.
// (Some early MultiBit wallets had a blank salt).
log.warn("You are using a ScryptParameters with no salt. Your encryption may be vulnerable to a dictionary attack.");
}
final Stopwatch watch = Stopwatch.createStarted();
byte[] keyBytes = SCrypt.scrypt(passwordBytes, salt, (int) scryptParameters.getN(), scryptParameters.getR(), scryptParameters.getP(), KEY_LENGTH);
watch.stop();
log.info("Deriving key took {} for {} scrypt iterations.", watch, scryptParameters.getN());
return new KeyParameter(keyBytes);
} catch (Exception e) {
throw new KeyCrypterException("Could not generate key from password and salt.", e);
} finally {
// Zero the password bytes.
if (passwordBytes != null) {
java.util.Arrays.fill(passwordBytes, (byte) 0);
}
}
} | java | @Override
public KeyParameter deriveKey(CharSequence password) throws KeyCrypterException {
byte[] passwordBytes = null;
try {
passwordBytes = convertToByteArray(password);
byte[] salt = new byte[0];
if ( scryptParameters.getSalt() != null) {
salt = scryptParameters.getSalt().toByteArray();
} else {
// Warn the user that they are not using a salt.
// (Some early MultiBit wallets had a blank salt).
log.warn("You are using a ScryptParameters with no salt. Your encryption may be vulnerable to a dictionary attack.");
}
final Stopwatch watch = Stopwatch.createStarted();
byte[] keyBytes = SCrypt.scrypt(passwordBytes, salt, (int) scryptParameters.getN(), scryptParameters.getR(), scryptParameters.getP(), KEY_LENGTH);
watch.stop();
log.info("Deriving key took {} for {} scrypt iterations.", watch, scryptParameters.getN());
return new KeyParameter(keyBytes);
} catch (Exception e) {
throw new KeyCrypterException("Could not generate key from password and salt.", e);
} finally {
// Zero the password bytes.
if (passwordBytes != null) {
java.util.Arrays.fill(passwordBytes, (byte) 0);
}
}
} | [
"@",
"Override",
"public",
"KeyParameter",
"deriveKey",
"(",
"CharSequence",
"password",
")",
"throws",
"KeyCrypterException",
"{",
"byte",
"[",
"]",
"passwordBytes",
"=",
"null",
";",
"try",
"{",
"passwordBytes",
"=",
"convertToByteArray",
"(",
"password",
")",
";",
"byte",
"[",
"]",
"salt",
"=",
"new",
"byte",
"[",
"0",
"]",
";",
"if",
"(",
"scryptParameters",
".",
"getSalt",
"(",
")",
"!=",
"null",
")",
"{",
"salt",
"=",
"scryptParameters",
".",
"getSalt",
"(",
")",
".",
"toByteArray",
"(",
")",
";",
"}",
"else",
"{",
"// Warn the user that they are not using a salt.",
"// (Some early MultiBit wallets had a blank salt).",
"log",
".",
"warn",
"(",
"\"You are using a ScryptParameters with no salt. Your encryption may be vulnerable to a dictionary attack.\"",
")",
";",
"}",
"final",
"Stopwatch",
"watch",
"=",
"Stopwatch",
".",
"createStarted",
"(",
")",
";",
"byte",
"[",
"]",
"keyBytes",
"=",
"SCrypt",
".",
"scrypt",
"(",
"passwordBytes",
",",
"salt",
",",
"(",
"int",
")",
"scryptParameters",
".",
"getN",
"(",
")",
",",
"scryptParameters",
".",
"getR",
"(",
")",
",",
"scryptParameters",
".",
"getP",
"(",
")",
",",
"KEY_LENGTH",
")",
";",
"watch",
".",
"stop",
"(",
")",
";",
"log",
".",
"info",
"(",
"\"Deriving key took {} for {} scrypt iterations.\"",
",",
"watch",
",",
"scryptParameters",
".",
"getN",
"(",
")",
")",
";",
"return",
"new",
"KeyParameter",
"(",
"keyBytes",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"KeyCrypterException",
"(",
"\"Could not generate key from password and salt.\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"// Zero the password bytes.",
"if",
"(",
"passwordBytes",
"!=",
"null",
")",
"{",
"java",
".",
"util",
".",
"Arrays",
".",
"fill",
"(",
"passwordBytes",
",",
"(",
"byte",
")",
"0",
")",
";",
"}",
"}",
"}"
] | Generate AES key.
This is a very slow operation compared to encrypt/ decrypt so it is normally worth caching the result.
@param password The password to use in key generation
@return The KeyParameter containing the created AES key
@throws KeyCrypterException | [
"Generate",
"AES",
"key",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/KeyCrypterScrypt.java#L145-L172 |
23,361 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/KeyCrypterScrypt.java | KeyCrypterScrypt.encrypt | @Override
public EncryptedData encrypt(byte[] plainBytes, KeyParameter aesKey) throws KeyCrypterException {
checkNotNull(plainBytes);
checkNotNull(aesKey);
try {
// Generate iv - each encryption call has a different iv.
byte[] iv = new byte[BLOCK_LENGTH];
secureRandom.nextBytes(iv);
ParametersWithIV keyWithIv = new ParametersWithIV(aesKey, iv);
// Encrypt using AES.
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
cipher.init(true, keyWithIv);
byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];
final int length1 = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
final int length2 = cipher.doFinal(encryptedBytes, length1);
return new EncryptedData(iv, Arrays.copyOf(encryptedBytes, length1 + length2));
} catch (Exception e) {
throw new KeyCrypterException("Could not encrypt bytes.", e);
}
} | java | @Override
public EncryptedData encrypt(byte[] plainBytes, KeyParameter aesKey) throws KeyCrypterException {
checkNotNull(plainBytes);
checkNotNull(aesKey);
try {
// Generate iv - each encryption call has a different iv.
byte[] iv = new byte[BLOCK_LENGTH];
secureRandom.nextBytes(iv);
ParametersWithIV keyWithIv = new ParametersWithIV(aesKey, iv);
// Encrypt using AES.
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
cipher.init(true, keyWithIv);
byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];
final int length1 = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
final int length2 = cipher.doFinal(encryptedBytes, length1);
return new EncryptedData(iv, Arrays.copyOf(encryptedBytes, length1 + length2));
} catch (Exception e) {
throw new KeyCrypterException("Could not encrypt bytes.", e);
}
} | [
"@",
"Override",
"public",
"EncryptedData",
"encrypt",
"(",
"byte",
"[",
"]",
"plainBytes",
",",
"KeyParameter",
"aesKey",
")",
"throws",
"KeyCrypterException",
"{",
"checkNotNull",
"(",
"plainBytes",
")",
";",
"checkNotNull",
"(",
"aesKey",
")",
";",
"try",
"{",
"// Generate iv - each encryption call has a different iv.",
"byte",
"[",
"]",
"iv",
"=",
"new",
"byte",
"[",
"BLOCK_LENGTH",
"]",
";",
"secureRandom",
".",
"nextBytes",
"(",
"iv",
")",
";",
"ParametersWithIV",
"keyWithIv",
"=",
"new",
"ParametersWithIV",
"(",
"aesKey",
",",
"iv",
")",
";",
"// Encrypt using AES.",
"BufferedBlockCipher",
"cipher",
"=",
"new",
"PaddedBufferedBlockCipher",
"(",
"new",
"CBCBlockCipher",
"(",
"new",
"AESEngine",
"(",
")",
")",
")",
";",
"cipher",
".",
"init",
"(",
"true",
",",
"keyWithIv",
")",
";",
"byte",
"[",
"]",
"encryptedBytes",
"=",
"new",
"byte",
"[",
"cipher",
".",
"getOutputSize",
"(",
"plainBytes",
".",
"length",
")",
"]",
";",
"final",
"int",
"length1",
"=",
"cipher",
".",
"processBytes",
"(",
"plainBytes",
",",
"0",
",",
"plainBytes",
".",
"length",
",",
"encryptedBytes",
",",
"0",
")",
";",
"final",
"int",
"length2",
"=",
"cipher",
".",
"doFinal",
"(",
"encryptedBytes",
",",
"length1",
")",
";",
"return",
"new",
"EncryptedData",
"(",
"iv",
",",
"Arrays",
".",
"copyOf",
"(",
"encryptedBytes",
",",
"length1",
"+",
"length2",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"KeyCrypterException",
"(",
"\"Could not encrypt bytes.\"",
",",
"e",
")",
";",
"}",
"}"
] | Password based encryption using AES - CBC 256 bits. | [
"Password",
"based",
"encryption",
"using",
"AES",
"-",
"CBC",
"256",
"bits",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/KeyCrypterScrypt.java#L177-L200 |
23,362 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/crypto/KeyCrypterScrypt.java | KeyCrypterScrypt.decrypt | @Override
public byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws KeyCrypterException {
checkNotNull(dataToDecrypt);
checkNotNull(aesKey);
try {
ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.getKey()), dataToDecrypt.initialisationVector);
// Decrypt the message.
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
cipher.init(false, keyWithIv);
byte[] cipherBytes = dataToDecrypt.encryptedBytes;
byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];
final int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);
final int length2 = cipher.doFinal(decryptedBytes, length1);
return Arrays.copyOf(decryptedBytes, length1 + length2);
} catch (InvalidCipherTextException e) {
throw new KeyCrypterException.InvalidCipherText("Could not decrypt bytes", e);
} catch (RuntimeException e) {
throw new KeyCrypterException("Could not decrypt bytes", e);
}
} | java | @Override
public byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws KeyCrypterException {
checkNotNull(dataToDecrypt);
checkNotNull(aesKey);
try {
ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.getKey()), dataToDecrypt.initialisationVector);
// Decrypt the message.
BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
cipher.init(false, keyWithIv);
byte[] cipherBytes = dataToDecrypt.encryptedBytes;
byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];
final int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);
final int length2 = cipher.doFinal(decryptedBytes, length1);
return Arrays.copyOf(decryptedBytes, length1 + length2);
} catch (InvalidCipherTextException e) {
throw new KeyCrypterException.InvalidCipherText("Could not decrypt bytes", e);
} catch (RuntimeException e) {
throw new KeyCrypterException("Could not decrypt bytes", e);
}
} | [
"@",
"Override",
"public",
"byte",
"[",
"]",
"decrypt",
"(",
"EncryptedData",
"dataToDecrypt",
",",
"KeyParameter",
"aesKey",
")",
"throws",
"KeyCrypterException",
"{",
"checkNotNull",
"(",
"dataToDecrypt",
")",
";",
"checkNotNull",
"(",
"aesKey",
")",
";",
"try",
"{",
"ParametersWithIV",
"keyWithIv",
"=",
"new",
"ParametersWithIV",
"(",
"new",
"KeyParameter",
"(",
"aesKey",
".",
"getKey",
"(",
")",
")",
",",
"dataToDecrypt",
".",
"initialisationVector",
")",
";",
"// Decrypt the message.",
"BufferedBlockCipher",
"cipher",
"=",
"new",
"PaddedBufferedBlockCipher",
"(",
"new",
"CBCBlockCipher",
"(",
"new",
"AESEngine",
"(",
")",
")",
")",
";",
"cipher",
".",
"init",
"(",
"false",
",",
"keyWithIv",
")",
";",
"byte",
"[",
"]",
"cipherBytes",
"=",
"dataToDecrypt",
".",
"encryptedBytes",
";",
"byte",
"[",
"]",
"decryptedBytes",
"=",
"new",
"byte",
"[",
"cipher",
".",
"getOutputSize",
"(",
"cipherBytes",
".",
"length",
")",
"]",
";",
"final",
"int",
"length1",
"=",
"cipher",
".",
"processBytes",
"(",
"cipherBytes",
",",
"0",
",",
"cipherBytes",
".",
"length",
",",
"decryptedBytes",
",",
"0",
")",
";",
"final",
"int",
"length2",
"=",
"cipher",
".",
"doFinal",
"(",
"decryptedBytes",
",",
"length1",
")",
";",
"return",
"Arrays",
".",
"copyOf",
"(",
"decryptedBytes",
",",
"length1",
"+",
"length2",
")",
";",
"}",
"catch",
"(",
"InvalidCipherTextException",
"e",
")",
"{",
"throw",
"new",
"KeyCrypterException",
".",
"InvalidCipherText",
"(",
"\"Could not decrypt bytes\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"RuntimeException",
"e",
")",
"{",
"throw",
"new",
"KeyCrypterException",
"(",
"\"Could not decrypt bytes\"",
",",
"e",
")",
";",
"}",
"}"
] | Decrypt bytes previously encrypted with this class.
@param dataToDecrypt The data to decrypt
@param aesKey The AES key to use for decryption
@return The decrypted bytes
@throws KeyCrypterException if bytes could not be decrypted | [
"Decrypt",
"bytes",
"previously",
"encrypted",
"with",
"this",
"class",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/KeyCrypterScrypt.java#L210-L233 |
23,363 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/utils/BriefLogFormatter.java | BriefLogFormatter.init | public static void init() {
logger = Logger.getLogger("");
final Handler[] handlers = logger.getHandlers();
// In regular Java there is always a handler. Avian doesn't install one however.
if (handlers.length > 0)
handlers[0].setFormatter(new BriefLogFormatter());
} | java | public static void init() {
logger = Logger.getLogger("");
final Handler[] handlers = logger.getHandlers();
// In regular Java there is always a handler. Avian doesn't install one however.
if (handlers.length > 0)
handlers[0].setFormatter(new BriefLogFormatter());
} | [
"public",
"static",
"void",
"init",
"(",
")",
"{",
"logger",
"=",
"Logger",
".",
"getLogger",
"(",
"\"\"",
")",
";",
"final",
"Handler",
"[",
"]",
"handlers",
"=",
"logger",
".",
"getHandlers",
"(",
")",
";",
"// In regular Java there is always a handler. Avian doesn't install one however.",
"if",
"(",
"handlers",
".",
"length",
">",
"0",
")",
"handlers",
"[",
"0",
"]",
".",
"setFormatter",
"(",
"new",
"BriefLogFormatter",
"(",
")",
")",
";",
"}"
] | Configures JDK logging to use this class for everything. | [
"Configures",
"JDK",
"logging",
"to",
"use",
"this",
"class",
"for",
"everything",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/utils/BriefLogFormatter.java#L38-L44 |
23,364 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/NetworkParameters.java | NetworkParameters.fromID | @Nullable
public static NetworkParameters fromID(String id) {
if (id.equals(ID_MAINNET)) {
return MainNetParams.get();
} else if (id.equals(ID_TESTNET)) {
return TestNet3Params.get();
} else if (id.equals(ID_UNITTESTNET)) {
return UnitTestParams.get();
} else if (id.equals(ID_REGTEST)) {
return RegTestParams.get();
} else {
return null;
}
} | java | @Nullable
public static NetworkParameters fromID(String id) {
if (id.equals(ID_MAINNET)) {
return MainNetParams.get();
} else if (id.equals(ID_TESTNET)) {
return TestNet3Params.get();
} else if (id.equals(ID_UNITTESTNET)) {
return UnitTestParams.get();
} else if (id.equals(ID_REGTEST)) {
return RegTestParams.get();
} else {
return null;
}
} | [
"@",
"Nullable",
"public",
"static",
"NetworkParameters",
"fromID",
"(",
"String",
"id",
")",
"{",
"if",
"(",
"id",
".",
"equals",
"(",
"ID_MAINNET",
")",
")",
"{",
"return",
"MainNetParams",
".",
"get",
"(",
")",
";",
"}",
"else",
"if",
"(",
"id",
".",
"equals",
"(",
"ID_TESTNET",
")",
")",
"{",
"return",
"TestNet3Params",
".",
"get",
"(",
")",
";",
"}",
"else",
"if",
"(",
"id",
".",
"equals",
"(",
"ID_UNITTESTNET",
")",
")",
"{",
"return",
"UnitTestParams",
".",
"get",
"(",
")",
";",
"}",
"else",
"if",
"(",
"id",
".",
"equals",
"(",
"ID_REGTEST",
")",
")",
"{",
"return",
"RegTestParams",
".",
"get",
"(",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] | Returns the network parameters for the given string ID or NULL if not recognized. | [
"Returns",
"the",
"network",
"parameters",
"for",
"the",
"given",
"string",
"ID",
"or",
"NULL",
"if",
"not",
"recognized",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/NetworkParameters.java#L182-L195 |
23,365 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/NetworkParameters.java | NetworkParameters.fromPmtProtocolID | @Nullable
public static NetworkParameters fromPmtProtocolID(String pmtProtocolId) {
if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_MAINNET)) {
return MainNetParams.get();
} else if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_TESTNET)) {
return TestNet3Params.get();
} else if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_UNIT_TESTS)) {
return UnitTestParams.get();
} else if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_REGTEST)) {
return RegTestParams.get();
} else {
return null;
}
} | java | @Nullable
public static NetworkParameters fromPmtProtocolID(String pmtProtocolId) {
if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_MAINNET)) {
return MainNetParams.get();
} else if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_TESTNET)) {
return TestNet3Params.get();
} else if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_UNIT_TESTS)) {
return UnitTestParams.get();
} else if (pmtProtocolId.equals(PAYMENT_PROTOCOL_ID_REGTEST)) {
return RegTestParams.get();
} else {
return null;
}
} | [
"@",
"Nullable",
"public",
"static",
"NetworkParameters",
"fromPmtProtocolID",
"(",
"String",
"pmtProtocolId",
")",
"{",
"if",
"(",
"pmtProtocolId",
".",
"equals",
"(",
"PAYMENT_PROTOCOL_ID_MAINNET",
")",
")",
"{",
"return",
"MainNetParams",
".",
"get",
"(",
")",
";",
"}",
"else",
"if",
"(",
"pmtProtocolId",
".",
"equals",
"(",
"PAYMENT_PROTOCOL_ID_TESTNET",
")",
")",
"{",
"return",
"TestNet3Params",
".",
"get",
"(",
")",
";",
"}",
"else",
"if",
"(",
"pmtProtocolId",
".",
"equals",
"(",
"PAYMENT_PROTOCOL_ID_UNIT_TESTS",
")",
")",
"{",
"return",
"UnitTestParams",
".",
"get",
"(",
")",
";",
"}",
"else",
"if",
"(",
"pmtProtocolId",
".",
"equals",
"(",
"PAYMENT_PROTOCOL_ID_REGTEST",
")",
")",
"{",
"return",
"RegTestParams",
".",
"get",
"(",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] | Returns the network parameters for the given string paymentProtocolID or NULL if not recognized. | [
"Returns",
"the",
"network",
"parameters",
"for",
"the",
"given",
"string",
"paymentProtocolID",
"or",
"NULL",
"if",
"not",
"recognized",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/NetworkParameters.java#L198-L211 |
23,366 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/NetworkParameters.java | NetworkParameters.passesCheckpoint | public boolean passesCheckpoint(int height, Sha256Hash hash) {
Sha256Hash checkpointHash = checkpoints.get(height);
return checkpointHash == null || checkpointHash.equals(hash);
} | java | public boolean passesCheckpoint(int height, Sha256Hash hash) {
Sha256Hash checkpointHash = checkpoints.get(height);
return checkpointHash == null || checkpointHash.equals(hash);
} | [
"public",
"boolean",
"passesCheckpoint",
"(",
"int",
"height",
",",
"Sha256Hash",
"hash",
")",
"{",
"Sha256Hash",
"checkpointHash",
"=",
"checkpoints",
".",
"get",
"(",
"height",
")",
";",
"return",
"checkpointHash",
"==",
"null",
"||",
"checkpointHash",
".",
"equals",
"(",
"hash",
")",
";",
"}"
] | Returns true if the block height is either not a checkpoint, or is a checkpoint and the hash matches. | [
"Returns",
"true",
"if",
"the",
"block",
"height",
"is",
"either",
"not",
"a",
"checkpoint",
"or",
"is",
"a",
"checkpoint",
"and",
"the",
"hash",
"matches",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/NetworkParameters.java#L227-L230 |
23,367 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/NetworkParameters.java | NetworkParameters.getDefaultSerializer | public final MessageSerializer getDefaultSerializer() {
// Construct a default serializer if we don't have one
if (null == this.defaultSerializer) {
// Don't grab a lock unless we absolutely need it
synchronized(this) {
// Now we have a lock, double check there's still no serializer
// and create one if so.
if (null == this.defaultSerializer) {
// As the serializers are intended to be immutable, creating
// two due to a race condition should not be a problem, however
// to be safe we ensure only one exists for each network.
this.defaultSerializer = getSerializer(false);
}
}
}
return defaultSerializer;
} | java | public final MessageSerializer getDefaultSerializer() {
// Construct a default serializer if we don't have one
if (null == this.defaultSerializer) {
// Don't grab a lock unless we absolutely need it
synchronized(this) {
// Now we have a lock, double check there's still no serializer
// and create one if so.
if (null == this.defaultSerializer) {
// As the serializers are intended to be immutable, creating
// two due to a race condition should not be a problem, however
// to be safe we ensure only one exists for each network.
this.defaultSerializer = getSerializer(false);
}
}
}
return defaultSerializer;
} | [
"public",
"final",
"MessageSerializer",
"getDefaultSerializer",
"(",
")",
"{",
"// Construct a default serializer if we don't have one",
"if",
"(",
"null",
"==",
"this",
".",
"defaultSerializer",
")",
"{",
"// Don't grab a lock unless we absolutely need it",
"synchronized",
"(",
"this",
")",
"{",
"// Now we have a lock, double check there's still no serializer",
"// and create one if so.",
"if",
"(",
"null",
"==",
"this",
".",
"defaultSerializer",
")",
"{",
"// As the serializers are intended to be immutable, creating",
"// two due to a race condition should not be a problem, however",
"// to be safe we ensure only one exists for each network.",
"this",
".",
"defaultSerializer",
"=",
"getSerializer",
"(",
"false",
")",
";",
"}",
"}",
"}",
"return",
"defaultSerializer",
";",
"}"
] | Return the default serializer for this network. This is a shared serializer.
@return the default serializer for this network. | [
"Return",
"the",
"default",
"serializer",
"for",
"this",
"network",
".",
"This",
"is",
"a",
"shared",
"serializer",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/NetworkParameters.java#L397-L413 |
23,368 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/NetworkParameters.java | NetworkParameters.getBlockVerificationFlags | public EnumSet<Block.VerifyFlag> getBlockVerificationFlags(final Block block,
final VersionTally tally, final Integer height) {
final EnumSet<Block.VerifyFlag> flags = EnumSet.noneOf(Block.VerifyFlag.class);
if (block.isBIP34()) {
final Integer count = tally.getCountAtOrAbove(Block.BLOCK_VERSION_BIP34);
if (null != count && count >= getMajorityEnforceBlockUpgrade()) {
flags.add(Block.VerifyFlag.HEIGHT_IN_COINBASE);
}
}
return flags;
} | java | public EnumSet<Block.VerifyFlag> getBlockVerificationFlags(final Block block,
final VersionTally tally, final Integer height) {
final EnumSet<Block.VerifyFlag> flags = EnumSet.noneOf(Block.VerifyFlag.class);
if (block.isBIP34()) {
final Integer count = tally.getCountAtOrAbove(Block.BLOCK_VERSION_BIP34);
if (null != count && count >= getMajorityEnforceBlockUpgrade()) {
flags.add(Block.VerifyFlag.HEIGHT_IN_COINBASE);
}
}
return flags;
} | [
"public",
"EnumSet",
"<",
"Block",
".",
"VerifyFlag",
">",
"getBlockVerificationFlags",
"(",
"final",
"Block",
"block",
",",
"final",
"VersionTally",
"tally",
",",
"final",
"Integer",
"height",
")",
"{",
"final",
"EnumSet",
"<",
"Block",
".",
"VerifyFlag",
">",
"flags",
"=",
"EnumSet",
".",
"noneOf",
"(",
"Block",
".",
"VerifyFlag",
".",
"class",
")",
";",
"if",
"(",
"block",
".",
"isBIP34",
"(",
")",
")",
"{",
"final",
"Integer",
"count",
"=",
"tally",
".",
"getCountAtOrAbove",
"(",
"Block",
".",
"BLOCK_VERSION_BIP34",
")",
";",
"if",
"(",
"null",
"!=",
"count",
"&&",
"count",
">=",
"getMajorityEnforceBlockUpgrade",
"(",
")",
")",
"{",
"flags",
".",
"add",
"(",
"Block",
".",
"VerifyFlag",
".",
"HEIGHT_IN_COINBASE",
")",
";",
"}",
"}",
"return",
"flags",
";",
"}"
] | The flags indicating which block validation tests should be applied to
the given block. Enables support for alternative blockchains which enable
tests based on different criteria.
@param block block to determine flags for.
@param height height of the block, if known, null otherwise. Returned
tests should be a safe subset if block height is unknown. | [
"The",
"flags",
"indicating",
"which",
"block",
"validation",
"tests",
"should",
"be",
"applied",
"to",
"the",
"given",
"block",
".",
"Enables",
"support",
"for",
"alternative",
"blockchains",
"which",
"enable",
"tests",
"based",
"on",
"different",
"criteria",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/NetworkParameters.java#L455-L466 |
23,369 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/NetworkParameters.java | NetworkParameters.getTransactionVerificationFlags | public EnumSet<Script.VerifyFlag> getTransactionVerificationFlags(final Block block,
final Transaction transaction, final VersionTally tally, final Integer height) {
final EnumSet<Script.VerifyFlag> verifyFlags = EnumSet.noneOf(Script.VerifyFlag.class);
if (block.getTimeSeconds() >= NetworkParameters.BIP16_ENFORCE_TIME)
verifyFlags.add(Script.VerifyFlag.P2SH);
// Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
// blocks, when 75% of the network has upgraded:
if (block.getVersion() >= Block.BLOCK_VERSION_BIP65 &&
tally.getCountAtOrAbove(Block.BLOCK_VERSION_BIP65) > this.getMajorityEnforceBlockUpgrade()) {
verifyFlags.add(Script.VerifyFlag.CHECKLOCKTIMEVERIFY);
}
return verifyFlags;
} | java | public EnumSet<Script.VerifyFlag> getTransactionVerificationFlags(final Block block,
final Transaction transaction, final VersionTally tally, final Integer height) {
final EnumSet<Script.VerifyFlag> verifyFlags = EnumSet.noneOf(Script.VerifyFlag.class);
if (block.getTimeSeconds() >= NetworkParameters.BIP16_ENFORCE_TIME)
verifyFlags.add(Script.VerifyFlag.P2SH);
// Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4
// blocks, when 75% of the network has upgraded:
if (block.getVersion() >= Block.BLOCK_VERSION_BIP65 &&
tally.getCountAtOrAbove(Block.BLOCK_VERSION_BIP65) > this.getMajorityEnforceBlockUpgrade()) {
verifyFlags.add(Script.VerifyFlag.CHECKLOCKTIMEVERIFY);
}
return verifyFlags;
} | [
"public",
"EnumSet",
"<",
"Script",
".",
"VerifyFlag",
">",
"getTransactionVerificationFlags",
"(",
"final",
"Block",
"block",
",",
"final",
"Transaction",
"transaction",
",",
"final",
"VersionTally",
"tally",
",",
"final",
"Integer",
"height",
")",
"{",
"final",
"EnumSet",
"<",
"Script",
".",
"VerifyFlag",
">",
"verifyFlags",
"=",
"EnumSet",
".",
"noneOf",
"(",
"Script",
".",
"VerifyFlag",
".",
"class",
")",
";",
"if",
"(",
"block",
".",
"getTimeSeconds",
"(",
")",
">=",
"NetworkParameters",
".",
"BIP16_ENFORCE_TIME",
")",
"verifyFlags",
".",
"add",
"(",
"Script",
".",
"VerifyFlag",
".",
"P2SH",
")",
";",
"// Start enforcing CHECKLOCKTIMEVERIFY, (BIP65) for block.nVersion=4",
"// blocks, when 75% of the network has upgraded:",
"if",
"(",
"block",
".",
"getVersion",
"(",
")",
">=",
"Block",
".",
"BLOCK_VERSION_BIP65",
"&&",
"tally",
".",
"getCountAtOrAbove",
"(",
"Block",
".",
"BLOCK_VERSION_BIP65",
")",
">",
"this",
".",
"getMajorityEnforceBlockUpgrade",
"(",
")",
")",
"{",
"verifyFlags",
".",
"add",
"(",
"Script",
".",
"VerifyFlag",
".",
"CHECKLOCKTIMEVERIFY",
")",
";",
"}",
"return",
"verifyFlags",
";",
"}"
] | The flags indicating which script validation tests should be applied to
the given transaction. Enables support for alternative blockchains which enable
tests based on different criteria.
@param block block the transaction belongs to.
@param transaction to determine flags for.
@param height height of the block, if known, null otherwise. Returned
tests should be a safe subset if block height is unknown. | [
"The",
"flags",
"indicating",
"which",
"script",
"validation",
"tests",
"should",
"be",
"applied",
"to",
"the",
"given",
"transaction",
".",
"Enables",
"support",
"for",
"alternative",
"blockchains",
"which",
"enable",
"tests",
"based",
"on",
"different",
"criteria",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/NetworkParameters.java#L478-L492 |
23,370 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/net/ProtobufConnection.java | ProtobufConnection.deserializeMessage | @SuppressWarnings("unchecked")
// The warning 'unchecked cast' being suppressed here comes from the build() formally returning
// a MessageLite-derived class that cannot be statically guaranteed to be the MessageType.
private void deserializeMessage(ByteBuffer buff) throws Exception {
MessageType msg = (MessageType) prototype.newBuilderForType().mergeFrom(ByteString.copyFrom(buff)).build();
resetTimeout();
handler.messageReceived(this, msg);
} | java | @SuppressWarnings("unchecked")
// The warning 'unchecked cast' being suppressed here comes from the build() formally returning
// a MessageLite-derived class that cannot be statically guaranteed to be the MessageType.
private void deserializeMessage(ByteBuffer buff) throws Exception {
MessageType msg = (MessageType) prototype.newBuilderForType().mergeFrom(ByteString.copyFrom(buff)).build();
resetTimeout();
handler.messageReceived(this, msg);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"// The warning 'unchecked cast' being suppressed here comes from the build() formally returning",
"// a MessageLite-derived class that cannot be statically guaranteed to be the MessageType.",
"private",
"void",
"deserializeMessage",
"(",
"ByteBuffer",
"buff",
")",
"throws",
"Exception",
"{",
"MessageType",
"msg",
"=",
"(",
"MessageType",
")",
"prototype",
".",
"newBuilderForType",
"(",
")",
".",
"mergeFrom",
"(",
"ByteString",
".",
"copyFrom",
"(",
"buff",
")",
")",
".",
"build",
"(",
")",
";",
"resetTimeout",
"(",
")",
";",
"handler",
".",
"messageReceived",
"(",
"this",
",",
"msg",
")",
";",
"}"
] | Does set the buffers's position to its limit | [
"Does",
"set",
"the",
"buffers",
"s",
"position",
"to",
"its",
"limit"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/net/ProtobufConnection.java#L127-L134 |
23,371 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoin/NativeSecp256k1.java | NativeSecp256k1.secKeyVerify | public static boolean secKeyVerify(byte[] seckey) {
Preconditions.checkArgument(seckey.length == 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < seckey.length) {
byteBuff = ByteBuffer.allocateDirect(seckey.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(seckey);
r.lock();
try {
return secp256k1_ec_seckey_verify(byteBuff, Secp256k1Context.getContext()) == 1;
} finally {
r.unlock();
}
} | java | public static boolean secKeyVerify(byte[] seckey) {
Preconditions.checkArgument(seckey.length == 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < seckey.length) {
byteBuff = ByteBuffer.allocateDirect(seckey.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(seckey);
r.lock();
try {
return secp256k1_ec_seckey_verify(byteBuff, Secp256k1Context.getContext()) == 1;
} finally {
r.unlock();
}
} | [
"public",
"static",
"boolean",
"secKeyVerify",
"(",
"byte",
"[",
"]",
"seckey",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"seckey",
".",
"length",
"==",
"32",
")",
";",
"ByteBuffer",
"byteBuff",
"=",
"nativeECDSABuffer",
".",
"get",
"(",
")",
";",
"if",
"(",
"byteBuff",
"==",
"null",
"||",
"byteBuff",
".",
"capacity",
"(",
")",
"<",
"seckey",
".",
"length",
")",
"{",
"byteBuff",
"=",
"ByteBuffer",
".",
"allocateDirect",
"(",
"seckey",
".",
"length",
")",
";",
"byteBuff",
".",
"order",
"(",
"ByteOrder",
".",
"nativeOrder",
"(",
")",
")",
";",
"nativeECDSABuffer",
".",
"set",
"(",
"byteBuff",
")",
";",
"}",
"byteBuff",
".",
"rewind",
"(",
")",
";",
"byteBuff",
".",
"put",
"(",
"seckey",
")",
";",
"r",
".",
"lock",
"(",
")",
";",
"try",
"{",
"return",
"secp256k1_ec_seckey_verify",
"(",
"byteBuff",
",",
"Secp256k1Context",
".",
"getContext",
"(",
")",
")",
"==",
"1",
";",
"}",
"finally",
"{",
"r",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | libsecp256k1 Seckey Verify - returns 1 if valid, 0 if invalid
@param seckey ECDSA Secret key, 32 bytes | [
"libsecp256k1",
"Seckey",
"Verify",
"-",
"returns",
"1",
"if",
"valid",
"0",
"if",
"invalid"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoin/NativeSecp256k1.java#L120-L138 |
23,372 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoin/NativeSecp256k1.java | NativeSecp256k1.privKeyTweakMul | public static byte[] privKeyTweakMul(byte[] privkey, byte[] tweak) throws AssertFailException {
Preconditions.checkArgument(privkey.length == 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) {
byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(privkey);
byteBuff.put(tweak);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_privkey_tweak_mul(byteBuff, Secp256k1Context.getContext());
} finally {
r.unlock();
}
byte[] privArr = retByteArray[0];
int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(privArr.length, privLen, "Got bad pubkey length.");
assertEquals(retVal, 1, "Failed return value check.");
return privArr;
} | java | public static byte[] privKeyTweakMul(byte[] privkey, byte[] tweak) throws AssertFailException {
Preconditions.checkArgument(privkey.length == 32);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) {
byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(privkey);
byteBuff.put(tweak);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_privkey_tweak_mul(byteBuff, Secp256k1Context.getContext());
} finally {
r.unlock();
}
byte[] privArr = retByteArray[0];
int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(privArr.length, privLen, "Got bad pubkey length.");
assertEquals(retVal, 1, "Failed return value check.");
return privArr;
} | [
"public",
"static",
"byte",
"[",
"]",
"privKeyTweakMul",
"(",
"byte",
"[",
"]",
"privkey",
",",
"byte",
"[",
"]",
"tweak",
")",
"throws",
"AssertFailException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"privkey",
".",
"length",
"==",
"32",
")",
";",
"ByteBuffer",
"byteBuff",
"=",
"nativeECDSABuffer",
".",
"get",
"(",
")",
";",
"if",
"(",
"byteBuff",
"==",
"null",
"||",
"byteBuff",
".",
"capacity",
"(",
")",
"<",
"privkey",
".",
"length",
"+",
"tweak",
".",
"length",
")",
"{",
"byteBuff",
"=",
"ByteBuffer",
".",
"allocateDirect",
"(",
"privkey",
".",
"length",
"+",
"tweak",
".",
"length",
")",
";",
"byteBuff",
".",
"order",
"(",
"ByteOrder",
".",
"nativeOrder",
"(",
")",
")",
";",
"nativeECDSABuffer",
".",
"set",
"(",
"byteBuff",
")",
";",
"}",
"byteBuff",
".",
"rewind",
"(",
")",
";",
"byteBuff",
".",
"put",
"(",
"privkey",
")",
";",
"byteBuff",
".",
"put",
"(",
"tweak",
")",
";",
"byte",
"[",
"]",
"[",
"]",
"retByteArray",
";",
"r",
".",
"lock",
"(",
")",
";",
"try",
"{",
"retByteArray",
"=",
"secp256k1_privkey_tweak_mul",
"(",
"byteBuff",
",",
"Secp256k1Context",
".",
"getContext",
"(",
")",
")",
";",
"}",
"finally",
"{",
"r",
".",
"unlock",
"(",
")",
";",
"}",
"byte",
"[",
"]",
"privArr",
"=",
"retByteArray",
"[",
"0",
"]",
";",
"int",
"privLen",
"=",
"(",
"byte",
")",
"new",
"BigInteger",
"(",
"new",
"byte",
"[",
"]",
"{",
"retByteArray",
"[",
"1",
"]",
"[",
"0",
"]",
"}",
")",
".",
"intValue",
"(",
")",
"&",
"0xFF",
";",
"int",
"retVal",
"=",
"new",
"BigInteger",
"(",
"new",
"byte",
"[",
"]",
"{",
"retByteArray",
"[",
"1",
"]",
"[",
"1",
"]",
"}",
")",
".",
"intValue",
"(",
")",
";",
"assertEquals",
"(",
"privArr",
".",
"length",
",",
"privLen",
",",
"\"Got bad pubkey length.\"",
")",
";",
"assertEquals",
"(",
"retVal",
",",
"1",
",",
"\"Failed return value check.\"",
")",
";",
"return",
"privArr",
";",
"}"
] | libsecp256k1 PrivKey Tweak-Mul - Tweak privkey by multiplying to it
@param tweak some bytes to tweak with
@param privkey 32-byte seckey | [
"libsecp256k1",
"PrivKey",
"Tweak",
"-",
"Mul",
"-",
"Tweak",
"privkey",
"by",
"multiplying",
"to",
"it"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoin/NativeSecp256k1.java#L205-L236 |
23,373 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoin/NativeSecp256k1.java | NativeSecp256k1.pubKeyTweakAdd | public static byte[] pubKeyTweakAdd(byte[] pubkey, byte[] tweak) throws AssertFailException {
Preconditions.checkArgument(pubkey.length == 33 || pubkey.length == 65);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) {
byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(pubkey);
byteBuff.put(tweak);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_pubkey_tweak_add(byteBuff, Secp256k1Context.getContext(), pubkey.length);
} finally {
r.unlock();
}
byte[] pubArr = retByteArray[0];
int pubLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");
assertEquals(retVal, 1, "Failed return value check.");
return pubArr;
} | java | public static byte[] pubKeyTweakAdd(byte[] pubkey, byte[] tweak) throws AssertFailException {
Preconditions.checkArgument(pubkey.length == 33 || pubkey.length == 65);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) {
byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(pubkey);
byteBuff.put(tweak);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_pubkey_tweak_add(byteBuff, Secp256k1Context.getContext(), pubkey.length);
} finally {
r.unlock();
}
byte[] pubArr = retByteArray[0];
int pubLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();
assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");
assertEquals(retVal, 1, "Failed return value check.");
return pubArr;
} | [
"public",
"static",
"byte",
"[",
"]",
"pubKeyTweakAdd",
"(",
"byte",
"[",
"]",
"pubkey",
",",
"byte",
"[",
"]",
"tweak",
")",
"throws",
"AssertFailException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"pubkey",
".",
"length",
"==",
"33",
"||",
"pubkey",
".",
"length",
"==",
"65",
")",
";",
"ByteBuffer",
"byteBuff",
"=",
"nativeECDSABuffer",
".",
"get",
"(",
")",
";",
"if",
"(",
"byteBuff",
"==",
"null",
"||",
"byteBuff",
".",
"capacity",
"(",
")",
"<",
"pubkey",
".",
"length",
"+",
"tweak",
".",
"length",
")",
"{",
"byteBuff",
"=",
"ByteBuffer",
".",
"allocateDirect",
"(",
"pubkey",
".",
"length",
"+",
"tweak",
".",
"length",
")",
";",
"byteBuff",
".",
"order",
"(",
"ByteOrder",
".",
"nativeOrder",
"(",
")",
")",
";",
"nativeECDSABuffer",
".",
"set",
"(",
"byteBuff",
")",
";",
"}",
"byteBuff",
".",
"rewind",
"(",
")",
";",
"byteBuff",
".",
"put",
"(",
"pubkey",
")",
";",
"byteBuff",
".",
"put",
"(",
"tweak",
")",
";",
"byte",
"[",
"]",
"[",
"]",
"retByteArray",
";",
"r",
".",
"lock",
"(",
")",
";",
"try",
"{",
"retByteArray",
"=",
"secp256k1_pubkey_tweak_add",
"(",
"byteBuff",
",",
"Secp256k1Context",
".",
"getContext",
"(",
")",
",",
"pubkey",
".",
"length",
")",
";",
"}",
"finally",
"{",
"r",
".",
"unlock",
"(",
")",
";",
"}",
"byte",
"[",
"]",
"pubArr",
"=",
"retByteArray",
"[",
"0",
"]",
";",
"int",
"pubLen",
"=",
"(",
"byte",
")",
"new",
"BigInteger",
"(",
"new",
"byte",
"[",
"]",
"{",
"retByteArray",
"[",
"1",
"]",
"[",
"0",
"]",
"}",
")",
".",
"intValue",
"(",
")",
"&",
"0xFF",
";",
"int",
"retVal",
"=",
"new",
"BigInteger",
"(",
"new",
"byte",
"[",
"]",
"{",
"retByteArray",
"[",
"1",
"]",
"[",
"1",
"]",
"}",
")",
".",
"intValue",
"(",
")",
";",
"assertEquals",
"(",
"pubArr",
".",
"length",
",",
"pubLen",
",",
"\"Got bad pubkey length.\"",
")",
";",
"assertEquals",
"(",
"retVal",
",",
"1",
",",
"\"Failed return value check.\"",
")",
";",
"return",
"pubArr",
";",
"}"
] | libsecp256k1 PubKey Tweak-Add - Tweak pubkey by adding to it
@param tweak some bytes to tweak with
@param pubkey 32-byte seckey | [
"libsecp256k1",
"PubKey",
"Tweak",
"-",
"Add",
"-",
"Tweak",
"pubkey",
"by",
"adding",
"to",
"it"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoin/NativeSecp256k1.java#L283-L314 |
23,374 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoin/NativeSecp256k1.java | NativeSecp256k1.createECDHSecret | public static byte[] createECDHSecret(byte[] seckey, byte[] pubkey) throws AssertFailException {
Preconditions.checkArgument(seckey.length <= 32 && pubkey.length <= 65);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < 32 + pubkey.length) {
byteBuff = ByteBuffer.allocateDirect(32 + pubkey.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(seckey);
byteBuff.put(pubkey);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_ecdh(byteBuff, Secp256k1Context.getContext(), pubkey.length);
} finally {
r.unlock();
}
byte[] resArr = retByteArray[0];
int retVal = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();
assertEquals(resArr.length, 32, "Got bad result length.");
assertEquals(retVal, 1, "Failed return value check.");
return resArr;
} | java | public static byte[] createECDHSecret(byte[] seckey, byte[] pubkey) throws AssertFailException {
Preconditions.checkArgument(seckey.length <= 32 && pubkey.length <= 65);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < 32 + pubkey.length) {
byteBuff = ByteBuffer.allocateDirect(32 + pubkey.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(seckey);
byteBuff.put(pubkey);
byte[][] retByteArray;
r.lock();
try {
retByteArray = secp256k1_ecdh(byteBuff, Secp256k1Context.getContext(), pubkey.length);
} finally {
r.unlock();
}
byte[] resArr = retByteArray[0];
int retVal = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();
assertEquals(resArr.length, 32, "Got bad result length.");
assertEquals(retVal, 1, "Failed return value check.");
return resArr;
} | [
"public",
"static",
"byte",
"[",
"]",
"createECDHSecret",
"(",
"byte",
"[",
"]",
"seckey",
",",
"byte",
"[",
"]",
"pubkey",
")",
"throws",
"AssertFailException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"seckey",
".",
"length",
"<=",
"32",
"&&",
"pubkey",
".",
"length",
"<=",
"65",
")",
";",
"ByteBuffer",
"byteBuff",
"=",
"nativeECDSABuffer",
".",
"get",
"(",
")",
";",
"if",
"(",
"byteBuff",
"==",
"null",
"||",
"byteBuff",
".",
"capacity",
"(",
")",
"<",
"32",
"+",
"pubkey",
".",
"length",
")",
"{",
"byteBuff",
"=",
"ByteBuffer",
".",
"allocateDirect",
"(",
"32",
"+",
"pubkey",
".",
"length",
")",
";",
"byteBuff",
".",
"order",
"(",
"ByteOrder",
".",
"nativeOrder",
"(",
")",
")",
";",
"nativeECDSABuffer",
".",
"set",
"(",
"byteBuff",
")",
";",
"}",
"byteBuff",
".",
"rewind",
"(",
")",
";",
"byteBuff",
".",
"put",
"(",
"seckey",
")",
";",
"byteBuff",
".",
"put",
"(",
"pubkey",
")",
";",
"byte",
"[",
"]",
"[",
"]",
"retByteArray",
";",
"r",
".",
"lock",
"(",
")",
";",
"try",
"{",
"retByteArray",
"=",
"secp256k1_ecdh",
"(",
"byteBuff",
",",
"Secp256k1Context",
".",
"getContext",
"(",
")",
",",
"pubkey",
".",
"length",
")",
";",
"}",
"finally",
"{",
"r",
".",
"unlock",
"(",
")",
";",
"}",
"byte",
"[",
"]",
"resArr",
"=",
"retByteArray",
"[",
"0",
"]",
";",
"int",
"retVal",
"=",
"new",
"BigInteger",
"(",
"new",
"byte",
"[",
"]",
"{",
"retByteArray",
"[",
"1",
"]",
"[",
"0",
"]",
"}",
")",
".",
"intValue",
"(",
")",
";",
"assertEquals",
"(",
"resArr",
".",
"length",
",",
"32",
",",
"\"Got bad result length.\"",
")",
";",
"assertEquals",
"(",
"retVal",
",",
"1",
",",
"\"Failed return value check.\"",
")",
";",
"return",
"resArr",
";",
"}"
] | libsecp256k1 create ECDH secret - constant time ECDH calculation
@param seckey byte array of secret key used in exponentiaion
@param pubkey byte array of public key used in exponentiaion | [
"libsecp256k1",
"create",
"ECDH",
"secret",
"-",
"constant",
"time",
"ECDH",
"calculation"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoin/NativeSecp256k1.java#L361-L389 |
23,375 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoin/NativeSecp256k1.java | NativeSecp256k1.randomize | public static synchronized boolean randomize(byte[] seed) throws AssertFailException {
Preconditions.checkArgument(seed.length == 32 || seed == null);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < seed.length) {
byteBuff = ByteBuffer.allocateDirect(seed.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(seed);
w.lock();
try {
return secp256k1_context_randomize(byteBuff, Secp256k1Context.getContext()) == 1;
} finally {
w.unlock();
}
} | java | public static synchronized boolean randomize(byte[] seed) throws AssertFailException {
Preconditions.checkArgument(seed.length == 32 || seed == null);
ByteBuffer byteBuff = nativeECDSABuffer.get();
if (byteBuff == null || byteBuff.capacity() < seed.length) {
byteBuff = ByteBuffer.allocateDirect(seed.length);
byteBuff.order(ByteOrder.nativeOrder());
nativeECDSABuffer.set(byteBuff);
}
byteBuff.rewind();
byteBuff.put(seed);
w.lock();
try {
return secp256k1_context_randomize(byteBuff, Secp256k1Context.getContext()) == 1;
} finally {
w.unlock();
}
} | [
"public",
"static",
"synchronized",
"boolean",
"randomize",
"(",
"byte",
"[",
"]",
"seed",
")",
"throws",
"AssertFailException",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"seed",
".",
"length",
"==",
"32",
"||",
"seed",
"==",
"null",
")",
";",
"ByteBuffer",
"byteBuff",
"=",
"nativeECDSABuffer",
".",
"get",
"(",
")",
";",
"if",
"(",
"byteBuff",
"==",
"null",
"||",
"byteBuff",
".",
"capacity",
"(",
")",
"<",
"seed",
".",
"length",
")",
"{",
"byteBuff",
"=",
"ByteBuffer",
".",
"allocateDirect",
"(",
"seed",
".",
"length",
")",
";",
"byteBuff",
".",
"order",
"(",
"ByteOrder",
".",
"nativeOrder",
"(",
")",
")",
";",
"nativeECDSABuffer",
".",
"set",
"(",
"byteBuff",
")",
";",
"}",
"byteBuff",
".",
"rewind",
"(",
")",
";",
"byteBuff",
".",
"put",
"(",
"seed",
")",
";",
"w",
".",
"lock",
"(",
")",
";",
"try",
"{",
"return",
"secp256k1_context_randomize",
"(",
"byteBuff",
",",
"Secp256k1Context",
".",
"getContext",
"(",
")",
")",
"==",
"1",
";",
"}",
"finally",
"{",
"w",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | libsecp256k1 randomize - updates the context randomization
@param seed 32-byte random seed | [
"libsecp256k1",
"randomize",
"-",
"updates",
"the",
"context",
"randomization"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoin/NativeSecp256k1.java#L396-L414 |
23,376 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PartialMerkleTree.java | PartialMerkleTree.buildFromLeaves | public static PartialMerkleTree buildFromLeaves(NetworkParameters params, byte[] includeBits, List<Sha256Hash> allLeafHashes) {
// Calculate height of the tree.
int height = 0;
while (getTreeWidth(allLeafHashes.size(), height) > 1)
height++;
List<Boolean> bitList = new ArrayList<>();
List<Sha256Hash> hashes = new ArrayList<>();
traverseAndBuild(height, 0, allLeafHashes, includeBits, bitList, hashes);
byte[] bits = new byte[(int)Math.ceil(bitList.size() / 8.0)];
for (int i = 0; i < bitList.size(); i++)
if (bitList.get(i))
Utils.setBitLE(bits, i);
return new PartialMerkleTree(params, bits, hashes, allLeafHashes.size());
} | java | public static PartialMerkleTree buildFromLeaves(NetworkParameters params, byte[] includeBits, List<Sha256Hash> allLeafHashes) {
// Calculate height of the tree.
int height = 0;
while (getTreeWidth(allLeafHashes.size(), height) > 1)
height++;
List<Boolean> bitList = new ArrayList<>();
List<Sha256Hash> hashes = new ArrayList<>();
traverseAndBuild(height, 0, allLeafHashes, includeBits, bitList, hashes);
byte[] bits = new byte[(int)Math.ceil(bitList.size() / 8.0)];
for (int i = 0; i < bitList.size(); i++)
if (bitList.get(i))
Utils.setBitLE(bits, i);
return new PartialMerkleTree(params, bits, hashes, allLeafHashes.size());
} | [
"public",
"static",
"PartialMerkleTree",
"buildFromLeaves",
"(",
"NetworkParameters",
"params",
",",
"byte",
"[",
"]",
"includeBits",
",",
"List",
"<",
"Sha256Hash",
">",
"allLeafHashes",
")",
"{",
"// Calculate height of the tree.",
"int",
"height",
"=",
"0",
";",
"while",
"(",
"getTreeWidth",
"(",
"allLeafHashes",
".",
"size",
"(",
")",
",",
"height",
")",
">",
"1",
")",
"height",
"++",
";",
"List",
"<",
"Boolean",
">",
"bitList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"List",
"<",
"Sha256Hash",
">",
"hashes",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"traverseAndBuild",
"(",
"height",
",",
"0",
",",
"allLeafHashes",
",",
"includeBits",
",",
"bitList",
",",
"hashes",
")",
";",
"byte",
"[",
"]",
"bits",
"=",
"new",
"byte",
"[",
"(",
"int",
")",
"Math",
".",
"ceil",
"(",
"bitList",
".",
"size",
"(",
")",
"/",
"8.0",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"bitList",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"if",
"(",
"bitList",
".",
"get",
"(",
"i",
")",
")",
"Utils",
".",
"setBitLE",
"(",
"bits",
",",
"i",
")",
";",
"return",
"new",
"PartialMerkleTree",
"(",
"params",
",",
"bits",
",",
"hashes",
",",
"allLeafHashes",
".",
"size",
"(",
")",
")",
";",
"}"
] | Calculates a PMT given the list of leaf hashes and which leaves need to be included. The relevant interior hashes
are calculated and a new PMT returned. | [
"Calculates",
"a",
"PMT",
"given",
"the",
"list",
"of",
"leaf",
"hashes",
"and",
"which",
"leaves",
"need",
"to",
"be",
"included",
".",
"The",
"relevant",
"interior",
"hashes",
"are",
"calculated",
"and",
"a",
"new",
"PMT",
"returned",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PartialMerkleTree.java#L89-L102 |
23,377 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PartialMerkleTree.java | PartialMerkleTree.recursiveExtractHashes | private Sha256Hash recursiveExtractHashes(int height, int pos, ValuesUsed used, List<Sha256Hash> matchedHashes) throws VerificationException {
if (used.bitsUsed >= matchedChildBits.length*8) {
// overflowed the bits array - failure
throw new VerificationException("PartialMerkleTree overflowed its bits array");
}
boolean parentOfMatch = checkBitLE(matchedChildBits, used.bitsUsed++);
if (height == 0 || !parentOfMatch) {
// if at height 0, or nothing interesting below, use stored hash and do not descend
if (used.hashesUsed >= hashes.size()) {
// overflowed the hash array - failure
throw new VerificationException("PartialMerkleTree overflowed its hash array");
}
Sha256Hash hash = hashes.get(used.hashesUsed++);
if (height == 0 && parentOfMatch) // in case of height 0, we have a matched txid
matchedHashes.add(hash);
return hash;
} else {
// otherwise, descend into the subtrees to extract matched txids and hashes
byte[] left = recursiveExtractHashes(height - 1, pos * 2, used, matchedHashes).getBytes(), right;
if (pos * 2 + 1 < getTreeWidth(transactionCount, height-1)) {
right = recursiveExtractHashes(height - 1, pos * 2 + 1, used, matchedHashes).getBytes();
if (Arrays.equals(right, left))
throw new VerificationException("Invalid merkle tree with duplicated left/right branches");
} else {
right = left;
}
// and combine them before returning
return combineLeftRight(left, right);
}
} | java | private Sha256Hash recursiveExtractHashes(int height, int pos, ValuesUsed used, List<Sha256Hash> matchedHashes) throws VerificationException {
if (used.bitsUsed >= matchedChildBits.length*8) {
// overflowed the bits array - failure
throw new VerificationException("PartialMerkleTree overflowed its bits array");
}
boolean parentOfMatch = checkBitLE(matchedChildBits, used.bitsUsed++);
if (height == 0 || !parentOfMatch) {
// if at height 0, or nothing interesting below, use stored hash and do not descend
if (used.hashesUsed >= hashes.size()) {
// overflowed the hash array - failure
throw new VerificationException("PartialMerkleTree overflowed its hash array");
}
Sha256Hash hash = hashes.get(used.hashesUsed++);
if (height == 0 && parentOfMatch) // in case of height 0, we have a matched txid
matchedHashes.add(hash);
return hash;
} else {
// otherwise, descend into the subtrees to extract matched txids and hashes
byte[] left = recursiveExtractHashes(height - 1, pos * 2, used, matchedHashes).getBytes(), right;
if (pos * 2 + 1 < getTreeWidth(transactionCount, height-1)) {
right = recursiveExtractHashes(height - 1, pos * 2 + 1, used, matchedHashes).getBytes();
if (Arrays.equals(right, left))
throw new VerificationException("Invalid merkle tree with duplicated left/right branches");
} else {
right = left;
}
// and combine them before returning
return combineLeftRight(left, right);
}
} | [
"private",
"Sha256Hash",
"recursiveExtractHashes",
"(",
"int",
"height",
",",
"int",
"pos",
",",
"ValuesUsed",
"used",
",",
"List",
"<",
"Sha256Hash",
">",
"matchedHashes",
")",
"throws",
"VerificationException",
"{",
"if",
"(",
"used",
".",
"bitsUsed",
">=",
"matchedChildBits",
".",
"length",
"*",
"8",
")",
"{",
"// overflowed the bits array - failure",
"throw",
"new",
"VerificationException",
"(",
"\"PartialMerkleTree overflowed its bits array\"",
")",
";",
"}",
"boolean",
"parentOfMatch",
"=",
"checkBitLE",
"(",
"matchedChildBits",
",",
"used",
".",
"bitsUsed",
"++",
")",
";",
"if",
"(",
"height",
"==",
"0",
"||",
"!",
"parentOfMatch",
")",
"{",
"// if at height 0, or nothing interesting below, use stored hash and do not descend",
"if",
"(",
"used",
".",
"hashesUsed",
">=",
"hashes",
".",
"size",
"(",
")",
")",
"{",
"// overflowed the hash array - failure",
"throw",
"new",
"VerificationException",
"(",
"\"PartialMerkleTree overflowed its hash array\"",
")",
";",
"}",
"Sha256Hash",
"hash",
"=",
"hashes",
".",
"get",
"(",
"used",
".",
"hashesUsed",
"++",
")",
";",
"if",
"(",
"height",
"==",
"0",
"&&",
"parentOfMatch",
")",
"// in case of height 0, we have a matched txid",
"matchedHashes",
".",
"add",
"(",
"hash",
")",
";",
"return",
"hash",
";",
"}",
"else",
"{",
"// otherwise, descend into the subtrees to extract matched txids and hashes",
"byte",
"[",
"]",
"left",
"=",
"recursiveExtractHashes",
"(",
"height",
"-",
"1",
",",
"pos",
"*",
"2",
",",
"used",
",",
"matchedHashes",
")",
".",
"getBytes",
"(",
")",
",",
"right",
";",
"if",
"(",
"pos",
"*",
"2",
"+",
"1",
"<",
"getTreeWidth",
"(",
"transactionCount",
",",
"height",
"-",
"1",
")",
")",
"{",
"right",
"=",
"recursiveExtractHashes",
"(",
"height",
"-",
"1",
",",
"pos",
"*",
"2",
"+",
"1",
",",
"used",
",",
"matchedHashes",
")",
".",
"getBytes",
"(",
")",
";",
"if",
"(",
"Arrays",
".",
"equals",
"(",
"right",
",",
"left",
")",
")",
"throw",
"new",
"VerificationException",
"(",
"\"Invalid merkle tree with duplicated left/right branches\"",
")",
";",
"}",
"else",
"{",
"right",
"=",
"left",
";",
"}",
"// and combine them before returning",
"return",
"combineLeftRight",
"(",
"left",
",",
"right",
")",
";",
"}",
"}"
] | it returns the hash of the respective node. | [
"it",
"returns",
"the",
"hash",
"of",
"the",
"respective",
"node",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PartialMerkleTree.java#L186-L215 |
23,378 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/PartialMerkleTree.java | PartialMerkleTree.getTxnHashAndMerkleRoot | public Sha256Hash getTxnHashAndMerkleRoot(List<Sha256Hash> matchedHashesOut) throws VerificationException {
matchedHashesOut.clear();
// An empty set will not work
if (transactionCount == 0)
throw new VerificationException("Got a CPartialMerkleTree with 0 transactions");
// check for excessively high numbers of transactions
if (transactionCount > Block.MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
throw new VerificationException("Got a CPartialMerkleTree with more transactions than is possible");
// there can never be more hashes provided than one for every txid
if (hashes.size() > transactionCount)
throw new VerificationException("Got a CPartialMerkleTree with more hashes than transactions");
// there must be at least one bit per node in the partial tree, and at least one node per hash
if (matchedChildBits.length*8 < hashes.size())
throw new VerificationException("Got a CPartialMerkleTree with fewer matched bits than hashes");
// calculate height of tree
int height = 0;
while (getTreeWidth(transactionCount, height) > 1)
height++;
// traverse the partial tree
ValuesUsed used = new ValuesUsed();
Sha256Hash merkleRoot = recursiveExtractHashes(height, 0, used, matchedHashesOut);
// verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
if ((used.bitsUsed+7)/8 != matchedChildBits.length ||
// verify that all hashes were consumed
used.hashesUsed != hashes.size())
throw new VerificationException("Got a CPartialMerkleTree that didn't need all the data it provided");
return merkleRoot;
} | java | public Sha256Hash getTxnHashAndMerkleRoot(List<Sha256Hash> matchedHashesOut) throws VerificationException {
matchedHashesOut.clear();
// An empty set will not work
if (transactionCount == 0)
throw new VerificationException("Got a CPartialMerkleTree with 0 transactions");
// check for excessively high numbers of transactions
if (transactionCount > Block.MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction
throw new VerificationException("Got a CPartialMerkleTree with more transactions than is possible");
// there can never be more hashes provided than one for every txid
if (hashes.size() > transactionCount)
throw new VerificationException("Got a CPartialMerkleTree with more hashes than transactions");
// there must be at least one bit per node in the partial tree, and at least one node per hash
if (matchedChildBits.length*8 < hashes.size())
throw new VerificationException("Got a CPartialMerkleTree with fewer matched bits than hashes");
// calculate height of tree
int height = 0;
while (getTreeWidth(transactionCount, height) > 1)
height++;
// traverse the partial tree
ValuesUsed used = new ValuesUsed();
Sha256Hash merkleRoot = recursiveExtractHashes(height, 0, used, matchedHashesOut);
// verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
if ((used.bitsUsed+7)/8 != matchedChildBits.length ||
// verify that all hashes were consumed
used.hashesUsed != hashes.size())
throw new VerificationException("Got a CPartialMerkleTree that didn't need all the data it provided");
return merkleRoot;
} | [
"public",
"Sha256Hash",
"getTxnHashAndMerkleRoot",
"(",
"List",
"<",
"Sha256Hash",
">",
"matchedHashesOut",
")",
"throws",
"VerificationException",
"{",
"matchedHashesOut",
".",
"clear",
"(",
")",
";",
"// An empty set will not work",
"if",
"(",
"transactionCount",
"==",
"0",
")",
"throw",
"new",
"VerificationException",
"(",
"\"Got a CPartialMerkleTree with 0 transactions\"",
")",
";",
"// check for excessively high numbers of transactions",
"if",
"(",
"transactionCount",
">",
"Block",
".",
"MAX_BLOCK_SIZE",
"/",
"60",
")",
"// 60 is the lower bound for the size of a serialized CTransaction",
"throw",
"new",
"VerificationException",
"(",
"\"Got a CPartialMerkleTree with more transactions than is possible\"",
")",
";",
"// there can never be more hashes provided than one for every txid",
"if",
"(",
"hashes",
".",
"size",
"(",
")",
">",
"transactionCount",
")",
"throw",
"new",
"VerificationException",
"(",
"\"Got a CPartialMerkleTree with more hashes than transactions\"",
")",
";",
"// there must be at least one bit per node in the partial tree, and at least one node per hash",
"if",
"(",
"matchedChildBits",
".",
"length",
"*",
"8",
"<",
"hashes",
".",
"size",
"(",
")",
")",
"throw",
"new",
"VerificationException",
"(",
"\"Got a CPartialMerkleTree with fewer matched bits than hashes\"",
")",
";",
"// calculate height of tree",
"int",
"height",
"=",
"0",
";",
"while",
"(",
"getTreeWidth",
"(",
"transactionCount",
",",
"height",
")",
">",
"1",
")",
"height",
"++",
";",
"// traverse the partial tree",
"ValuesUsed",
"used",
"=",
"new",
"ValuesUsed",
"(",
")",
";",
"Sha256Hash",
"merkleRoot",
"=",
"recursiveExtractHashes",
"(",
"height",
",",
"0",
",",
"used",
",",
"matchedHashesOut",
")",
";",
"// verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)",
"if",
"(",
"(",
"used",
".",
"bitsUsed",
"+",
"7",
")",
"/",
"8",
"!=",
"matchedChildBits",
".",
"length",
"||",
"// verify that all hashes were consumed",
"used",
".",
"hashesUsed",
"!=",
"hashes",
".",
"size",
"(",
")",
")",
"throw",
"new",
"VerificationException",
"(",
"\"Got a CPartialMerkleTree that didn't need all the data it provided\"",
")",
";",
"return",
"merkleRoot",
";",
"}"
] | Extracts tx hashes that are in this merkle tree
and returns the merkle root of this tree.
The returned root should be checked against the
merkle root contained in the block header for security.
@param matchedHashesOut A list which will contain the matched txn (will be cleared).
@return the merkle root of this merkle tree
@throws ProtocolException if this partial merkle tree is invalid | [
"Extracts",
"tx",
"hashes",
"that",
"are",
"in",
"this",
"merkle",
"tree",
"and",
"returns",
"the",
"merkle",
"root",
"of",
"this",
"tree",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/PartialMerkleTree.java#L232-L261 |
23,379 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelV1ServerState.java | PaymentChannelV1ServerState.getRefundTransactionUnlockTime | public synchronized long getRefundTransactionUnlockTime() {
checkState(getState().compareTo(State.WAITING_FOR_MULTISIG_CONTRACT) > 0 && getState() != State.ERROR);
return refundTransactionUnlockTimeSecs;
} | java | public synchronized long getRefundTransactionUnlockTime() {
checkState(getState().compareTo(State.WAITING_FOR_MULTISIG_CONTRACT) > 0 && getState() != State.ERROR);
return refundTransactionUnlockTimeSecs;
} | [
"public",
"synchronized",
"long",
"getRefundTransactionUnlockTime",
"(",
")",
"{",
"checkState",
"(",
"getState",
"(",
")",
".",
"compareTo",
"(",
"State",
".",
"WAITING_FOR_MULTISIG_CONTRACT",
")",
">",
"0",
"&&",
"getState",
"(",
")",
"!=",
"State",
".",
"ERROR",
")",
";",
"return",
"refundTransactionUnlockTimeSecs",
";",
"}"
] | Gets the client's refund transaction which they can spend to get the entire channel value back if it reaches its
lock time. | [
"Gets",
"the",
"client",
"s",
"refund",
"transaction",
"which",
"they",
"can",
"spend",
"to",
"get",
"the",
"entire",
"channel",
"value",
"back",
"if",
"it",
"reaches",
"its",
"lock",
"time",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelV1ServerState.java#L282-L285 |
23,380 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelServer.java | PaymentChannelServer.receiveMessage | public void receiveMessage(Protos.TwoWayChannelMessage msg) {
lock.lock();
try {
checkState(connectionOpen);
if (channelSettling)
return;
try {
switch (msg.getType()) {
case CLIENT_VERSION:
receiveVersionMessage(msg);
return;
case PROVIDE_REFUND:
receiveRefundMessage(msg);
return;
case PROVIDE_CONTRACT:
receiveContractMessage(msg);
return;
case UPDATE_PAYMENT:
checkState(step == InitStep.CHANNEL_OPEN && msg.hasUpdatePayment());
receiveUpdatePaymentMessage(msg.getUpdatePayment(), true);
return;
case CLOSE:
receiveCloseMessage();
return;
case ERROR:
checkState(msg.hasError());
log.error("Client sent ERROR {} with explanation {}", msg.getError().getCode().name(),
msg.getError().hasExplanation() ? msg.getError().getExplanation() : "");
conn.destroyConnection(CloseReason.REMOTE_SENT_ERROR);
return;
default:
final String errorText = "Got unknown message type or type that doesn't apply to servers.";
error(errorText, Protos.Error.ErrorCode.SYNTAX_ERROR, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
}
} catch (VerificationException e) {
log.error("Caught verification exception handling message from client", e);
error(e.getMessage(), Protos.Error.ErrorCode.BAD_TRANSACTION, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
} catch (ValueOutOfRangeException e) {
log.error("Caught value out of range exception handling message from client", e);
error(e.getMessage(), Protos.Error.ErrorCode.BAD_TRANSACTION, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
} catch (InsufficientMoneyException e) {
log.error("Caught insufficient money exception handling message from client", e);
error(e.getMessage(), Protos.Error.ErrorCode.BAD_TRANSACTION, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
} catch (SignatureDecodeException e) {
log.error("Caught illegal state exception handling message from client", e);
error(e.getMessage(), Protos.Error.ErrorCode.SYNTAX_ERROR, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
}
} finally {
lock.unlock();
}
} | java | public void receiveMessage(Protos.TwoWayChannelMessage msg) {
lock.lock();
try {
checkState(connectionOpen);
if (channelSettling)
return;
try {
switch (msg.getType()) {
case CLIENT_VERSION:
receiveVersionMessage(msg);
return;
case PROVIDE_REFUND:
receiveRefundMessage(msg);
return;
case PROVIDE_CONTRACT:
receiveContractMessage(msg);
return;
case UPDATE_PAYMENT:
checkState(step == InitStep.CHANNEL_OPEN && msg.hasUpdatePayment());
receiveUpdatePaymentMessage(msg.getUpdatePayment(), true);
return;
case CLOSE:
receiveCloseMessage();
return;
case ERROR:
checkState(msg.hasError());
log.error("Client sent ERROR {} with explanation {}", msg.getError().getCode().name(),
msg.getError().hasExplanation() ? msg.getError().getExplanation() : "");
conn.destroyConnection(CloseReason.REMOTE_SENT_ERROR);
return;
default:
final String errorText = "Got unknown message type or type that doesn't apply to servers.";
error(errorText, Protos.Error.ErrorCode.SYNTAX_ERROR, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
}
} catch (VerificationException e) {
log.error("Caught verification exception handling message from client", e);
error(e.getMessage(), Protos.Error.ErrorCode.BAD_TRANSACTION, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
} catch (ValueOutOfRangeException e) {
log.error("Caught value out of range exception handling message from client", e);
error(e.getMessage(), Protos.Error.ErrorCode.BAD_TRANSACTION, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
} catch (InsufficientMoneyException e) {
log.error("Caught insufficient money exception handling message from client", e);
error(e.getMessage(), Protos.Error.ErrorCode.BAD_TRANSACTION, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
} catch (SignatureDecodeException e) {
log.error("Caught illegal state exception handling message from client", e);
error(e.getMessage(), Protos.Error.ErrorCode.SYNTAX_ERROR, CloseReason.REMOTE_SENT_INVALID_MESSAGE);
}
} finally {
lock.unlock();
}
} | [
"public",
"void",
"receiveMessage",
"(",
"Protos",
".",
"TwoWayChannelMessage",
"msg",
")",
"{",
"lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"checkState",
"(",
"connectionOpen",
")",
";",
"if",
"(",
"channelSettling",
")",
"return",
";",
"try",
"{",
"switch",
"(",
"msg",
".",
"getType",
"(",
")",
")",
"{",
"case",
"CLIENT_VERSION",
":",
"receiveVersionMessage",
"(",
"msg",
")",
";",
"return",
";",
"case",
"PROVIDE_REFUND",
":",
"receiveRefundMessage",
"(",
"msg",
")",
";",
"return",
";",
"case",
"PROVIDE_CONTRACT",
":",
"receiveContractMessage",
"(",
"msg",
")",
";",
"return",
";",
"case",
"UPDATE_PAYMENT",
":",
"checkState",
"(",
"step",
"==",
"InitStep",
".",
"CHANNEL_OPEN",
"&&",
"msg",
".",
"hasUpdatePayment",
"(",
")",
")",
";",
"receiveUpdatePaymentMessage",
"(",
"msg",
".",
"getUpdatePayment",
"(",
")",
",",
"true",
")",
";",
"return",
";",
"case",
"CLOSE",
":",
"receiveCloseMessage",
"(",
")",
";",
"return",
";",
"case",
"ERROR",
":",
"checkState",
"(",
"msg",
".",
"hasError",
"(",
")",
")",
";",
"log",
".",
"error",
"(",
"\"Client sent ERROR {} with explanation {}\"",
",",
"msg",
".",
"getError",
"(",
")",
".",
"getCode",
"(",
")",
".",
"name",
"(",
")",
",",
"msg",
".",
"getError",
"(",
")",
".",
"hasExplanation",
"(",
")",
"?",
"msg",
".",
"getError",
"(",
")",
".",
"getExplanation",
"(",
")",
":",
"\"\"",
")",
";",
"conn",
".",
"destroyConnection",
"(",
"CloseReason",
".",
"REMOTE_SENT_ERROR",
")",
";",
"return",
";",
"default",
":",
"final",
"String",
"errorText",
"=",
"\"Got unknown message type or type that doesn't apply to servers.\"",
";",
"error",
"(",
"errorText",
",",
"Protos",
".",
"Error",
".",
"ErrorCode",
".",
"SYNTAX_ERROR",
",",
"CloseReason",
".",
"REMOTE_SENT_INVALID_MESSAGE",
")",
";",
"}",
"}",
"catch",
"(",
"VerificationException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Caught verification exception handling message from client\"",
",",
"e",
")",
";",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"Protos",
".",
"Error",
".",
"ErrorCode",
".",
"BAD_TRANSACTION",
",",
"CloseReason",
".",
"REMOTE_SENT_INVALID_MESSAGE",
")",
";",
"}",
"catch",
"(",
"ValueOutOfRangeException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Caught value out of range exception handling message from client\"",
",",
"e",
")",
";",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"Protos",
".",
"Error",
".",
"ErrorCode",
".",
"BAD_TRANSACTION",
",",
"CloseReason",
".",
"REMOTE_SENT_INVALID_MESSAGE",
")",
";",
"}",
"catch",
"(",
"InsufficientMoneyException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Caught insufficient money exception handling message from client\"",
",",
"e",
")",
";",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"Protos",
".",
"Error",
".",
"ErrorCode",
".",
"BAD_TRANSACTION",
",",
"CloseReason",
".",
"REMOTE_SENT_INVALID_MESSAGE",
")",
";",
"}",
"catch",
"(",
"SignatureDecodeException",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Caught illegal state exception handling message from client\"",
",",
"e",
")",
";",
"error",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"Protos",
".",
"Error",
".",
"ErrorCode",
".",
"SYNTAX_ERROR",
",",
"CloseReason",
".",
"REMOTE_SENT_INVALID_MESSAGE",
")",
";",
"}",
"}",
"finally",
"{",
"lock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Called when a message is received from the client. Processes the given message and generates events based on its
content. | [
"Called",
"when",
"a",
"message",
"is",
"received",
"from",
"the",
"client",
".",
"Processes",
"the",
"given",
"message",
"and",
"generates",
"events",
"based",
"on",
"its",
"content",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelServer.java#L475-L525 |
23,381 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelServerListener.java | PaymentChannelServerListener.bindAndStart | public void bindAndStart(int port) throws Exception {
server = new NioServer(new StreamConnectionFactory() {
@Override
public ProtobufConnection<Protos.TwoWayChannelMessage> getNewConnection(InetAddress inetAddress, int port) {
return new ServerHandler(new InetSocketAddress(inetAddress, port), timeoutSeconds).socketProtobufHandler;
}
}, new InetSocketAddress(port));
server.startAsync();
server.awaitRunning();
} | java | public void bindAndStart(int port) throws Exception {
server = new NioServer(new StreamConnectionFactory() {
@Override
public ProtobufConnection<Protos.TwoWayChannelMessage> getNewConnection(InetAddress inetAddress, int port) {
return new ServerHandler(new InetSocketAddress(inetAddress, port), timeoutSeconds).socketProtobufHandler;
}
}, new InetSocketAddress(port));
server.startAsync();
server.awaitRunning();
} | [
"public",
"void",
"bindAndStart",
"(",
"int",
"port",
")",
"throws",
"Exception",
"{",
"server",
"=",
"new",
"NioServer",
"(",
"new",
"StreamConnectionFactory",
"(",
")",
"{",
"@",
"Override",
"public",
"ProtobufConnection",
"<",
"Protos",
".",
"TwoWayChannelMessage",
">",
"getNewConnection",
"(",
"InetAddress",
"inetAddress",
",",
"int",
"port",
")",
"{",
"return",
"new",
"ServerHandler",
"(",
"new",
"InetSocketAddress",
"(",
"inetAddress",
",",
"port",
")",
",",
"timeoutSeconds",
")",
".",
"socketProtobufHandler",
";",
"}",
"}",
",",
"new",
"InetSocketAddress",
"(",
"port",
")",
")",
";",
"server",
".",
"startAsync",
"(",
")",
";",
"server",
".",
"awaitRunning",
"(",
")",
";",
"}"
] | Binds to the given port and starts accepting new client connections.
@throws Exception If binding to the given port fails (eg SocketException: Permission denied for privileged ports) | [
"Binds",
"to",
"the",
"given",
"port",
"and",
"starts",
"accepting",
"new",
"client",
"connections",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelServerListener.java#L152-L161 |
23,382 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/net/ConnectionHandler.java | ConnectionHandler.closeConnection | @Override
public void closeConnection() {
checkState(!lock.isHeldByCurrentThread());
try {
channel.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
connectionClosed();
} | java | @Override
public void closeConnection() {
checkState(!lock.isHeldByCurrentThread());
try {
channel.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
connectionClosed();
} | [
"@",
"Override",
"public",
"void",
"closeConnection",
"(",
")",
"{",
"checkState",
"(",
"!",
"lock",
".",
"isHeldByCurrentThread",
"(",
")",
")",
";",
"try",
"{",
"channel",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"connectionClosed",
"(",
")",
";",
"}"
] | May NOT be called with lock held | [
"May",
"NOT",
"be",
"called",
"with",
"lock",
"held"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/net/ConnectionHandler.java#L172-L181 |
23,383 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/net/ConnectionHandler.java | ConnectionHandler.handleKey | public static void handleKey(SelectionKey key) {
ConnectionHandler handler = ((ConnectionHandler)key.attachment());
try {
if (handler == null)
return;
if (!key.isValid()) {
handler.closeConnection(); // Key has been cancelled, make sure the socket gets closed
return;
}
if (key.isReadable()) {
// Do a socket read and invoke the connection's receiveBytes message
int read = handler.channel.read(handler.readBuff);
if (read == 0)
return; // Was probably waiting on a write
else if (read == -1) { // Socket was closed
key.cancel();
handler.closeConnection();
return;
}
// "flip" the buffer - setting the limit to the current position and setting position to 0
handler.readBuff.flip();
// Use connection.receiveBytes's return value as a check that it stopped reading at the right location
int bytesConsumed = checkNotNull(handler.connection).receiveBytes(handler.readBuff);
checkState(handler.readBuff.position() == bytesConsumed);
// Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative
// position)
handler.readBuff.compact();
}
if (key.isWritable())
handler.tryWriteBytes();
} catch (Exception e) {
// This can happen eg if the channel closes while the thread is about to get killed
// (ClosedByInterruptException), or if handler.connection.receiveBytes throws something
Throwable t = Throwables.getRootCause(e);
log.warn("Error handling SelectionKey: {} {}", t.getClass().getName(), t.getMessage() != null ? t.getMessage() : "", e);
handler.closeConnection();
}
} | java | public static void handleKey(SelectionKey key) {
ConnectionHandler handler = ((ConnectionHandler)key.attachment());
try {
if (handler == null)
return;
if (!key.isValid()) {
handler.closeConnection(); // Key has been cancelled, make sure the socket gets closed
return;
}
if (key.isReadable()) {
// Do a socket read and invoke the connection's receiveBytes message
int read = handler.channel.read(handler.readBuff);
if (read == 0)
return; // Was probably waiting on a write
else if (read == -1) { // Socket was closed
key.cancel();
handler.closeConnection();
return;
}
// "flip" the buffer - setting the limit to the current position and setting position to 0
handler.readBuff.flip();
// Use connection.receiveBytes's return value as a check that it stopped reading at the right location
int bytesConsumed = checkNotNull(handler.connection).receiveBytes(handler.readBuff);
checkState(handler.readBuff.position() == bytesConsumed);
// Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative
// position)
handler.readBuff.compact();
}
if (key.isWritable())
handler.tryWriteBytes();
} catch (Exception e) {
// This can happen eg if the channel closes while the thread is about to get killed
// (ClosedByInterruptException), or if handler.connection.receiveBytes throws something
Throwable t = Throwables.getRootCause(e);
log.warn("Error handling SelectionKey: {} {}", t.getClass().getName(), t.getMessage() != null ? t.getMessage() : "", e);
handler.closeConnection();
}
} | [
"public",
"static",
"void",
"handleKey",
"(",
"SelectionKey",
"key",
")",
"{",
"ConnectionHandler",
"handler",
"=",
"(",
"(",
"ConnectionHandler",
")",
"key",
".",
"attachment",
"(",
")",
")",
";",
"try",
"{",
"if",
"(",
"handler",
"==",
"null",
")",
"return",
";",
"if",
"(",
"!",
"key",
".",
"isValid",
"(",
")",
")",
"{",
"handler",
".",
"closeConnection",
"(",
")",
";",
"// Key has been cancelled, make sure the socket gets closed",
"return",
";",
"}",
"if",
"(",
"key",
".",
"isReadable",
"(",
")",
")",
"{",
"// Do a socket read and invoke the connection's receiveBytes message",
"int",
"read",
"=",
"handler",
".",
"channel",
".",
"read",
"(",
"handler",
".",
"readBuff",
")",
";",
"if",
"(",
"read",
"==",
"0",
")",
"return",
";",
"// Was probably waiting on a write",
"else",
"if",
"(",
"read",
"==",
"-",
"1",
")",
"{",
"// Socket was closed",
"key",
".",
"cancel",
"(",
")",
";",
"handler",
".",
"closeConnection",
"(",
")",
";",
"return",
";",
"}",
"// \"flip\" the buffer - setting the limit to the current position and setting position to 0",
"handler",
".",
"readBuff",
".",
"flip",
"(",
")",
";",
"// Use connection.receiveBytes's return value as a check that it stopped reading at the right location",
"int",
"bytesConsumed",
"=",
"checkNotNull",
"(",
"handler",
".",
"connection",
")",
".",
"receiveBytes",
"(",
"handler",
".",
"readBuff",
")",
";",
"checkState",
"(",
"handler",
".",
"readBuff",
".",
"position",
"(",
")",
"==",
"bytesConsumed",
")",
";",
"// Now drop the bytes which were read by compacting readBuff (resetting limit and keeping relative",
"// position)",
"handler",
".",
"readBuff",
".",
"compact",
"(",
")",
";",
"}",
"if",
"(",
"key",
".",
"isWritable",
"(",
")",
")",
"handler",
".",
"tryWriteBytes",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"// This can happen eg if the channel closes while the thread is about to get killed",
"// (ClosedByInterruptException), or if handler.connection.receiveBytes throws something",
"Throwable",
"t",
"=",
"Throwables",
".",
"getRootCause",
"(",
"e",
")",
";",
"log",
".",
"warn",
"(",
"\"Error handling SelectionKey: {} {}\"",
",",
"t",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
",",
"t",
".",
"getMessage",
"(",
")",
"!=",
"null",
"?",
"t",
".",
"getMessage",
"(",
")",
":",
"\"\"",
",",
"e",
")",
";",
"handler",
".",
"closeConnection",
"(",
")",
";",
"}",
"}"
] | atomically for a given ConnectionHandler) | [
"atomically",
"for",
"a",
"given",
"ConnectionHandler",
")"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/net/ConnectionHandler.java#L201-L238 |
23,384 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/Script.java | Script.getProgram | public byte[] getProgram() {
try {
// Don't round-trip as Bitcoin Core doesn't and it would introduce a mismatch.
if (program != null)
return Arrays.copyOf(program, program.length);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (ScriptChunk chunk : chunks) {
chunk.write(bos);
}
program = bos.toByteArray();
return program;
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
} | java | public byte[] getProgram() {
try {
// Don't round-trip as Bitcoin Core doesn't and it would introduce a mismatch.
if (program != null)
return Arrays.copyOf(program, program.length);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (ScriptChunk chunk : chunks) {
chunk.write(bos);
}
program = bos.toByteArray();
return program;
} catch (IOException e) {
throw new RuntimeException(e); // Cannot happen.
}
} | [
"public",
"byte",
"[",
"]",
"getProgram",
"(",
")",
"{",
"try",
"{",
"// Don't round-trip as Bitcoin Core doesn't and it would introduce a mismatch.",
"if",
"(",
"program",
"!=",
"null",
")",
"return",
"Arrays",
".",
"copyOf",
"(",
"program",
",",
"program",
".",
"length",
")",
";",
"ByteArrayOutputStream",
"bos",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"for",
"(",
"ScriptChunk",
"chunk",
":",
"chunks",
")",
"{",
"chunk",
".",
"write",
"(",
"bos",
")",
";",
"}",
"program",
"=",
"bos",
".",
"toByteArray",
"(",
")",
";",
"return",
"program",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"// Cannot happen.",
"}",
"}"
] | Returns the serialized program as a newly created byte array. | [
"Returns",
"the",
"serialized",
"program",
"as",
"a",
"newly",
"created",
"byte",
"array",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/Script.java#L157-L171 |
23,385 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/Script.java | Script.getToAddress | public Address getToAddress(NetworkParameters params, boolean forcePayToPubKey) throws ScriptException {
if (ScriptPattern.isP2PKH(this))
return LegacyAddress.fromPubKeyHash(params, ScriptPattern.extractHashFromP2PKH(this));
else if (ScriptPattern.isP2SH(this))
return LegacyAddress.fromScriptHash(params, ScriptPattern.extractHashFromP2SH(this));
else if (forcePayToPubKey && ScriptPattern.isP2PK(this))
return LegacyAddress.fromKey(params, ECKey.fromPublicOnly(ScriptPattern.extractKeyFromP2PK(this)));
else if (ScriptPattern.isP2WH(this))
return SegwitAddress.fromHash(params, ScriptPattern.extractHashFromP2WH(this));
else
throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Cannot cast this script to an address");
} | java | public Address getToAddress(NetworkParameters params, boolean forcePayToPubKey) throws ScriptException {
if (ScriptPattern.isP2PKH(this))
return LegacyAddress.fromPubKeyHash(params, ScriptPattern.extractHashFromP2PKH(this));
else if (ScriptPattern.isP2SH(this))
return LegacyAddress.fromScriptHash(params, ScriptPattern.extractHashFromP2SH(this));
else if (forcePayToPubKey && ScriptPattern.isP2PK(this))
return LegacyAddress.fromKey(params, ECKey.fromPublicOnly(ScriptPattern.extractKeyFromP2PK(this)));
else if (ScriptPattern.isP2WH(this))
return SegwitAddress.fromHash(params, ScriptPattern.extractHashFromP2WH(this));
else
throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Cannot cast this script to an address");
} | [
"public",
"Address",
"getToAddress",
"(",
"NetworkParameters",
"params",
",",
"boolean",
"forcePayToPubKey",
")",
"throws",
"ScriptException",
"{",
"if",
"(",
"ScriptPattern",
".",
"isP2PKH",
"(",
"this",
")",
")",
"return",
"LegacyAddress",
".",
"fromPubKeyHash",
"(",
"params",
",",
"ScriptPattern",
".",
"extractHashFromP2PKH",
"(",
"this",
")",
")",
";",
"else",
"if",
"(",
"ScriptPattern",
".",
"isP2SH",
"(",
"this",
")",
")",
"return",
"LegacyAddress",
".",
"fromScriptHash",
"(",
"params",
",",
"ScriptPattern",
".",
"extractHashFromP2SH",
"(",
"this",
")",
")",
";",
"else",
"if",
"(",
"forcePayToPubKey",
"&&",
"ScriptPattern",
".",
"isP2PK",
"(",
"this",
")",
")",
"return",
"LegacyAddress",
".",
"fromKey",
"(",
"params",
",",
"ECKey",
".",
"fromPublicOnly",
"(",
"ScriptPattern",
".",
"extractKeyFromP2PK",
"(",
"this",
")",
")",
")",
";",
"else",
"if",
"(",
"ScriptPattern",
".",
"isP2WH",
"(",
"this",
")",
")",
"return",
"SegwitAddress",
".",
"fromHash",
"(",
"params",
",",
"ScriptPattern",
".",
"extractHashFromP2WH",
"(",
"this",
")",
")",
";",
"else",
"throw",
"new",
"ScriptException",
"(",
"ScriptError",
".",
"SCRIPT_ERR_UNKNOWN_ERROR",
",",
"\"Cannot cast this script to an address\"",
")",
";",
"}"
] | Gets the destination address from this script, if it's in the required form.
@param forcePayToPubKey
If true, allow payToPubKey to be casted to the corresponding address. This is useful if you prefer
showing addresses rather than pubkeys. | [
"Gets",
"the",
"destination",
"address",
"from",
"this",
"script",
"if",
"it",
"s",
"in",
"the",
"required",
"form",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/Script.java#L301-L312 |
23,386 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/Script.java | Script.getScriptSigWithSignature | public Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index) {
int sigsPrefixCount = 0;
int sigsSuffixCount = 0;
if (ScriptPattern.isP2SH(this)) {
sigsPrefixCount = 1; // OP_0 <sig>* <redeemScript>
sigsSuffixCount = 1;
} else if (ScriptPattern.isSentToMultisig(this)) {
sigsPrefixCount = 1; // OP_0 <sig>*
} else if (ScriptPattern.isP2PKH(this)) {
sigsSuffixCount = 1; // <sig> <pubkey>
}
return ScriptBuilder.updateScriptWithSignature(scriptSig, sigBytes, index, sigsPrefixCount, sigsSuffixCount);
} | java | public Script getScriptSigWithSignature(Script scriptSig, byte[] sigBytes, int index) {
int sigsPrefixCount = 0;
int sigsSuffixCount = 0;
if (ScriptPattern.isP2SH(this)) {
sigsPrefixCount = 1; // OP_0 <sig>* <redeemScript>
sigsSuffixCount = 1;
} else if (ScriptPattern.isSentToMultisig(this)) {
sigsPrefixCount = 1; // OP_0 <sig>*
} else if (ScriptPattern.isP2PKH(this)) {
sigsSuffixCount = 1; // <sig> <pubkey>
}
return ScriptBuilder.updateScriptWithSignature(scriptSig, sigBytes, index, sigsPrefixCount, sigsSuffixCount);
} | [
"public",
"Script",
"getScriptSigWithSignature",
"(",
"Script",
"scriptSig",
",",
"byte",
"[",
"]",
"sigBytes",
",",
"int",
"index",
")",
"{",
"int",
"sigsPrefixCount",
"=",
"0",
";",
"int",
"sigsSuffixCount",
"=",
"0",
";",
"if",
"(",
"ScriptPattern",
".",
"isP2SH",
"(",
"this",
")",
")",
"{",
"sigsPrefixCount",
"=",
"1",
";",
"// OP_0 <sig>* <redeemScript>",
"sigsSuffixCount",
"=",
"1",
";",
"}",
"else",
"if",
"(",
"ScriptPattern",
".",
"isSentToMultisig",
"(",
"this",
")",
")",
"{",
"sigsPrefixCount",
"=",
"1",
";",
"// OP_0 <sig>*",
"}",
"else",
"if",
"(",
"ScriptPattern",
".",
"isP2PKH",
"(",
"this",
")",
")",
"{",
"sigsSuffixCount",
"=",
"1",
";",
"// <sig> <pubkey>",
"}",
"return",
"ScriptBuilder",
".",
"updateScriptWithSignature",
"(",
"scriptSig",
",",
"sigBytes",
",",
"index",
",",
"sigsPrefixCount",
",",
"sigsSuffixCount",
")",
";",
"}"
] | Returns a copy of the given scriptSig with the signature inserted in the given position. | [
"Returns",
"a",
"copy",
"of",
"the",
"given",
"scriptSig",
"with",
"the",
"signature",
"inserted",
"in",
"the",
"given",
"position",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/Script.java#L419-L431 |
23,387 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/Script.java | Script.getSigInsertionIndex | public int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey) {
// Iterate over existing signatures, skipping the initial OP_0, the final redeem script
// and any placeholder OP_0 sigs.
List<ScriptChunk> existingChunks = chunks.subList(1, chunks.size() - 1);
ScriptChunk redeemScriptChunk = chunks.get(chunks.size() - 1);
checkNotNull(redeemScriptChunk.data);
Script redeemScript = new Script(redeemScriptChunk.data);
int sigCount = 0;
int myIndex = redeemScript.findKeyInRedeem(signingKey);
for (ScriptChunk chunk : existingChunks) {
if (chunk.opcode == OP_0) {
// OP_0, skip
} else {
checkNotNull(chunk.data);
try {
if (myIndex < redeemScript.findSigInRedeem(chunk.data, hash))
return sigCount;
} catch (SignatureDecodeException e) {
// ignore
}
sigCount++;
}
}
return sigCount;
} | java | public int getSigInsertionIndex(Sha256Hash hash, ECKey signingKey) {
// Iterate over existing signatures, skipping the initial OP_0, the final redeem script
// and any placeholder OP_0 sigs.
List<ScriptChunk> existingChunks = chunks.subList(1, chunks.size() - 1);
ScriptChunk redeemScriptChunk = chunks.get(chunks.size() - 1);
checkNotNull(redeemScriptChunk.data);
Script redeemScript = new Script(redeemScriptChunk.data);
int sigCount = 0;
int myIndex = redeemScript.findKeyInRedeem(signingKey);
for (ScriptChunk chunk : existingChunks) {
if (chunk.opcode == OP_0) {
// OP_0, skip
} else {
checkNotNull(chunk.data);
try {
if (myIndex < redeemScript.findSigInRedeem(chunk.data, hash))
return sigCount;
} catch (SignatureDecodeException e) {
// ignore
}
sigCount++;
}
}
return sigCount;
} | [
"public",
"int",
"getSigInsertionIndex",
"(",
"Sha256Hash",
"hash",
",",
"ECKey",
"signingKey",
")",
"{",
"// Iterate over existing signatures, skipping the initial OP_0, the final redeem script",
"// and any placeholder OP_0 sigs.",
"List",
"<",
"ScriptChunk",
">",
"existingChunks",
"=",
"chunks",
".",
"subList",
"(",
"1",
",",
"chunks",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"ScriptChunk",
"redeemScriptChunk",
"=",
"chunks",
".",
"get",
"(",
"chunks",
".",
"size",
"(",
")",
"-",
"1",
")",
";",
"checkNotNull",
"(",
"redeemScriptChunk",
".",
"data",
")",
";",
"Script",
"redeemScript",
"=",
"new",
"Script",
"(",
"redeemScriptChunk",
".",
"data",
")",
";",
"int",
"sigCount",
"=",
"0",
";",
"int",
"myIndex",
"=",
"redeemScript",
".",
"findKeyInRedeem",
"(",
"signingKey",
")",
";",
"for",
"(",
"ScriptChunk",
"chunk",
":",
"existingChunks",
")",
"{",
"if",
"(",
"chunk",
".",
"opcode",
"==",
"OP_0",
")",
"{",
"// OP_0, skip",
"}",
"else",
"{",
"checkNotNull",
"(",
"chunk",
".",
"data",
")",
";",
"try",
"{",
"if",
"(",
"myIndex",
"<",
"redeemScript",
".",
"findSigInRedeem",
"(",
"chunk",
".",
"data",
",",
"hash",
")",
")",
"return",
"sigCount",
";",
"}",
"catch",
"(",
"SignatureDecodeException",
"e",
")",
"{",
"// ignore",
"}",
"sigCount",
"++",
";",
"}",
"}",
"return",
"sigCount",
";",
"}"
] | Returns the index where a signature by the key should be inserted. Only applicable to
a P2SH scriptSig. | [
"Returns",
"the",
"index",
"where",
"a",
"signature",
"by",
"the",
"key",
"should",
"be",
"inserted",
".",
"Only",
"applicable",
"to",
"a",
"P2SH",
"scriptSig",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/Script.java#L438-L463 |
23,388 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/Script.java | Script.getPubKeys | public List<ECKey> getPubKeys() {
if (!ScriptPattern.isSentToMultisig(this))
throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Only usable for multisig scripts.");
ArrayList<ECKey> result = Lists.newArrayList();
int numKeys = Script.decodeFromOpN(chunks.get(chunks.size() - 2).opcode);
for (int i = 0 ; i < numKeys ; i++)
result.add(ECKey.fromPublicOnly(chunks.get(1 + i).data));
return result;
} | java | public List<ECKey> getPubKeys() {
if (!ScriptPattern.isSentToMultisig(this))
throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Only usable for multisig scripts.");
ArrayList<ECKey> result = Lists.newArrayList();
int numKeys = Script.decodeFromOpN(chunks.get(chunks.size() - 2).opcode);
for (int i = 0 ; i < numKeys ; i++)
result.add(ECKey.fromPublicOnly(chunks.get(1 + i).data));
return result;
} | [
"public",
"List",
"<",
"ECKey",
">",
"getPubKeys",
"(",
")",
"{",
"if",
"(",
"!",
"ScriptPattern",
".",
"isSentToMultisig",
"(",
"this",
")",
")",
"throw",
"new",
"ScriptException",
"(",
"ScriptError",
".",
"SCRIPT_ERR_UNKNOWN_ERROR",
",",
"\"Only usable for multisig scripts.\"",
")",
";",
"ArrayList",
"<",
"ECKey",
">",
"result",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"int",
"numKeys",
"=",
"Script",
".",
"decodeFromOpN",
"(",
"chunks",
".",
"get",
"(",
"chunks",
".",
"size",
"(",
")",
"-",
"2",
")",
".",
"opcode",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numKeys",
";",
"i",
"++",
")",
"result",
".",
"(",
"ECKey",
".",
"fromPublicOnly",
"(",
"chunks",
".",
"get",
"(",
"1",
"+",
"i",
")",
".",
"data",
")",
")",
";",
"return",
"result",
";",
"}"
] | Returns a list of the keys required by this script, assuming a multi-sig script.
@throws ScriptException if the script type is not understood or is pay to address or is P2SH (run this method on the "Redeem script" instead). | [
"Returns",
"a",
"list",
"of",
"the",
"keys",
"required",
"by",
"this",
"script",
"assuming",
"a",
"multi",
"-",
"sig",
"script",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/Script.java#L482-L491 |
23,389 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/Script.java | Script.getP2SHSigOpCount | public static long getP2SHSigOpCount(byte[] scriptSig) throws ScriptException {
Script script = new Script();
try {
script.parse(scriptSig);
} catch (ScriptException e) {
// Ignore errors and count up to the parse-able length
}
for (int i = script.chunks.size() - 1; i >= 0; i--)
if (!script.chunks.get(i).isOpCode()) {
Script subScript = new Script();
subScript.parse(script.chunks.get(i).data);
return getSigOpCount(subScript.chunks, true);
}
return 0;
} | java | public static long getP2SHSigOpCount(byte[] scriptSig) throws ScriptException {
Script script = new Script();
try {
script.parse(scriptSig);
} catch (ScriptException e) {
// Ignore errors and count up to the parse-able length
}
for (int i = script.chunks.size() - 1; i >= 0; i--)
if (!script.chunks.get(i).isOpCode()) {
Script subScript = new Script();
subScript.parse(script.chunks.get(i).data);
return getSigOpCount(subScript.chunks, true);
}
return 0;
} | [
"public",
"static",
"long",
"getP2SHSigOpCount",
"(",
"byte",
"[",
"]",
"scriptSig",
")",
"throws",
"ScriptException",
"{",
"Script",
"script",
"=",
"new",
"Script",
"(",
")",
";",
"try",
"{",
"script",
".",
"parse",
"(",
"scriptSig",
")",
";",
"}",
"catch",
"(",
"ScriptException",
"e",
")",
"{",
"// Ignore errors and count up to the parse-able length",
"}",
"for",
"(",
"int",
"i",
"=",
"script",
".",
"chunks",
".",
"size",
"(",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"if",
"(",
"!",
"script",
".",
"chunks",
".",
"get",
"(",
"i",
")",
".",
"isOpCode",
"(",
")",
")",
"{",
"Script",
"subScript",
"=",
"new",
"Script",
"(",
")",
";",
"subScript",
".",
"parse",
"(",
"script",
".",
"chunks",
".",
"get",
"(",
"i",
")",
".",
"data",
")",
";",
"return",
"getSigOpCount",
"(",
"subScript",
".",
"chunks",
",",
"true",
")",
";",
"}",
"return",
"0",
";",
"}"
] | Gets the count of P2SH Sig Ops in the Script scriptSig | [
"Gets",
"the",
"count",
"of",
"P2SH",
"Sig",
"Ops",
"in",
"the",
"Script",
"scriptSig"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/Script.java#L573-L587 |
23,390 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/Script.java | Script.getNumberOfSignaturesRequiredToSpend | public int getNumberOfSignaturesRequiredToSpend() {
if (ScriptPattern.isSentToMultisig(this)) {
// for N of M CHECKMULTISIG script we will need N signatures to spend
ScriptChunk nChunk = chunks.get(0);
return Script.decodeFromOpN(nChunk.opcode);
} else if (ScriptPattern.isP2PKH(this) || ScriptPattern.isP2PK(this)) {
// P2PKH and P2PK require single sig
return 1;
} else if (ScriptPattern.isP2SH(this)) {
throw new IllegalStateException("For P2SH number of signatures depends on redeem script");
} else {
throw new IllegalStateException("Unsupported script type");
}
} | java | public int getNumberOfSignaturesRequiredToSpend() {
if (ScriptPattern.isSentToMultisig(this)) {
// for N of M CHECKMULTISIG script we will need N signatures to spend
ScriptChunk nChunk = chunks.get(0);
return Script.decodeFromOpN(nChunk.opcode);
} else if (ScriptPattern.isP2PKH(this) || ScriptPattern.isP2PK(this)) {
// P2PKH and P2PK require single sig
return 1;
} else if (ScriptPattern.isP2SH(this)) {
throw new IllegalStateException("For P2SH number of signatures depends on redeem script");
} else {
throw new IllegalStateException("Unsupported script type");
}
} | [
"public",
"int",
"getNumberOfSignaturesRequiredToSpend",
"(",
")",
"{",
"if",
"(",
"ScriptPattern",
".",
"isSentToMultisig",
"(",
"this",
")",
")",
"{",
"// for N of M CHECKMULTISIG script we will need N signatures to spend",
"ScriptChunk",
"nChunk",
"=",
"chunks",
".",
"get",
"(",
"0",
")",
";",
"return",
"Script",
".",
"decodeFromOpN",
"(",
"nChunk",
".",
"opcode",
")",
";",
"}",
"else",
"if",
"(",
"ScriptPattern",
".",
"isP2PKH",
"(",
"this",
")",
"||",
"ScriptPattern",
".",
"isP2PK",
"(",
"this",
")",
")",
"{",
"// P2PKH and P2PK require single sig",
"return",
"1",
";",
"}",
"else",
"if",
"(",
"ScriptPattern",
".",
"isP2SH",
"(",
"this",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"For P2SH number of signatures depends on redeem script\"",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Unsupported script type\"",
")",
";",
"}",
"}"
] | Returns number of signatures required to satisfy this script. | [
"Returns",
"number",
"of",
"signatures",
"required",
"to",
"satisfy",
"this",
"script",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/Script.java#L592-L605 |
23,391 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/Script.java | Script.removeAllInstancesOf | public static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove) {
// We usually don't end up removing anything
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(inputScript.length);
int cursor = 0;
while (cursor < inputScript.length) {
boolean skip = equalsRange(inputScript, cursor, chunkToRemove);
int opcode = inputScript[cursor++] & 0xFF;
int additionalBytes = 0;
if (opcode >= 0 && opcode < OP_PUSHDATA1) {
additionalBytes = opcode;
} else if (opcode == OP_PUSHDATA1) {
additionalBytes = (0xFF & inputScript[cursor]) + 1;
} else if (opcode == OP_PUSHDATA2) {
additionalBytes = Utils.readUint16(inputScript, cursor) + 2;
} else if (opcode == OP_PUSHDATA4) {
additionalBytes = (int) Utils.readUint32(inputScript, cursor) + 4;
}
if (!skip) {
try {
bos.write(opcode);
bos.write(Arrays.copyOfRange(inputScript, cursor, cursor + additionalBytes));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
cursor += additionalBytes;
}
return bos.toByteArray();
} | java | public static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove) {
// We usually don't end up removing anything
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(inputScript.length);
int cursor = 0;
while (cursor < inputScript.length) {
boolean skip = equalsRange(inputScript, cursor, chunkToRemove);
int opcode = inputScript[cursor++] & 0xFF;
int additionalBytes = 0;
if (opcode >= 0 && opcode < OP_PUSHDATA1) {
additionalBytes = opcode;
} else if (opcode == OP_PUSHDATA1) {
additionalBytes = (0xFF & inputScript[cursor]) + 1;
} else if (opcode == OP_PUSHDATA2) {
additionalBytes = Utils.readUint16(inputScript, cursor) + 2;
} else if (opcode == OP_PUSHDATA4) {
additionalBytes = (int) Utils.readUint32(inputScript, cursor) + 4;
}
if (!skip) {
try {
bos.write(opcode);
bos.write(Arrays.copyOfRange(inputScript, cursor, cursor + additionalBytes));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
cursor += additionalBytes;
}
return bos.toByteArray();
} | [
"public",
"static",
"byte",
"[",
"]",
"removeAllInstancesOf",
"(",
"byte",
"[",
"]",
"inputScript",
",",
"byte",
"[",
"]",
"chunkToRemove",
")",
"{",
"// We usually don't end up removing anything",
"UnsafeByteArrayOutputStream",
"bos",
"=",
"new",
"UnsafeByteArrayOutputStream",
"(",
"inputScript",
".",
"length",
")",
";",
"int",
"cursor",
"=",
"0",
";",
"while",
"(",
"cursor",
"<",
"inputScript",
".",
"length",
")",
"{",
"boolean",
"skip",
"=",
"equalsRange",
"(",
"inputScript",
",",
"cursor",
",",
"chunkToRemove",
")",
";",
"int",
"opcode",
"=",
"inputScript",
"[",
"cursor",
"++",
"]",
"&",
"0xFF",
";",
"int",
"additionalBytes",
"=",
"0",
";",
"if",
"(",
"opcode",
">=",
"0",
"&&",
"opcode",
"<",
"OP_PUSHDATA1",
")",
"{",
"additionalBytes",
"=",
"opcode",
";",
"}",
"else",
"if",
"(",
"opcode",
"==",
"OP_PUSHDATA1",
")",
"{",
"additionalBytes",
"=",
"(",
"0xFF",
"&",
"inputScript",
"[",
"cursor",
"]",
")",
"+",
"1",
";",
"}",
"else",
"if",
"(",
"opcode",
"==",
"OP_PUSHDATA2",
")",
"{",
"additionalBytes",
"=",
"Utils",
".",
"readUint16",
"(",
"inputScript",
",",
"cursor",
")",
"+",
"2",
";",
"}",
"else",
"if",
"(",
"opcode",
"==",
"OP_PUSHDATA4",
")",
"{",
"additionalBytes",
"=",
"(",
"int",
")",
"Utils",
".",
"readUint32",
"(",
"inputScript",
",",
"cursor",
")",
"+",
"4",
";",
"}",
"if",
"(",
"!",
"skip",
")",
"{",
"try",
"{",
"bos",
".",
"write",
"(",
"opcode",
")",
";",
"bos",
".",
"write",
"(",
"Arrays",
".",
"copyOfRange",
"(",
"inputScript",
",",
"cursor",
",",
"cursor",
"+",
"additionalBytes",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"cursor",
"+=",
"additionalBytes",
";",
"}",
"return",
"bos",
".",
"toByteArray",
"(",
")",
";",
"}"
] | Returns the script bytes of inputScript with all instances of the specified script object removed | [
"Returns",
"the",
"script",
"bytes",
"of",
"inputScript",
"with",
"all",
"instances",
"of",
"the",
"specified",
"script",
"object",
"removed"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/Script.java#L666-L696 |
23,392 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/Script.java | Script.executeCheckLockTimeVerify | private static void executeCheckLockTimeVerify(Transaction txContainingThis, int index, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags) throws ScriptException {
if (stack.size() < 1)
throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_CHECKLOCKTIMEVERIFY on a stack with size < 1");
// Thus as a special case we tell CScriptNum to accept up
// to 5-byte bignums to avoid year 2038 issue.
final BigInteger nLockTime = castToBigInteger(stack.getLast(), 5, verifyFlags.contains(VerifyFlag.MINIMALDATA));
if (nLockTime.compareTo(BigInteger.ZERO) < 0)
throw new ScriptException(ScriptError.SCRIPT_ERR_NEGATIVE_LOCKTIME, "Negative locktime");
// There are two kinds of nLockTime, need to ensure we're comparing apples-to-apples
if (!(
((txContainingThis.getLockTime() < Transaction.LOCKTIME_THRESHOLD) && (nLockTime.compareTo(Transaction.LOCKTIME_THRESHOLD_BIG)) < 0) ||
((txContainingThis.getLockTime() >= Transaction.LOCKTIME_THRESHOLD) && (nLockTime.compareTo(Transaction.LOCKTIME_THRESHOLD_BIG)) >= 0))
)
throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Locktime requirement type mismatch");
// Now that we know we're comparing apples-to-apples, the
// comparison is a simple numeric one.
if (nLockTime.compareTo(BigInteger.valueOf(txContainingThis.getLockTime())) > 0)
throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Locktime requirement not satisfied");
// Finally the nLockTime feature can be disabled and thus
// CHECKLOCKTIMEVERIFY bypassed if every txin has been
// finalized by setting nSequence to maxint. The
// transaction would be allowed into the blockchain, making
// the opcode ineffective.
//
// Testing if this vin is not final is sufficient to
// prevent this condition. Alternatively we could test all
// inputs, but testing just this input minimizes the data
// required to prove correct CHECKLOCKTIMEVERIFY execution.
if (!txContainingThis.getInput(index).hasSequence())
throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Transaction contains a final transaction input for a CHECKLOCKTIMEVERIFY script.");
} | java | private static void executeCheckLockTimeVerify(Transaction txContainingThis, int index, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags) throws ScriptException {
if (stack.size() < 1)
throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_CHECKLOCKTIMEVERIFY on a stack with size < 1");
// Thus as a special case we tell CScriptNum to accept up
// to 5-byte bignums to avoid year 2038 issue.
final BigInteger nLockTime = castToBigInteger(stack.getLast(), 5, verifyFlags.contains(VerifyFlag.MINIMALDATA));
if (nLockTime.compareTo(BigInteger.ZERO) < 0)
throw new ScriptException(ScriptError.SCRIPT_ERR_NEGATIVE_LOCKTIME, "Negative locktime");
// There are two kinds of nLockTime, need to ensure we're comparing apples-to-apples
if (!(
((txContainingThis.getLockTime() < Transaction.LOCKTIME_THRESHOLD) && (nLockTime.compareTo(Transaction.LOCKTIME_THRESHOLD_BIG)) < 0) ||
((txContainingThis.getLockTime() >= Transaction.LOCKTIME_THRESHOLD) && (nLockTime.compareTo(Transaction.LOCKTIME_THRESHOLD_BIG)) >= 0))
)
throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Locktime requirement type mismatch");
// Now that we know we're comparing apples-to-apples, the
// comparison is a simple numeric one.
if (nLockTime.compareTo(BigInteger.valueOf(txContainingThis.getLockTime())) > 0)
throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Locktime requirement not satisfied");
// Finally the nLockTime feature can be disabled and thus
// CHECKLOCKTIMEVERIFY bypassed if every txin has been
// finalized by setting nSequence to maxint. The
// transaction would be allowed into the blockchain, making
// the opcode ineffective.
//
// Testing if this vin is not final is sufficient to
// prevent this condition. Alternatively we could test all
// inputs, but testing just this input minimizes the data
// required to prove correct CHECKLOCKTIMEVERIFY execution.
if (!txContainingThis.getInput(index).hasSequence())
throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Transaction contains a final transaction input for a CHECKLOCKTIMEVERIFY script.");
} | [
"private",
"static",
"void",
"executeCheckLockTimeVerify",
"(",
"Transaction",
"txContainingThis",
",",
"int",
"index",
",",
"LinkedList",
"<",
"byte",
"[",
"]",
">",
"stack",
",",
"Set",
"<",
"VerifyFlag",
">",
"verifyFlags",
")",
"throws",
"ScriptException",
"{",
"if",
"(",
"stack",
".",
"size",
"(",
")",
"<",
"1",
")",
"throw",
"new",
"ScriptException",
"(",
"ScriptError",
".",
"SCRIPT_ERR_INVALID_STACK_OPERATION",
",",
"\"Attempted OP_CHECKLOCKTIMEVERIFY on a stack with size < 1\"",
")",
";",
"// Thus as a special case we tell CScriptNum to accept up",
"// to 5-byte bignums to avoid year 2038 issue.",
"final",
"BigInteger",
"nLockTime",
"=",
"castToBigInteger",
"(",
"stack",
".",
"getLast",
"(",
")",
",",
"5",
",",
"verifyFlags",
".",
"contains",
"(",
"VerifyFlag",
".",
"MINIMALDATA",
")",
")",
";",
"if",
"(",
"nLockTime",
".",
"compareTo",
"(",
"BigInteger",
".",
"ZERO",
")",
"<",
"0",
")",
"throw",
"new",
"ScriptException",
"(",
"ScriptError",
".",
"SCRIPT_ERR_NEGATIVE_LOCKTIME",
",",
"\"Negative locktime\"",
")",
";",
"// There are two kinds of nLockTime, need to ensure we're comparing apples-to-apples",
"if",
"(",
"!",
"(",
"(",
"(",
"txContainingThis",
".",
"getLockTime",
"(",
")",
"<",
"Transaction",
".",
"LOCKTIME_THRESHOLD",
")",
"&&",
"(",
"nLockTime",
".",
"compareTo",
"(",
"Transaction",
".",
"LOCKTIME_THRESHOLD_BIG",
")",
")",
"<",
"0",
")",
"||",
"(",
"(",
"txContainingThis",
".",
"getLockTime",
"(",
")",
">=",
"Transaction",
".",
"LOCKTIME_THRESHOLD",
")",
"&&",
"(",
"nLockTime",
".",
"compareTo",
"(",
"Transaction",
".",
"LOCKTIME_THRESHOLD_BIG",
")",
")",
">=",
"0",
")",
")",
")",
"throw",
"new",
"ScriptException",
"(",
"ScriptError",
".",
"SCRIPT_ERR_UNSATISFIED_LOCKTIME",
",",
"\"Locktime requirement type mismatch\"",
")",
";",
"// Now that we know we're comparing apples-to-apples, the",
"// comparison is a simple numeric one.",
"if",
"(",
"nLockTime",
".",
"compareTo",
"(",
"BigInteger",
".",
"valueOf",
"(",
"txContainingThis",
".",
"getLockTime",
"(",
")",
")",
")",
">",
"0",
")",
"throw",
"new",
"ScriptException",
"(",
"ScriptError",
".",
"SCRIPT_ERR_UNSATISFIED_LOCKTIME",
",",
"\"Locktime requirement not satisfied\"",
")",
";",
"// Finally the nLockTime feature can be disabled and thus",
"// CHECKLOCKTIMEVERIFY bypassed if every txin has been",
"// finalized by setting nSequence to maxint. The",
"// transaction would be allowed into the blockchain, making",
"// the opcode ineffective.",
"//",
"// Testing if this vin is not final is sufficient to",
"// prevent this condition. Alternatively we could test all",
"// inputs, but testing just this input minimizes the data",
"// required to prove correct CHECKLOCKTIMEVERIFY execution.",
"if",
"(",
"!",
"txContainingThis",
".",
"getInput",
"(",
"index",
")",
".",
"hasSequence",
"(",
")",
")",
"throw",
"new",
"ScriptException",
"(",
"ScriptError",
".",
"SCRIPT_ERR_UNSATISFIED_LOCKTIME",
",",
"\"Transaction contains a final transaction input for a CHECKLOCKTIMEVERIFY script.\"",
")",
";",
"}"
] | This is more or less a direct translation of the code in Bitcoin Core | [
"This",
"is",
"more",
"or",
"less",
"a",
"direct",
"translation",
"of",
"the",
"code",
"in",
"Bitcoin",
"Core"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/Script.java#L1305-L1340 |
23,393 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/script/ScriptOpCodes.java | ScriptOpCodes.getOpCode | public static int getOpCode(String opCodeName) {
if (opCodeNameMap.containsKey(opCodeName))
return opCodeNameMap.get(opCodeName);
return OP_INVALIDOPCODE;
} | java | public static int getOpCode(String opCodeName) {
if (opCodeNameMap.containsKey(opCodeName))
return opCodeNameMap.get(opCodeName);
return OP_INVALIDOPCODE;
} | [
"public",
"static",
"int",
"getOpCode",
"(",
"String",
"opCodeName",
")",
"{",
"if",
"(",
"opCodeNameMap",
".",
"containsKey",
"(",
"opCodeName",
")",
")",
"return",
"opCodeNameMap",
".",
"get",
"(",
"opCodeName",
")",
";",
"return",
"OP_INVALIDOPCODE",
";",
"}"
] | Converts the given OpCodeName into an int | [
"Converts",
"the",
"given",
"OpCodeName",
"into",
"an",
"int"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/script/ScriptOpCodes.java#L418-L423 |
23,394 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/RedeemData.java | RedeemData.of | public static RedeemData of(ECKey key, Script redeemScript) {
checkArgument(ScriptPattern.isP2PKH(redeemScript)
|| ScriptPattern.isP2WPKH(redeemScript) || ScriptPattern.isP2PK(redeemScript));
return key != null ? new RedeemData(Collections.singletonList(key), redeemScript) : null;
} | java | public static RedeemData of(ECKey key, Script redeemScript) {
checkArgument(ScriptPattern.isP2PKH(redeemScript)
|| ScriptPattern.isP2WPKH(redeemScript) || ScriptPattern.isP2PK(redeemScript));
return key != null ? new RedeemData(Collections.singletonList(key), redeemScript) : null;
} | [
"public",
"static",
"RedeemData",
"of",
"(",
"ECKey",
"key",
",",
"Script",
"redeemScript",
")",
"{",
"checkArgument",
"(",
"ScriptPattern",
".",
"isP2PKH",
"(",
"redeemScript",
")",
"||",
"ScriptPattern",
".",
"isP2WPKH",
"(",
"redeemScript",
")",
"||",
"ScriptPattern",
".",
"isP2PK",
"(",
"redeemScript",
")",
")",
";",
"return",
"key",
"!=",
"null",
"?",
"new",
"RedeemData",
"(",
"Collections",
".",
"singletonList",
"(",
"key",
")",
",",
"redeemScript",
")",
":",
"null",
";",
"}"
] | Creates RedeemData for P2PKH, P2WPKH or P2PK input. Provided key is a single private key needed
to spend such inputs. | [
"Creates",
"RedeemData",
"for",
"P2PKH",
"P2WPKH",
"or",
"P2PK",
"input",
".",
"Provided",
"key",
"is",
"a",
"single",
"private",
"key",
"needed",
"to",
"spend",
"such",
"inputs",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/RedeemData.java#L59-L63 |
23,395 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelClientState.java | PaymentChannelClientState.isSettlementTransaction | public synchronized boolean isSettlementTransaction(Transaction tx) {
try {
tx.verify();
tx.getInput(0).verify(getContractInternal().getOutput(0));
return true;
} catch (VerificationException e) {
return false;
}
} | java | public synchronized boolean isSettlementTransaction(Transaction tx) {
try {
tx.verify();
tx.getInput(0).verify(getContractInternal().getOutput(0));
return true;
} catch (VerificationException e) {
return false;
}
} | [
"public",
"synchronized",
"boolean",
"isSettlementTransaction",
"(",
"Transaction",
"tx",
")",
"{",
"try",
"{",
"tx",
".",
"verify",
"(",
")",
";",
"tx",
".",
"getInput",
"(",
"0",
")",
".",
"verify",
"(",
"getContractInternal",
"(",
")",
".",
"getOutput",
"(",
"0",
")",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"VerificationException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | Returns true if the tx is a valid settlement transaction. | [
"Returns",
"true",
"if",
"the",
"tx",
"is",
"a",
"valid",
"settlement",
"transaction",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelClientState.java#L119-L127 |
23,396 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelClientState.java | PaymentChannelClientState.fakeSave | @VisibleForTesting synchronized void fakeSave() {
try {
wallet.commitTx(getContractInternal());
} catch (VerificationException e) {
throw new RuntimeException(e); // We created it
}
stateMachine.transition(State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER);
} | java | @VisibleForTesting synchronized void fakeSave() {
try {
wallet.commitTx(getContractInternal());
} catch (VerificationException e) {
throw new RuntimeException(e); // We created it
}
stateMachine.transition(State.PROVIDE_MULTISIG_CONTRACT_TO_SERVER);
} | [
"@",
"VisibleForTesting",
"synchronized",
"void",
"fakeSave",
"(",
")",
"{",
"try",
"{",
"wallet",
".",
"commitTx",
"(",
"getContractInternal",
"(",
")",
")",
";",
"}",
"catch",
"(",
"VerificationException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"// We created it",
"}",
"stateMachine",
".",
"transition",
"(",
"State",
".",
"PROVIDE_MULTISIG_CONTRACT_TO_SERVER",
")",
";",
"}"
] | Skips saving state in the wallet for testing | [
"Skips",
"saving",
"state",
"in",
"the",
"wallet",
"for",
"testing"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelClientState.java#L347-L354 |
23,397 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/SegwitAddress.java | SegwitAddress.encode | private static byte[] encode(int witnessVersion, byte[] witnessProgram) throws AddressFormatException {
byte[] convertedProgram = convertBits(witnessProgram, 0, witnessProgram.length, 8, 5, true);
byte[] bytes = new byte[1 + convertedProgram.length];
bytes[0] = (byte) (Script.encodeToOpN(witnessVersion) & 0xff);
System.arraycopy(convertedProgram, 0, bytes, 1, convertedProgram.length);
return bytes;
} | java | private static byte[] encode(int witnessVersion, byte[] witnessProgram) throws AddressFormatException {
byte[] convertedProgram = convertBits(witnessProgram, 0, witnessProgram.length, 8, 5, true);
byte[] bytes = new byte[1 + convertedProgram.length];
bytes[0] = (byte) (Script.encodeToOpN(witnessVersion) & 0xff);
System.arraycopy(convertedProgram, 0, bytes, 1, convertedProgram.length);
return bytes;
} | [
"private",
"static",
"byte",
"[",
"]",
"encode",
"(",
"int",
"witnessVersion",
",",
"byte",
"[",
"]",
"witnessProgram",
")",
"throws",
"AddressFormatException",
"{",
"byte",
"[",
"]",
"convertedProgram",
"=",
"convertBits",
"(",
"witnessProgram",
",",
"0",
",",
"witnessProgram",
".",
"length",
",",
"8",
",",
"5",
",",
"true",
")",
";",
"byte",
"[",
"]",
"bytes",
"=",
"new",
"byte",
"[",
"1",
"+",
"convertedProgram",
".",
"length",
"]",
";",
"bytes",
"[",
"0",
"]",
"=",
"(",
"byte",
")",
"(",
"Script",
".",
"encodeToOpN",
"(",
"witnessVersion",
")",
"&",
"0xff",
")",
";",
"System",
".",
"arraycopy",
"(",
"convertedProgram",
",",
"0",
",",
"bytes",
",",
"1",
",",
"convertedProgram",
".",
"length",
")",
";",
"return",
"bytes",
";",
"}"
] | Helper for the above constructor. | [
"Helper",
"for",
"the",
"above",
"constructor",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/SegwitAddress.java#L71-L77 |
23,398 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/core/SegwitAddress.java | SegwitAddress.convertBits | private static byte[] convertBits(final byte[] in, final int inStart, final int inLen, final int fromBits,
final int toBits, final boolean pad) throws AddressFormatException {
int acc = 0;
int bits = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream(64);
final int maxv = (1 << toBits) - 1;
final int max_acc = (1 << (fromBits + toBits - 1)) - 1;
for (int i = 0; i < inLen; i++) {
int value = in[i + inStart] & 0xff;
if ((value >>> fromBits) != 0) {
throw new AddressFormatException(
String.format("Input value '%X' exceeds '%d' bit size", value, fromBits));
}
acc = ((acc << fromBits) | value) & max_acc;
bits += fromBits;
while (bits >= toBits) {
bits -= toBits;
out.write((acc >>> bits) & maxv);
}
}
if (pad) {
if (bits > 0)
out.write((acc << (toBits - bits)) & maxv);
} else if (bits >= fromBits || ((acc << (toBits - bits)) & maxv) != 0) {
throw new AddressFormatException("Could not convert bits, invalid padding");
}
return out.toByteArray();
} | java | private static byte[] convertBits(final byte[] in, final int inStart, final int inLen, final int fromBits,
final int toBits, final boolean pad) throws AddressFormatException {
int acc = 0;
int bits = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream(64);
final int maxv = (1 << toBits) - 1;
final int max_acc = (1 << (fromBits + toBits - 1)) - 1;
for (int i = 0; i < inLen; i++) {
int value = in[i + inStart] & 0xff;
if ((value >>> fromBits) != 0) {
throw new AddressFormatException(
String.format("Input value '%X' exceeds '%d' bit size", value, fromBits));
}
acc = ((acc << fromBits) | value) & max_acc;
bits += fromBits;
while (bits >= toBits) {
bits -= toBits;
out.write((acc >>> bits) & maxv);
}
}
if (pad) {
if (bits > 0)
out.write((acc << (toBits - bits)) & maxv);
} else if (bits >= fromBits || ((acc << (toBits - bits)) & maxv) != 0) {
throw new AddressFormatException("Could not convert bits, invalid padding");
}
return out.toByteArray();
} | [
"private",
"static",
"byte",
"[",
"]",
"convertBits",
"(",
"final",
"byte",
"[",
"]",
"in",
",",
"final",
"int",
"inStart",
",",
"final",
"int",
"inLen",
",",
"final",
"int",
"fromBits",
",",
"final",
"int",
"toBits",
",",
"final",
"boolean",
"pad",
")",
"throws",
"AddressFormatException",
"{",
"int",
"acc",
"=",
"0",
";",
"int",
"bits",
"=",
"0",
";",
"ByteArrayOutputStream",
"out",
"=",
"new",
"ByteArrayOutputStream",
"(",
"64",
")",
";",
"final",
"int",
"maxv",
"=",
"(",
"1",
"<<",
"toBits",
")",
"-",
"1",
";",
"final",
"int",
"max_acc",
"=",
"(",
"1",
"<<",
"(",
"fromBits",
"+",
"toBits",
"-",
"1",
")",
")",
"-",
"1",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"inLen",
";",
"i",
"++",
")",
"{",
"int",
"value",
"=",
"in",
"[",
"i",
"+",
"inStart",
"]",
"&",
"0xff",
";",
"if",
"(",
"(",
"value",
">>>",
"fromBits",
")",
"!=",
"0",
")",
"{",
"throw",
"new",
"AddressFormatException",
"(",
"String",
".",
"format",
"(",
"\"Input value '%X' exceeds '%d' bit size\"",
",",
"value",
",",
"fromBits",
")",
")",
";",
"}",
"acc",
"=",
"(",
"(",
"acc",
"<<",
"fromBits",
")",
"|",
"value",
")",
"&",
"max_acc",
";",
"bits",
"+=",
"fromBits",
";",
"while",
"(",
"bits",
">=",
"toBits",
")",
"{",
"bits",
"-=",
"toBits",
";",
"out",
".",
"write",
"(",
"(",
"acc",
">>>",
"bits",
")",
"&",
"maxv",
")",
";",
"}",
"}",
"if",
"(",
"pad",
")",
"{",
"if",
"(",
"bits",
">",
"0",
")",
"out",
".",
"write",
"(",
"(",
"acc",
"<<",
"(",
"toBits",
"-",
"bits",
")",
")",
"&",
"maxv",
")",
";",
"}",
"else",
"if",
"(",
"bits",
">=",
"fromBits",
"||",
"(",
"(",
"acc",
"<<",
"(",
"toBits",
"-",
"bits",
")",
")",
"&",
"maxv",
")",
"!=",
"0",
")",
"{",
"throw",
"new",
"AddressFormatException",
"(",
"\"Could not convert bits, invalid padding\"",
")",
";",
"}",
"return",
"out",
".",
"toByteArray",
"(",
")",
";",
"}"
] | Helper for re-arranging bits into groups. | [
"Helper",
"for",
"re",
"-",
"arranging",
"bits",
"into",
"groups",
"."
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/core/SegwitAddress.java#L222-L249 |
23,399 | bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelServerState.java | PaymentChannelServerState.makeUnsignedChannelContract | protected synchronized SendRequest makeUnsignedChannelContract(Coin valueToMe) {
Transaction tx = new Transaction(wallet.getParams());
if (!getTotalValue().subtract(valueToMe).equals(Coin.ZERO)) {
tx.addOutput(getTotalValue().subtract(valueToMe), LegacyAddress.fromKey(wallet.getParams(), getClientKey()));
}
tx.addInput(contract.getOutput(0));
return SendRequest.forTx(tx);
} | java | protected synchronized SendRequest makeUnsignedChannelContract(Coin valueToMe) {
Transaction tx = new Transaction(wallet.getParams());
if (!getTotalValue().subtract(valueToMe).equals(Coin.ZERO)) {
tx.addOutput(getTotalValue().subtract(valueToMe), LegacyAddress.fromKey(wallet.getParams(), getClientKey()));
}
tx.addInput(contract.getOutput(0));
return SendRequest.forTx(tx);
} | [
"protected",
"synchronized",
"SendRequest",
"makeUnsignedChannelContract",
"(",
"Coin",
"valueToMe",
")",
"{",
"Transaction",
"tx",
"=",
"new",
"Transaction",
"(",
"wallet",
".",
"getParams",
"(",
")",
")",
";",
"if",
"(",
"!",
"getTotalValue",
"(",
")",
".",
"subtract",
"(",
"valueToMe",
")",
".",
"equals",
"(",
"Coin",
".",
"ZERO",
")",
")",
"{",
"tx",
".",
"addOutput",
"(",
"getTotalValue",
"(",
")",
".",
"subtract",
"(",
"valueToMe",
")",
",",
"LegacyAddress",
".",
"fromKey",
"(",
"wallet",
".",
"getParams",
"(",
")",
",",
"getClientKey",
"(",
")",
")",
")",
";",
"}",
"tx",
".",
"addInput",
"(",
"contract",
".",
"getOutput",
"(",
"0",
")",
")",
";",
"return",
"SendRequest",
".",
"forTx",
"(",
"tx",
")",
";",
"}"
] | Create a payment transaction with valueToMe going back to us | [
"Create",
"a",
"payment",
"transaction",
"with",
"valueToMe",
"going",
"back",
"to",
"us"
] | 9cf13d29315014ed59cf4fc5944e5f227e8df9a6 | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/protocols/channels/PaymentChannelServerState.java#L221-L228 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.