repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/BIP38PrivateKey.java
/* * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import com.google.common.primitives.Bytes; import org.bitcoinj.base.Network; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.base.exceptions.AddressFormatException; import org.bitcoinj.base.Base58; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.base.Sha256Hash; import org.bouncycastle.crypto.generators.SCrypt; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.text.Normalizer; import java.util.Arrays; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Implementation of <a href="https://github.com/bitcoin/bips/blob/master/bip-0038.mediawiki">BIP 38</a> * passphrase-protected private keys. Currently, only decryption is supported. */ public class BIP38PrivateKey extends EncodedPrivateKey { public final boolean ecMultiply; public final boolean compressed; public final boolean hasLotAndSequence; public final byte[] addressHash; public final byte[] content; public static final class BadPassphraseException extends Exception { } /** * Construct a password-protected private key from its Base58 representation. * @param network * The network 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 */ public static BIP38PrivateKey fromBase58(Network network, 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(network, bytes, ecMultiply, compressed, hasLotAndSequence, addressHash, content); } /** * Construct a password-protected private key from its Base58 representation. * @param params * The network 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 * @deprecated use {@link #fromBase58(Network, String)} */ @Deprecated public static BIP38PrivateKey fromBase58(NetworkParameters params, String base58) throws AddressFormatException { return fromBase58(params.network(), base58); } private BIP38PrivateKey(Network network, byte[] bytes, boolean ecMultiply, boolean compressed, boolean hasLotAndSequence, byte[] addressHash, byte[] content) throws AddressFormatException { super(network, bytes); this.ecMultiply = ecMultiply; this.compressed = compressed; this.hasLotAndSequence = hasLotAndSequence; this.addressHash = addressHash; this.content = content; } /** * Returns the base58-encoded textual form, including version and checksum bytes. * * @return textual form */ public String toBase58() { return Base58.encodeChecked(1, bytes); } public ECKey decrypt(String passphrase) throws BadPassphraseException { String normalizedPassphrase = Normalizer.normalize(passphrase, Normalizer.Form.NFC); ECKey key = ecMultiply ? decryptEC(normalizedPassphrase) : decryptNoEC(normalizedPassphrase); Sha256Hash hash = Sha256Hash.twiceOf(key.toAddress(ScriptType.P2PKH, network).toString().getBytes(StandardCharsets.US_ASCII)); byte[] actualAddressHash = Arrays.copyOfRange(hash.getBytes(), 0, 4); if (!Arrays.equals(actualAddressHash, addressHash)) throw new BadPassphraseException(); return key; } private ECKey decryptNoEC(String normalizedPassphrase) { try { byte[] derived = SCrypt.generate(normalizedPassphrase.getBytes(StandardCharsets.UTF_8), addressHash, 16384, 8, 8, 64); byte[] key = Arrays.copyOfRange(derived, 32, 64); SecretKeySpec keyspec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, keyspec); byte[] decrypted = cipher.doFinal(content, 0, 32); for (int i = 0; i < 32; i++) decrypted[i] ^= derived[i]; return ECKey.fromPrivate(decrypted, compressed); } catch (GeneralSecurityException x) { throw new RuntimeException(x); } } private ECKey decryptEC(String normalizedPassphrase) { try { byte[] ownerEntropy = Arrays.copyOfRange(content, 0, 8); byte[] ownerSalt = hasLotAndSequence ? Arrays.copyOfRange(ownerEntropy, 0, 4) : ownerEntropy; byte[] passFactorBytes = SCrypt.generate(normalizedPassphrase.getBytes(StandardCharsets.UTF_8), ownerSalt, 16384, 8, 8, 32); if (hasLotAndSequence) { byte[] hashBytes = Bytes.concat(passFactorBytes, ownerEntropy); checkState(hashBytes.length == 40); passFactorBytes = Sha256Hash.hashTwice(hashBytes); } BigInteger passFactor = ByteUtils.bytesToBigInteger(passFactorBytes); ECKey k = ECKey.fromPrivate(passFactor, true); byte[] salt = Bytes.concat(addressHash, ownerEntropy); checkState(salt.length == 12); byte[] derived = SCrypt.generate(k.getPubKey(), salt, 1024, 1, 1, 64); byte[] aeskey = Arrays.copyOfRange(derived, 32, 64); SecretKeySpec keyspec = new SecretKeySpec(aeskey, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, keyspec); byte[] encrypted2 = Arrays.copyOfRange(content, 16, 32); byte[] decrypted2 = cipher.doFinal(encrypted2); checkState(decrypted2.length == 16); for (int i = 0; i < 16; i++) decrypted2[i] ^= derived[i + 16]; byte[] encrypted1 = Bytes.concat(Arrays.copyOfRange(content, 8, 16), Arrays.copyOfRange(decrypted2, 0, 8)); byte[] decrypted1 = cipher.doFinal(encrypted1); checkState(decrypted1.length == 16); for (int i = 0; i < 16; i++) decrypted1[i] ^= derived[i]; byte[] seed = Bytes.concat(decrypted1, Arrays.copyOfRange(decrypted2, 8, 16)); checkState(seed.length == 24); BigInteger seedFactor = ByteUtils.bytesToBigInteger(Sha256Hash.hashTwice(seed)); checkState(passFactor.signum() >= 0); checkState(seedFactor.signum() >= 0); BigInteger priv = passFactor.multiply(seedFactor).mod(ECKey.CURVE.getN()); return ECKey.fromPrivate(priv, compressed); } catch (GeneralSecurityException x) { throw new RuntimeException(x); } } @Override public String toString() { return toBase58(); } }
9,766
43.802752
136
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/X509Utils.java
/* * Copyright 2014 The bitcoinj authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.bitcoinj.protocols.payments.PaymentSession; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1String; import org.bouncycastle.asn1.x500.AttributeTypeAndValue; import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.RFC4519Style; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; /** * X509Utils provides tools for working with X.509 certificates and keystores, as used in the BIP 70 payment protocol. * For more details on this, see {@link PaymentSession}, the article "Working with * the payment protocol" on the bitcoinj website, or the Bitcoin developer guide. */ public class X509Utils { /** * Returns either a string that "sums up" the certificate for humans, in a similar manner to what you might see * in a web browser, or null if one cannot be extracted. This will typically be the common name (CN) field, but * can also be the org (O) field, org+location+country if withLocation is set, or the email * address for S/MIME certificates. */ @Nullable public static String getDisplayNameFromCertificate(@Nonnull X509Certificate certificate, boolean withLocation) throws CertificateParsingException { X500Name name = new X500Name(certificate.getSubjectX500Principal().getName()); String commonName = null, org = null, location = null, country = null; for (RDN rdn : name.getRDNs()) { AttributeTypeAndValue pair = rdn.getFirst(); String val = ((ASN1String) pair.getValue()).getString(); ASN1ObjectIdentifier type = pair.getType(); if (type.equals(RFC4519Style.cn)) commonName = val; else if (type.equals(RFC4519Style.o)) org = val; else if (type.equals(RFC4519Style.l)) location = val; else if (type.equals(RFC4519Style.c)) country = val; } String altName = null; try { final Collection<List<?>> subjectAlternativeNames = certificate.getSubjectAlternativeNames(); if (subjectAlternativeNames != null) for (final List<?> subjectAlternativeName : subjectAlternativeNames) if ((Integer) subjectAlternativeName.get(0) == 1) // rfc822name altName = (String) subjectAlternativeName.get(1); } catch (CertificateParsingException e) { // swallow } if (org != null) { return withLocation ? Stream.of(org, location, country).filter(Objects::nonNull).collect(Collectors.joining()) : org; } else if (commonName != null) { return commonName; } else { return altName; } } /** Returns a key store loaded from the given stream. Just a convenience around the Java APIs. */ public static KeyStore loadKeyStore(String keystoreType, @Nullable String keystorePassword, InputStream is) throws KeyStoreException { try { KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(is, keystorePassword != null ? keystorePassword.toCharArray() : null); return keystore; } catch (IOException | GeneralSecurityException x) { throw new KeyStoreException(x); } finally { try { is.close(); } catch (IOException x) { // Ignored. } } } }
4,597
41.183486
151
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/MnemonicException.java
/* * Copyright 2013 Ken Sedgwick * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; /** * Exceptions thrown by the MnemonicCode module. */ @SuppressWarnings("serial") public class MnemonicException extends Exception { public MnemonicException() { super(); } public MnemonicException(String msg) { super(msg); } /** * Thrown when an argument to MnemonicCode is the wrong length. */ public static class MnemonicLengthException extends MnemonicException { public MnemonicLengthException(String msg) { super(msg); } } /** * Thrown when a list of MnemonicCode words fails the checksum check. */ public static class MnemonicChecksumException extends MnemonicException { public MnemonicChecksumException() { super(); } } /** * Thrown when a word is encountered which is not in the MnemonicCode's word list. */ public static class MnemonicWordException extends MnemonicException { /** Contains the word that was not found in the word list. */ public final String badWord; public MnemonicWordException(String badWord) { super(); this.badWord = badWord; } } }
1,809
27.730159
86
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/HDKeyDerivation.java
/* * Copyright 2013 Matija Mazi. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.base.internal.ByteUtils; import org.bouncycastle.math.ec.ECPoint; import java.math.BigInteger; import java.nio.ByteBuffer; import java.security.SecureRandom; import java.util.Arrays; import java.util.function.Supplier; import java.util.stream.Stream; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Implementation of the <a href="https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki">BIP 32</a> * deterministic wallet child key generation algorithm. */ public final class HDKeyDerivation { static { RAND_INT = new BigInteger(256, new SecureRandom()); } // Some arbitrary random number. Doesn't matter what it is. private static final BigInteger RAND_INT; private HDKeyDerivation() { } /** * Child derivation may fail (although with extremely low probability); in such case it is re-attempted. * This is the maximum number of re-attempts (to avoid an infinite loop in case of bugs etc.). */ public static final int MAX_CHILD_DERIVATION_ATTEMPTS = 100; /** * Generates a new deterministic key from the given seed, which can be any arbitrary byte array. However resist * the temptation to use a string as the seed - any key derived from a password is likely to be weak and easily * broken by attackers (this is not theoretical, people have had money stolen that way). This method checks * that the given seed is at least 64 bits long. * * @throws HDDerivationException if generated master key is invalid (private key not between 0 and n inclusive) * @throws IllegalArgumentException if the seed is less than 8 bytes and could be brute forced */ public static DeterministicKey createMasterPrivateKey(byte[] seed) throws HDDerivationException { checkArgument(seed.length > 8, () -> "seed is too short and could be brute forced"); // Calculate I = HMAC-SHA512(key="Bitcoin seed", msg=S) byte[] i = HDUtils.hmacSha512(HDUtils.createHmacSha512Digest("Bitcoin seed".getBytes()), seed); // Split I into two 32-byte sequences, Il and Ir. // Use Il as master secret key, and Ir as master chain code. checkState(i.length == 64, () -> "" + i.length); byte[] il = Arrays.copyOfRange(i, 0, 32); byte[] ir = Arrays.copyOfRange(i, 32, 64); Arrays.fill(i, (byte)0); DeterministicKey masterPrivKey = createMasterPrivKeyFromBytes(il, ir); Arrays.fill(il, (byte)0); Arrays.fill(ir, (byte)0); // Child deterministic keys will chain up to their parents to find the keys. masterPrivKey.setCreationTime(TimeUtils.currentTime()); return masterPrivKey; } /** * @throws HDDerivationException if privKeyBytes is invalid (not between 0 and n inclusive). */ public static DeterministicKey createMasterPrivKeyFromBytes(byte[] privKeyBytes, byte[] chainCode) throws HDDerivationException { BigInteger priv = ByteUtils.bytesToBigInteger(privKeyBytes); assertNonZero(priv, "Generated master key is invalid."); assertLessThanN(priv, "Generated master key is invalid."); return new DeterministicKey(HDPath.m(), chainCode, priv, null); } public static DeterministicKey createMasterPubKeyFromBytes(byte[] pubKeyBytes, byte[] chainCode) { return new DeterministicKey(HDPath.M(), chainCode, new LazyECPoint(ECKey.CURVE.getCurve(), pubKeyBytes), null, null); } /** * Derives a key given the "extended" child number, ie. the 0x80000000 bit of the value that you * pass for {@code childNumber} will determine whether to use hardened derivation or not. * Consider whether your code would benefit from the clarity of the equivalent, but explicit, form * of this method that takes a {@code ChildNumber} rather than an {@code int}, for example: * {@code deriveChildKey(parent, new ChildNumber(childNumber, true))} * where the value of the hardened bit of {@code childNumber} is zero. */ public static DeterministicKey deriveChildKey(DeterministicKey parent, int childNumber) { return deriveChildKey(parent, new ChildNumber(childNumber)); } /** * Derives a key of the "extended" child number, ie. with the 0x80000000 bit specifying whether to use * hardened derivation or not. If derivation fails, tries a next child. */ public static DeterministicKey deriveThisOrNextChildKey(DeterministicKey parent, int childNumber) { int nAttempts = 0; ChildNumber child = new ChildNumber(childNumber); boolean isHardened = child.isHardened(); while (nAttempts < MAX_CHILD_DERIVATION_ATTEMPTS) { try { child = new ChildNumber(child.num() + nAttempts, isHardened); return deriveChildKey(parent, child); } catch (HDDerivationException ignore) { } nAttempts++; } throw new HDDerivationException("Maximum number of child derivation attempts reached, this is probably an indication of a bug."); } /** * Generate an infinite stream of {@link DeterministicKey}s from the given parent and index. * <p> * Note: Use {@link Stream#limit(long)} to get the desired number of keys. * @param parent The parent key * @param childNumber The index of the first child to supply/generate * @return A stream of {@code DeterministicKey}s */ public static Stream<DeterministicKey> generate(DeterministicKey parent, int childNumber) { return Stream.generate(new KeySupplier(parent, childNumber)); } /** * @throws HDDerivationException if private derivation is attempted for a public-only parent key, or * if the resulting derived key is invalid (eg. private key == 0). */ public static DeterministicKey deriveChildKey(DeterministicKey parent, ChildNumber childNumber) throws HDDerivationException { if (!parent.hasPrivKey()) return deriveChildKeyFromPublic(parent, childNumber, PublicDeriveMode.NORMAL); else return deriveChildKeyFromPrivate(parent, childNumber); } public static DeterministicKey deriveChildKeyFromPrivate(DeterministicKey parent, ChildNumber childNumber) throws HDDerivationException { RawKeyBytes rawKey = deriveChildKeyBytesFromPrivate(parent, childNumber); return new DeterministicKey(parent.getPath().extend(childNumber), rawKey.chainCode, ByteUtils.bytesToBigInteger(rawKey.keyBytes), parent); } public static RawKeyBytes deriveChildKeyBytesFromPrivate(DeterministicKey parent, ChildNumber childNumber) throws HDDerivationException { checkArgument(parent.hasPrivKey(), () -> "parent key must have private key bytes for this method"); byte[] parentPublicKey = parent.getPubKeyPoint().getEncoded(true); checkState(parentPublicKey.length == 33, () -> "parent pubkey must be 33 bytes, but is: " + parentPublicKey.length); ByteBuffer data = ByteBuffer.allocate(37); if (childNumber.isHardened()) { data.put(parent.getPrivKeyBytes33()); } else { data.put(parentPublicKey); } data.putInt(childNumber.i()); byte[] i = HDUtils.hmacSha512(parent.getChainCode(), data.array()); checkState(i.length == 64, () -> "" + i.length); byte[] il = Arrays.copyOfRange(i, 0, 32); byte[] chainCode = Arrays.copyOfRange(i, 32, 64); BigInteger ilInt = ByteUtils.bytesToBigInteger(il); assertLessThanN(ilInt, "Illegal derived key: I_L >= n"); final BigInteger priv = parent.getPrivKey(); BigInteger ki = priv.add(ilInt).mod(ECKey.CURVE.getN()); assertNonZero(ki, "Illegal derived key: derived private key equals 0."); return new RawKeyBytes(ki.toByteArray(), chainCode); } public enum PublicDeriveMode { NORMAL, WITH_INVERSION } public static DeterministicKey deriveChildKeyFromPublic(DeterministicKey parent, ChildNumber childNumber, PublicDeriveMode mode) throws HDDerivationException { RawKeyBytes rawKey = deriveChildKeyBytesFromPublic(parent, childNumber, PublicDeriveMode.NORMAL); return new DeterministicKey(parent.getPath().extend(childNumber), rawKey.chainCode, new LazyECPoint(ECKey.CURVE.getCurve(), rawKey.keyBytes), null, parent); } public static RawKeyBytes deriveChildKeyBytesFromPublic(DeterministicKey parent, ChildNumber childNumber, PublicDeriveMode mode) throws HDDerivationException { checkArgument(!childNumber.isHardened(), () -> "hardened derivation is unsupported: " + childNumber); byte[] parentPublicKey = parent.getPubKeyPoint().getEncoded(true); checkState(parentPublicKey.length == 33, () -> "parent pubkey must be 33 bytes, but is: " + parentPublicKey.length); ByteBuffer data = ByteBuffer.allocate(37); data.put(parentPublicKey); data.putInt(childNumber.i()); byte[] i = HDUtils.hmacSha512(parent.getChainCode(), data.array()); checkState(i.length == 64, () -> "" + i.length); byte[] il = Arrays.copyOfRange(i, 0, 32); byte[] chainCode = Arrays.copyOfRange(i, 32, 64); BigInteger ilInt = ByteUtils.bytesToBigInteger(il); assertLessThanN(ilInt, "Illegal derived key: I_L >= n"); final BigInteger N = ECKey.CURVE.getN(); ECPoint Ki; switch (mode) { case NORMAL: Ki = ECKey.publicPointFromPrivate(ilInt).add(parent.getPubKeyPoint()); break; case WITH_INVERSION: // This trick comes from Gregory Maxwell. Check the homomorphic properties of our curve hold. The // below calculations should be redundant and give the same result as NORMAL but if the precalculated // tables have taken a bit flip will yield a different answer. This mode is used when vending a key // to perform a last-ditch sanity check trying to catch bad RAM. Ki = ECKey.publicPointFromPrivate(ilInt.add(RAND_INT).mod(N)); BigInteger additiveInverse = RAND_INT.negate().mod(N); Ki = Ki.add(ECKey.publicPointFromPrivate(additiveInverse)); Ki = Ki.add(parent.getPubKeyPoint()); break; default: throw new AssertionError(); } assertNonInfinity(Ki, "Illegal derived key: derived public key equals infinity."); return new RawKeyBytes(Ki.getEncoded(true), chainCode); } private static void assertNonZero(BigInteger integer, String errorMessage) { if (integer.equals(BigInteger.ZERO)) throw new HDDerivationException(errorMessage); } private static void assertNonInfinity(ECPoint point, String errorMessage) { if (point.equals(ECKey.CURVE.getCurve().getInfinity())) throw new HDDerivationException(errorMessage); } private static void assertLessThanN(BigInteger integer, String errorMessage) { if (integer.compareTo(ECKey.CURVE.getN()) > 0) throw new HDDerivationException(errorMessage); } /** * A supplier of a sequence of {@code DeterministicKey}s generated from a starting * parent and child index. * <p><b>Not threadsafe: Should be used on a single thread</b> */ private static class KeySupplier implements Supplier<DeterministicKey> { private final DeterministicKey parent; private int nextChild; /** * Construct a key supplier with the specified starting point * @param parent The parent key * @param nextChild The index of the next child to supply/generate */ public KeySupplier(DeterministicKey parent, int nextChild) { this.parent = parent; this.nextChild = nextChild; } @Override public DeterministicKey get() { DeterministicKey key = HDKeyDerivation.deriveThisOrNextChildKey(parent, nextChild); nextChild = key.getChildNumber().num() + 1; return key; } } public static class RawKeyBytes { public final byte[] keyBytes, chainCode; public RawKeyBytes(byte[] keyBytes, byte[] chainCode) { this.keyBytes = keyBytes; this.chainCode = chainCode; } } }
13,387
45.648084
163
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/utils/MessageVerifyUtils.java
package org.bitcoinj.crypto.utils; import com.google.common.primitives.Bytes; import org.bitcoinj.base.LegacyAddress; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Address; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.base.SegwitAddress; import org.bitcoinj.crypto.internal.CryptoUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.security.SignatureException; import java.util.Arrays; /** * Small utility class for verifying signatures of text messages created with * Bitcoin addresses (more precisely: with the private key of Bitcoin addresses). * Supports verifying of signatures created with:<ul> * <li>P2PKH addresses (old legacy 1… addresses)</li> * <li>P2WPKH addresses (native segwit v0 addresses, aka bc1q… addresses)</li> * <li>P2SH-P2WPKH addresses (segwit wrapped into P2SH, aka legacy segwit addresses, like 3…)</li> * </ul> */ public class MessageVerifyUtils { private MessageVerifyUtils() {} private static final Logger log = LoggerFactory.getLogger(MessageVerifyUtils.class); public static final String SIGNATURE_FAILED_ERROR_MESSAGE = "Signature did not match for message"; /** * Verifies messages signed with private keys of Bitcoin addresses. * * @param address bitcoin address used to create the signature * @param message message which has been signed * @param signatureBase64 signature as base64 encoded string * @throws SignatureException if the signature does not match the message and the address */ public static void verifyMessage(final Address address, final String message, final String signatureBase64) throws SignatureException { try { final ScriptType scriptType = address.getOutputScriptType(); switch (scriptType) { case P2PKH: case P2WPKH: comparePubKeyHash(address, message, signatureBase64); break; case P2SH: compareP2SHScriptHashDerivedFromPubKey((LegacyAddress) address, message, signatureBase64); break; default: throw new SignatureException(SIGNATURE_FAILED_ERROR_MESSAGE); } } catch (final SignatureException se) { throw se; } catch (final Exception e) { log.warn("verifying of message signature failed with exception", e); throw new SignatureException(SIGNATURE_FAILED_ERROR_MESSAGE); } } private static void comparePubKeyHash(final Address address, final String message, final String signatureBase64) throws SignatureException { // Message signing/verification in this form is not supported for Taproot addresses // (Taproot uses Schnorr signatures, which - unlike ECDSA - do not support key recovery.) // A new message signing format is currently in work in BIP 322 that can verify signatures // from all types of addresses, including scripts, multisig, and Taproot. // It is currently a draft. if (address instanceof SegwitAddress) { if (((SegwitAddress) address).getWitnessVersion() > 0) { throw new SignatureException("Message verification currently only supports segwit version 0"); } } final byte[] pubKeyHashFromSignature = ECKey.signedMessageToKey(message, signatureBase64).getPubKeyHash(); final byte[] pubKeyHashFromAddress = address.getHash(); if (!Arrays.equals(pubKeyHashFromAddress, pubKeyHashFromSignature)) { throw new SignatureException(SIGNATURE_FAILED_ERROR_MESSAGE); } } private static void compareP2SHScriptHashDerivedFromPubKey(final LegacyAddress address, final String message, final String signatureBase64) throws SignatureException { final byte[] pubKeyHashFromSignature = ECKey.signedMessageToKey(message, signatureBase64).getPubKeyHash(); // in case of P2SH addresses the address doesn't contain a pubKeyHash, but // instead the hash of a script, to be used in a scriptPubKey like this: // > OP_HASH160 <20-byte-script-hash> OP_EQUAL // Here we get this "<20-byte-script-hash>": final byte[] scriptHashFromAddress = address.getHash(); // The script whose hash is embedded in a P2SH-P2WPKH address is the // scriptPubKey of P2WPKH (see BIP 141): // > 0x00 OP_PUSH_20 <20-byte-pub-key-hash> // (the leading 0x00 is the witness program version byte) // So to be able to compare this with the recovered pubKeyHash, we need to // wrap the recovered pubKeyHash from the signature in the same type of script: final byte[] segwitScriptFromSignaturePubKey = wrapPubKeyHashInSegwitScript(pubKeyHashFromSignature); // and as in a P2SH address only the hash of the script is contained, we also hash this script before comparing: final byte[] scriptHashDerivedFromSig = CryptoUtils.sha256hash160(segwitScriptFromSignaturePubKey); if (!Arrays.equals(scriptHashFromAddress, scriptHashDerivedFromSig)) { throw new SignatureException(SIGNATURE_FAILED_ERROR_MESSAGE); } } /** * Returns "scriptPubKey" as it's used in BIP 141 P2WPKH addresses: 0x0014{20-byte-key-hash} * * @return (0x00 | 0x14 | pubKeyHash) * @see <a href="https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH">BIP 141</a> */ private static byte[] wrapPubKeyHashInSegwitScript(final byte[] pubKeyHash) { // According to BIP 141 the scriptPubkey for Segwit (P2WPKH) is prefixed with: 0x00 0x14 // see BIP 141 (https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#p2wpkh) // 0x00 indicates witness version 0 // 0x14 is OP_PUSH_20, pushes the next 20 bytes (=length of the pubkeyHash) on the stack // (it's safe to hardcode version 0 here, as P2SH-wrapping is only defined for segwit version 0) final byte[] scriptPubKeyPrefix = {0x00, 0x14}; return Bytes.concat(scriptPubKeyPrefix, pubKeyHash); } }
6,457
47.19403
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/crypto/internal/CryptoUtils.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.crypto.internal; import org.bitcoinj.base.Sha256Hash; import org.bouncycastle.crypto.digests.RIPEMD160Digest; import org.bouncycastle.jcajce.provider.digest.SHA3; import java.nio.charset.StandardCharsets; import java.util.Arrays; /** * Utilities for the crypto module (e.g. using Bouncy Castle) */ public class CryptoUtils { /** * Calculate RIPEMD160(SHA256(input)). This is used in Address calculations. * @param input bytes to hash * @return RIPEMD160(SHA256(input)) */ public static byte[] sha256hash160(byte[] input) { byte[] sha256 = Sha256Hash.hash(input); return digestRipeMd160(sha256); } /** * Calculate RIPEMD160(input). * @param input bytes to hash * @return RIPEMD160(input) */ public static byte[] digestRipeMd160(byte[] input) { RIPEMD160Digest digest = new RIPEMD160Digest(); digest.update(input, 0, input.length); byte[] ripmemdHash = new byte[20]; digest.doFinal(ripmemdHash, 0); return ripmemdHash; } /** * Calculate TOR Onion Checksum (used by PeerAddress) */ public static byte[] onionChecksum(byte[] pubkey, byte version) { if (pubkey.length != 32) throw new IllegalArgumentException(); SHA3.Digest256 digest256 = new SHA3.Digest256(); digest256.update(".onion checksum".getBytes(StandardCharsets.US_ASCII)); digest256.update(pubkey); digest256.update(version); return Arrays.copyOf(digest256.digest(), 2); } }
2,174
32.461538
80
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/BloomFilter.java
/* * Copyright 2012 Matt Corallo * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.base.MoreObjects; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.Buffers; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptChunk; import org.bitcoinj.script.ScriptPattern; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import static java.lang.Math.E; import static java.lang.Math.log; import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.pow; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * <p>A Bloom filter is a probabilistic data structure which can be sent to another client so that it can avoid * sending us transactions that aren't relevant to our set of keys. This allows for significantly more efficient * use of available network bandwidth and CPU time.</p> * * <p>Because a Bloom filter is probabilistic, it has a configurable false positive rate. So the filter will sometimes * match transactions that weren't inserted into it, but it will never fail to match transactions that were. This is * a useful privacy feature - if you have spare bandwidth the false positive rate can be increased so the remote peer * gets a noisy picture of what transactions are relevant to your wallet.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class BloomFilter extends BaseMessage { /** The BLOOM_UPDATE_* constants control when the bloom filter is auto-updated by the peer using it as a filter, either never, for all outputs or only for P2PK outputs (default) */ public enum BloomUpdate { UPDATE_NONE, // 0 UPDATE_ALL, // 1 /** Only adds outpoints to the filter if the output is a P2PK/pay-to-multisig script */ UPDATE_P2PUBKEY_ONLY //2 } private byte[] data; private long hashFuncs; private int nTweak; private byte nFlags; // Same value as Bitcoin Core // A filter of 20,000 items and a false positive rate of 0.1% or one of 10,000 items and 0.0001% is just under 36,000 bytes private static final long MAX_FILTER_SIZE = 36000; // There is little reason to ever have more hash functions than 50 given a limit of 36,000 bytes private static final int MAX_HASH_FUNCS = 50; /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static BloomFilter read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { byte[] data = Buffers.readLengthPrefixedBytes(payload); if (data.length > MAX_FILTER_SIZE) throw new ProtocolException("Bloom filter out of size range."); long hashFuncs = ByteUtils.readUint32(payload); if (hashFuncs > MAX_HASH_FUNCS) throw new ProtocolException("Bloom filter hash function count out of range"); int nTweak = ByteUtils.readInt32(payload); byte nFlags = payload.get(); return new BloomFilter(data, hashFuncs, nTweak, nFlags); } /** * Constructs a filter with the given parameters which is updated on P2PK outputs only. */ public BloomFilter(int elements, double falsePositiveRate, int randomNonce) { this(elements, falsePositiveRate, randomNonce, BloomUpdate.UPDATE_P2PUBKEY_ONLY); } /** * <p>Constructs a new Bloom Filter which will provide approximately the given false positive rate when the given * number of elements have been inserted. If the filter would otherwise be larger than the maximum allowed size, * it will be automatically downsized to the maximum size.</p> * * <p>To check the theoretical false positive rate of a given filter, use * {@link BloomFilter#getFalsePositiveRate(int)}.</p> * * <p>The anonymity of which coins are yours to any peer which you send a BloomFilter to is controlled by the * false positive rate. For reference, as of block 187,000, the total number of addresses used in the chain was * roughly 4.5 million. Thus, if you use a false positive rate of 0.001 (0.1%), there will be, on average, 4,500 * distinct public keys/addresses which will be thought to be yours by nodes which have your bloom filter, but * which are not actually yours. Keep in mind that a remote node can do a pretty good job estimating the order of * magnitude of the false positive rate of a given filter you provide it when considering the anonymity of a given * filter.</p> * * <p>In order for filtered block download to function efficiently, the number of matched transactions in any given * block should be less than (with some headroom) the maximum size of the MemoryPool used by the Peer * doing the downloading (default is {@link TxConfidenceTable#MAX_SIZE}). See the comment in processBlock(FilteredBlock) * for more information on this restriction.</p> * * <p>randomNonce is a tweak for the hash function used to prevent some theoretical DoS attacks. * It should be a random value, however secureness of the random value is of no great consequence.</p> * * <p>updateFlag is used to control filter behaviour on the server (remote node) side when it encounters a hit. * See {@link BloomFilter.BloomUpdate} for a brief description of each mode. The purpose * of this flag is to reduce network round-tripping and avoid over-dirtying the filter for the most common * wallet configurations.</p> */ public BloomFilter(int elements, double falsePositiveRate, int randomNonce, BloomUpdate updateFlag) { // The following formulas were stolen from Wikipedia's page on Bloom Filters (with the addition of min(..., MAX_...)) // Size required for a given number of elements and false-positive rate int size = (int)(-1 / (pow(log(2), 2)) * elements * log(falsePositiveRate)); size = max(1, min(size, (int) MAX_FILTER_SIZE * 8) / 8); data = new byte[size]; // Optimal number of hash functions for a given filter size and element count. hashFuncs = (int)(data.length * 8 / (double)elements * log(2)); hashFuncs = max(1, min(hashFuncs, MAX_HASH_FUNCS)); this.nTweak = randomNonce; this.nFlags = (byte)(0xff & updateFlag.ordinal()); } private BloomFilter(byte[] data, long hashFuncs, int nTweak, byte nFlags) { this.data = data; this.hashFuncs = hashFuncs; this.nTweak = nTweak; this.nFlags = nFlags; } /** * Returns the theoretical false positive rate of this filter if were to contain the given number of elements. */ public double getFalsePositiveRate(int elements) { return pow(1 - pow(E, -1.0 * (hashFuncs * elements) / (data.length * 8)), hashFuncs); } @Override public String toString() { final MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues(); helper.add("data length", data.length); helper.add("hashFuncs", hashFuncs); helper.add("nFlags", getUpdateFlag()); return helper.toString(); } /** * Serializes this message to the provided stream. If you just want the raw bytes use bitcoinSerialize(). */ @Override protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { stream.write(VarInt.of(data.length).serialize()); stream.write(data); ByteUtils.writeInt32LE(hashFuncs, stream); ByteUtils.writeInt32LE(nTweak, stream); stream.write(nFlags); } private static int rotateLeft32(int x, int r) { return (x << r) | (x >>> (32 - r)); } /** * Applies the MurmurHash3 (x86_32) algorithm to the given data. * See this <a href="https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp">C++ code for the original.</a> */ public static int murmurHash3(byte[] data, long nTweak, int hashNum, byte[] object) { int h1 = (int)(hashNum * 0xFBA4C795L + nTweak); final int c1 = 0xcc9e2d51; final int c2 = 0x1b873593; int numBlocks = (object.length / 4) * 4; // body for(int i = 0; i < numBlocks; i += 4) { int k1 = (object[i] & 0xFF) | ((object[i+1] & 0xFF) << 8) | ((object[i+2] & 0xFF) << 16) | ((object[i+3] & 0xFF) << 24); k1 *= c1; k1 = rotateLeft32(k1, 15); k1 *= c2; h1 ^= k1; h1 = rotateLeft32(h1, 13); h1 = h1*5+0xe6546b64; } int k1 = 0; switch(object.length & 3) { case 3: k1 ^= (object[numBlocks + 2] & 0xff) << 16; // Fall through. case 2: k1 ^= (object[numBlocks + 1] & 0xff) << 8; // Fall through. case 1: k1 ^= (object[numBlocks] & 0xff); k1 *= c1; k1 = rotateLeft32(k1, 15); k1 *= c2; h1 ^= k1; // Fall through. default: // Do nothing. break; } // finalization h1 ^= object.length; h1 ^= h1 >>> 16; h1 *= 0x85ebca6b; h1 ^= h1 >>> 13; h1 *= 0xc2b2ae35; h1 ^= h1 >>> 16; return (int)((h1&0xFFFFFFFFL) % (data.length * 8)); } /** * Returns true if the given object matches the filter either because it was inserted, or because we have a * false-positive. */ public synchronized boolean contains(byte[] object) { for (int i = 0; i < hashFuncs; i++) { if (!ByteUtils.checkBitLE(data, murmurHash3(data, nTweak, i, object))) return false; } return true; } /** Insert the given arbitrary data into the filter */ public synchronized void insert(byte[] object) { for (int i = 0; i < hashFuncs; i++) ByteUtils.setBitLE(data, murmurHash3(data, nTweak, i, object)); } /** Inserts the given key and equivalent hashed form (for the address). */ public synchronized void insert(ECKey key) { insert(key.getPubKey()); insert(key.getPubKeyHash()); } /** Inserts the given transaction outpoint. */ public synchronized void insert(TransactionOutPoint outpoint) { insert(outpoint.serialize()); } /** * Sets this filter to match all objects. A Bloom filter which matches everything may seem pointless, however, * it is useful in order to reduce steady state bandwidth usage when you want full blocks. Instead of receiving * all transaction data twice, you will receive the vast majority of all transactions just once, at broadcast time. * Solved blocks will then be send just as Merkle trees of tx hashes, meaning a constant 32 bytes of data for each * transaction instead of 100-300 bytes as per usual. */ public synchronized void setMatchAll() { data = new byte[] {(byte) 0xff}; } /** * Copies filter into this. Filter must have the same size, hash function count and nTweak or an * IllegalArgumentException will be thrown. */ public synchronized void merge(BloomFilter filter) { if (!this.matchesAll() && !filter.matchesAll()) { checkArgument(filter.data.length == this.data.length && filter.hashFuncs == this.hashFuncs && filter.nTweak == this.nTweak); for (int i = 0; i < data.length; i++) this.data[i] |= filter.data[i]; } else { this.data = new byte[] {(byte) 0xff}; } } /** * Returns true if this filter will match anything. See {@link BloomFilter#setMatchAll()} * for when this can be a useful thing to do. */ public synchronized boolean matchesAll() { for (byte b : data) if (b != (byte) 0xff) return false; return true; } /** * The update flag controls how application of the filter to a block modifies the filter. See the enum javadocs * for information on what occurs and when. */ public synchronized BloomUpdate getUpdateFlag() { if (nFlags == 0) return BloomUpdate.UPDATE_NONE; else if (nFlags == 1) return BloomUpdate.UPDATE_ALL; else if (nFlags == 2) return BloomUpdate.UPDATE_P2PUBKEY_ONLY; else throw new IllegalStateException("Unknown flag combination"); } /** * Creates a new FilteredBlock from the given Block, using this filter to select transactions. Matches can cause the * filter to be updated with the matched element, this ensures that when a filter is applied to a block, spends of * matched transactions are also matched. However it means this filter can be mutated by the operation. The returned * filtered block already has the matched transactions associated with it. */ public synchronized FilteredBlock applyAndUpdate(Block block) { List<Transaction> txns = block.getTransactions(); List<Sha256Hash> txHashes = new ArrayList<>(txns.size()); List<Transaction> matched = new ArrayList<>(); byte[] bits = new byte[(int) Math.ceil(txns.size() / 8.0)]; for (int i = 0; i < txns.size(); i++) { Transaction tx = txns.get(i); txHashes.add(tx.getTxId()); if (applyAndUpdate(tx)) { ByteUtils.setBitLE(bits, i); matched.add(tx); } } PartialMerkleTree pmt = PartialMerkleTree.buildFromLeaves(bits, txHashes); FilteredBlock filteredBlock = new FilteredBlock(block.cloneAsHeader(), pmt); for (Transaction transaction : matched) filteredBlock.provideTransaction(transaction); return filteredBlock; } public synchronized boolean applyAndUpdate(Transaction tx) { if (contains(tx.getTxId().getBytes())) return true; boolean found = false; BloomUpdate flag = getUpdateFlag(); for (TransactionOutput output : tx.getOutputs()) { Script script = output.getScriptPubKey(); for (ScriptChunk chunk : script.chunks()) { if (!chunk.isPushData()) continue; if (contains(chunk.data)) { boolean isSendingToPubKeys = ScriptPattern.isP2PK(script) || ScriptPattern.isSentToMultisig(script); if (flag == BloomUpdate.UPDATE_ALL || (flag == BloomUpdate.UPDATE_P2PUBKEY_ONLY && isSendingToPubKeys)) insert(output.getOutPointFor()); found = true; } } } if (found) return true; for (TransactionInput input : tx.getInputs()) { if (contains(input.getOutpoint().serialize())) { return true; } for (ScriptChunk chunk : input.getScriptSig().chunks()) { if (chunk.isPushData() && contains(chunk.data)) return true; } } return false; } @Override public synchronized boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BloomFilter other = (BloomFilter) o; return hashFuncs == other.hashFuncs && nTweak == other.nTweak && Arrays.equals(data, other.data); } @Override public synchronized int hashCode() { return Objects.hash(hashFuncs, nTweak, Arrays.hashCode(data)); } }
16,836
41.842239
127
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/GetHeadersMessage.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.ByteUtils; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import static org.bitcoinj.base.internal.Preconditions.check; /** * <p>The "getheaders" command is structurally identical to "getblocks", but has different meaning. On receiving this * message a Bitcoin node returns matching blocks up to the limit, but without the bodies. It is useful as an * optimization: when your wallet does not contain any keys created before a particular time, you don't have to download * the bodies for those blocks because you know there are no relevant transactions.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class GetHeadersMessage extends GetBlocksMessage { /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static GetHeadersMessage read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { long version = ByteUtils.readUint32(payload); VarInt startCountVarInt = VarInt.read(payload); check(startCountVarInt.fitsInt(), BufferUnderflowException::new); int startCount = startCountVarInt.intValue(); if (startCount > 500) throw new ProtocolException("Number of locators cannot be > 500, received: " + startCount); BlockLocator locator = new BlockLocator(); for (int i = 0; i < startCount; i++) { locator = locator.add(Sha256Hash.read(payload)); } Sha256Hash stopHash = Sha256Hash.read(payload); return new GetHeadersMessage(version, locator, stopHash); } public GetHeadersMessage(long protocolVersion, BlockLocator locator, Sha256Hash stopHash) { super(protocolVersion, locator, stopHash); } @Override public String toString() { return "getheaders: " + locator.toString(); } /** * Compares two getheaders messages. Note that even though they are structurally identical a GetHeadersMessage * will not compare equal to a GetBlocksMessage containing the same data. */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GetHeadersMessage other = (GetHeadersMessage) o; return version == other.version && stopHash.equals(other.stopHash) && locator.size() == other.locator.size() && locator.equals(other.locator); // ignores locator ordering } @Override public int hashCode() { int hashCode = (int) version ^ "getheaders".hashCode() ^ stopHash.hashCode(); return hashCode ^= locator.hashCode(); } }
3,566
40
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/AddressV2Message.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.InternalUtils; import org.bitcoinj.net.discovery.PeerDiscovery; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.List; /** * Represents an "addrv2" message on the P2P network, which contains broadcast addresses of other peers. This is * one of the ways peers can find each other without using the {@link PeerDiscovery} mechanism. * <p> * See <a href="https://github.com/bitcoin/bips/blob/master/bip-0155.mediawiki">BIP155</a> for details. * <p> * Instances of this class are not safe for use by multiple threads. */ public class AddressV2Message extends AddressMessage { /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static AddressV2Message read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { return new AddressV2Message(readAddresses(payload, 2)); } private AddressV2Message(List<PeerAddress> addresses) { super(addresses); } public void addAddress(PeerAddress address) { addresses.add(address); } @Override protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { if (addresses == null) return; stream.write(VarInt.of(addresses.size()).serialize()); for (PeerAddress addr : addresses) { stream.write(addr.serialize(2)); } } @Override public String toString() { return "addrv2: " + InternalUtils.SPACE_JOINER.join(addresses); } }
2,460
33.180556
112
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/HeadersMessage.java
/* * Copyright 2011 Google Inc. * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.VarInt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.bitcoinj.base.internal.Preconditions.check; /** * <p>A protocol message that contains a repeated series of block headers, sent in response to the "getheaders" command. * This is useful when you want to traverse the chain but know you don't care about the block contents, for example, * because you have a freshly created wallet with no keys.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class HeadersMessage extends BaseMessage { private static final Logger log = LoggerFactory.getLogger(HeadersMessage.class); // The main client will never send us more than this number of headers. public static final int MAX_HEADERS = 2000; private List<Block> blockHeaders; /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static HeadersMessage read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { VarInt numHeadersVarInt = VarInt.read(payload); check(numHeadersVarInt.fitsInt(), BufferUnderflowException::new); int numHeaders = numHeadersVarInt.intValue(); if (numHeaders > MAX_HEADERS) throw new ProtocolException("Too many headers: got " + numHeaders + " which is larger than " + MAX_HEADERS); List<Block> blockHeaders = new ArrayList<>(); for (int i = 0; i < numHeaders; ++i) { final Block newBlockHeader = Block.read(payload); if (newBlockHeader.hasTransactions()) { throw new ProtocolException("Block header does not end with a null byte"); } blockHeaders.add(newBlockHeader); } if (log.isDebugEnabled()) { for (int i = 0; i < numHeaders; ++i) { log.debug(blockHeaders.get(i).toString()); } } return new HeadersMessage(blockHeaders); } public HeadersMessage(Block... headers) throws ProtocolException { super(); blockHeaders = Arrays.asList(headers); } public HeadersMessage(List<Block> headers) throws ProtocolException { super(); blockHeaders = headers; } @Override public void bitcoinSerializeToStream(OutputStream stream) throws IOException { stream.write(VarInt.of(blockHeaders.size()).serialize()); for (Block header : blockHeaders) { header.cloneAsHeader().bitcoinSerializeToStream(stream); stream.write(0); } } public List<Block> getBlockHeaders() { return blockHeaders; } }
3,724
34.817308
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/package-info.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The core package contains classes for network messages like {@link org.bitcoinj.core.Block} and * {@link org.bitcoinj.core.Transaction}, peer connectivity via {@link org.bitcoinj.core.PeerGroup}, * and block chain management. * If what you're doing can be described as basic bitcoin tasks, the code is probably found here. * To learn more please consult the documentation on the website. */ package org.bitcoinj.core;
1,043
42.5
100
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/ListMessage.java
/* * Copyright 2011 Google Inc. * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.base.MoreObjects; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.ByteUtils; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.bitcoinj.base.internal.Preconditions.check; /** * <p>Abstract superclass of classes with list based payload, ie InventoryMessage and GetDataMessage.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public abstract class ListMessage extends BaseMessage { // For some reason the compiler complains if this is inside InventoryItem protected List<InventoryItem> items; public static final int MAX_INVENTORY_ITEMS = 50000; protected static List<InventoryItem> readItems(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { VarInt arrayLenVarInt = VarInt.read(payload); check(arrayLenVarInt.fitsInt(), BufferUnderflowException::new); int arrayLen = arrayLenVarInt.intValue(); if (arrayLen > MAX_INVENTORY_ITEMS) throw new ProtocolException("Too many items in INV message: " + arrayLen); // An inv is vector<CInv> where CInv is int+hash. The int is either 1 or 2 for tx or block. List<InventoryItem> items = new ArrayList<>(arrayLen); for (int i = 0; i < arrayLen; i++) { if (payload.remaining() < InventoryItem.MESSAGE_LENGTH) { throw new ProtocolException("Ran off the end of the INV"); } int typeCode = (int) ByteUtils.readUint32(payload); InventoryItem.Type type = InventoryItem.Type.ofCode(typeCode); if (type == null) throw new ProtocolException("Unknown CInv type: " + typeCode); InventoryItem item = new InventoryItem(type, Sha256Hash.read(payload)); items.add(item); } return items; } public ListMessage() { super(); items = new ArrayList<>(); } protected ListMessage(List<InventoryItem> items) { this.items = items; } public List<InventoryItem> getItems() { return Collections.unmodifiableList(items); } public void addItem(InventoryItem item) { items.add(item); } public void removeItem(int index) { items.remove(index); } @Override public void bitcoinSerializeToStream(OutputStream stream) throws IOException { stream.write(VarInt.of(items.size()).serialize()); for (InventoryItem i : items) { // Write out the type code. ByteUtils.writeInt32LE(i.type.code, stream); // And now the hash. stream.write(i.hash.serialize()); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return items.equals(((ListMessage)o).items); } @Override public int hashCode() { return items.hashCode(); } @Override public String toString() { MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this); helper.addValue(items); return helper.toString(); } }
4,047
32.180328
105
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/UTXOProviderException.java
/* * Copyright 2014 Kalpesh Parmar. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; public class UTXOProviderException extends Exception { public UTXOProviderException() { super(); } public UTXOProviderException(String message) { super(message); } public UTXOProviderException(String message, Throwable cause) { super(message, cause); } public UTXOProviderException(Throwable cause) { super(cause); } }
1,013
27.166667
75
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/Context.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Coin; import org.bitcoinj.utils.ContextPropagatingThreadFactory; import org.bitcoinj.wallet.SendRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Objects; // TODO: Finish adding Context c'tors to all the different objects so we can start deprecating the versions that take NetworkParameters. // TODO: Add a working directory notion to Context and make various subsystems that want to use files default to that directory (eg. Orchid, block stores, wallet, etc). // TODO: Auto-register the block chain object here, and then use it in the (newly deprecated) TransactionConfidence.getDepthInBlocks() method: the new version should take an AbstractBlockChain specifically. // Also use the block chain object reference from the context in PeerGroup and remove the other constructors, as it's easy to forget to wire things up. // TODO: Move Threading.USER_THREAD to here and leave behind just a source code stub. Allow different instantiations of the library to use different user threads. // TODO: Keep a URI to where library internal data files can be found, to abstract over the lack of JAR files on Android. // TODO: Stash anything else that resembles global library configuration in here and use it to clean up the rest of the API without breaking people. /** * <p>The Context object holds various objects and pieces of configuration that are scoped to a specific instantiation of * bitcoinj for a specific network. You can get an instance of this class through calling {@link #get()}.</p> * * <p>Context is new in 0.13 and the library is currently in a transitional period: you should create a Context that * wraps your chosen network parameters before using the rest of the library. However if you don't, things will still * work as a Context will be created for you and stashed in thread local storage. The context is then propagated between * library created threads as needed. This automagical propagation and creation is a temporary mechanism: one day it * will be removed to avoid confusing edge cases that could occur if the developer does not fully understand it e.g. * in the case where multiple instances of the library are in use simultaneously.</p> */ public class Context { private static final Logger log = LoggerFactory.getLogger(Context.class); public static final int DEFAULT_EVENT_HORIZON = 100; final private TxConfidenceTable confidenceTable; final private int eventHorizon; final private boolean ensureMinRequiredFee; final private Coin feePerKb; final private boolean relaxProofOfWork; /** * Creates a new context object. For now, this will be done for you by the framework. Eventually you will be * expected to do this yourself in the same manner as fetching a NetworkParameters object (at the start of your app). */ public Context() { this(DEFAULT_EVENT_HORIZON, Transaction.DEFAULT_TX_FEE, true, false); } /** * Note that NetworkParameters have been removed from this class. Thus, this constructor just swallows them. * @deprecated Use {@link Context#Context()} */ @Deprecated public Context(NetworkParameters params) { this(); } /** * Creates a new custom context object. This is mainly meant for unit tests for now. * * @param eventHorizon Number of blocks after which the library will delete data and be unable to always process reorgs. See {@link #getEventHorizon()}. * @param feePerKb The default fee per 1000 virtual bytes of transaction data to pay when completing transactions. For details, see {@link SendRequest#feePerKb}. * @param ensureMinRequiredFee Whether to ensure the minimum required fee by default when completing transactions. For details, see {@link SendRequest#ensureMinRequiredFee}. * @param relaxProofOfWork If true, proof of work is not enforced. This is useful for unit-testing. See {@link Block#checkProofOfWork(boolean)}. */ public Context(int eventHorizon, Coin feePerKb, boolean ensureMinRequiredFee, boolean relaxProofOfWork) { log.info("Creating bitcoinj {} context.", VersionMessage.BITCOINJ_VERSION); this.confidenceTable = new TxConfidenceTable(); this.eventHorizon = eventHorizon; this.ensureMinRequiredFee = ensureMinRequiredFee; this.feePerKb = feePerKb; this.relaxProofOfWork = relaxProofOfWork; lastConstructed = this; } /** * Note that NetworkParameters have been removed from this class. Thus, this constructor just swallows them. * @deprecated Use {@link Context#Context(int, Coin, boolean, boolean)} */ @Deprecated public Context(NetworkParameters params, int eventHorizon, Coin feePerKb, boolean ensureMinRequiredFee) { this(eventHorizon, feePerKb, ensureMinRequiredFee, false); } private static volatile Context lastConstructed; private static boolean isStrictMode; private static final ThreadLocal<Context> slot = new ThreadLocal<>(); /** * Returns the current context that is associated with the <b>calling thread</b>. BitcoinJ is an API that has thread * affinity: much like OpenGL it expects each thread that accesses it to have been configured with a global Context * object. This method returns that. Note that to help you develop, this method will <i>also</i> propagate whichever * context was created last onto the current thread, if it's missing. However it will print an error when doing so * because propagation of contexts is meant to be done manually: this is so two libraries or subsystems that * independently use bitcoinj (or possibly alt coin forks of it) can operate correctly. * * @throws java.lang.IllegalStateException if no context exists at all or if we are in strict mode and there is no context. */ public static Context get() { Context tls = slot.get(); if (tls == null) { if (isStrictMode) { log.error("Thread is missing a bitcoinj context."); log.error("You should use Context.propagate() or a ContextPropagatingThreadFactory."); throw new IllegalStateException("missing context"); } if (lastConstructed == null) throw new IllegalStateException("You must construct a Context object before using bitcoinj!"); slot.set(lastConstructed); log.error("Performing thread fixup: you are accessing bitcoinj via a thread that has not had any context set on it."); log.error("This error has been corrected for, but doing this makes your app less robust."); log.error("You should use Context.propagate() or a ContextPropagatingThreadFactory."); log.error("Please refer to the user guide for more information about this."); log.error("Thread name is {}.", Thread.currentThread().getName()); // TODO: Actually write the user guide section about this. // TODO: If the above TODO makes it past the 0.13 release, kick Mike and tell him he sucks. return lastConstructed; } else { return tls; } } /** * Require that new threads use {@link #propagate(Context)} or {@link ContextPropagatingThreadFactory}, * rather than using a heuristic for the desired context. */ public static void enableStrictMode() { isStrictMode = true; } // A temporary internal shim designed to help us migrate internally in a way that doesn't wreck source compatibility. public static Context getOrCreate() { Context context; try { context = get(); } catch (IllegalStateException e) { log.warn("Implicitly creating context. This is a migration step and this message will eventually go away."); context = new Context(); return context; } return context; } /** * Note that NetworkParameters have been removed from this class. Thus, this method just swallows them. * @deprecated Use {@link Context#getOrCreate()} */ @Deprecated public static Context getOrCreate(NetworkParameters params) { return getOrCreate(); } /** * Sets the given context as the current thread context. You should use this if you create your own threads that * want to create core BitcoinJ objects. Generally, if a class can accept a Context in its constructor and might * be used (even indirectly) by a thread, you will want to call this first. Your task may be simplified by using * a {@link ContextPropagatingThreadFactory}. */ public static void propagate(Context context) { slot.set(Objects.requireNonNull(context)); } /** * Returns the {@link TxConfidenceTable} created by this context. The pool tracks advertised * and downloaded transactions so their confidence can be measured as a proportion of how many peers announced it. * With an un-tampered with internet connection, the more peers announce a transaction the more confidence you can * have that it's really valid. */ public TxConfidenceTable getConfidenceTable() { return confidenceTable; } /** * The event horizon is the number of blocks after which various bits of the library consider a transaction to be * so confirmed that it's safe to delete data. Re-orgs larger than the event horizon will not be correctly * processed, so the default value is high (100). */ public int getEventHorizon() { return eventHorizon; } /** * The default fee per 1000 virtual bytes of transaction data to pay when completing transactions. For details, see {@link SendRequest#feePerKb}. */ public Coin getFeePerKb() { return feePerKb; } /** * Whether to ensure the minimum required fee by default when completing transactions. For details, see {@link SendRequest#ensureMinRequiredFee}. */ public boolean isEnsureMinRequiredFee() { return ensureMinRequiredFee; } /** * If this is set to true, proof of work is not enforced. This is useful for unit-testing, as we need to create * and solve fake blocks quite often. */ public boolean isRelaxProofOfWork() { return relaxProofOfWork; } }
11,052
49.240909
206
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/InventoryMessage.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.List; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * <p>Represents the "inv" P2P network message. An inv contains a list of hashes of either blocks or transactions. It's * a bandwidth optimization - on receiving some data, a (fully validating) peer sends every connected peer an inv * containing the hash of what it saw. It'll only transmit the full thing if a peer asks for it with a * {@link GetDataMessage}.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class InventoryMessage extends ListMessage { /** A hard coded constant in the protocol. */ public static final int MAX_INV_SIZE = 50000; /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static InventoryMessage read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { return new InventoryMessage(readItems(payload)); } public InventoryMessage() { super(); } protected InventoryMessage(List<InventoryItem> items) { super(items); } public void addBlock(Block block) { addItem(new InventoryItem(InventoryItem.Type.BLOCK, block.getHash())); } public void addTransaction(Transaction tx) { addItem(new InventoryItem(InventoryItem.Type.TRANSACTION, tx.getTxId())); } /** Creates a new inv message for the given transactions. */ public static InventoryMessage with(Transaction... txns) { checkArgument(txns.length > 0); InventoryMessage result = new InventoryMessage(); for (Transaction tx : txns) result.addTransaction(tx); return result; } }
2,581
33.891892
119
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/TransactionOutputChanges.java
/* * Copyright 2012 Matt Corallo. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.internal.ByteUtils; import java.util.LinkedList; import java.util.List; /** * <p>TransactionOutputChanges represents a delta to the set of unspent outputs. It used as a return value for * {@link AbstractBlockChain#connectTransactions(int, Block)}. It contains the full list of transaction outputs created * and spent in a block. It DOES contain outputs created that were spent later in the block, as those are needed for * BIP30 (no duplicate txid creation if the previous one was not fully spent prior to this block) verification.</p> */ public class TransactionOutputChanges { public final List<UTXO> txOutsCreated; public final List<UTXO> txOutsSpent; public TransactionOutputChanges(List<UTXO> txOutsCreated, List<UTXO> txOutsSpent) { this.txOutsCreated = txOutsCreated; this.txOutsSpent = txOutsSpent; } }
1,505
37.615385
119
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/BitcoinSerializer.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.ByteUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import static org.bitcoinj.base.internal.ByteUtils.readUint32; import static org.bitcoinj.base.internal.Preconditions.check; /** * <p>Methods to serialize and de-serialize messages to the Bitcoin network format as defined in * <a href="https://en.bitcoin.it/wiki/Protocol_specification">the protocol specification</a>.</p> * * <p>To be able to serialize and deserialize new Message subclasses the following criteria needs to be met.</p> * * <ul> * <li>The proper Class instance needs to be mapped to its message name in the names variable below</li> * <li>There needs to be a constructor matching: NetworkParameters params, byte[] payload</li> * <li>Message.bitcoinSerializeToStream() needs to be properly subclassed</li> * </ul> */ public class BitcoinSerializer extends MessageSerializer { private static final Logger log = LoggerFactory.getLogger(BitcoinSerializer.class); private static final int COMMAND_LEN = 12; private final NetworkParameters params; private final int packetMagic; private final int protocolVersion; private static final Map<Class<? extends Message>, String> names = new HashMap<>(); static { names.put(VersionMessage.class, "version"); names.put(InventoryMessage.class, "inv"); names.put(Block.class, "block"); names.put(GetDataMessage.class, "getdata"); names.put(Transaction.class, "tx"); names.put(AddressV1Message.class, "addr"); names.put(AddressV2Message.class, "addrv2"); names.put(Ping.class, "ping"); names.put(Pong.class, "pong"); names.put(VersionAck.class, "verack"); names.put(GetBlocksMessage.class, "getblocks"); names.put(GetHeadersMessage.class, "getheaders"); names.put(GetAddrMessage.class, "getaddr"); names.put(SendAddrV2Message.class, "sendaddrv2"); names.put(HeadersMessage.class, "headers"); names.put(BloomFilter.class, "filterload"); names.put(FilteredBlock.class, "merkleblock"); names.put(NotFoundMessage.class, "notfound"); names.put(MemoryPoolMessage.class, "mempool"); names.put(RejectMessage.class, "reject"); names.put(SendHeadersMessage.class, "sendheaders"); names.put(FeeFilterMessage.class, "feefilter"); } /** * Constructs a BitcoinSerializer with the given behavior. * * @param params networkParams used to create Messages instances and determining packetMagic */ public BitcoinSerializer(NetworkParameters params) { this(params, ProtocolVersion.CURRENT.intValue()); } /** * Constructs a BitcoinSerializer with the given behavior. * * @param params networkParams used to create Messages instances and determining packetMagic * @param protocolVersion the protocol version to use */ public BitcoinSerializer(NetworkParameters params, int protocolVersion) { this.params = params; this.packetMagic = params.getPacketMagic(); this.protocolVersion = protocolVersion; } @Override public BitcoinSerializer withProtocolVersion(int protocolVersion) { return protocolVersion == this.protocolVersion ? this : new BitcoinSerializer(params, protocolVersion); } @Override public int getProtocolVersion() { return protocolVersion; } /** * Writes message to to the output stream. */ @Override public void serialize(String name, byte[] message, OutputStream out) throws IOException { byte[] header = new byte[4 + COMMAND_LEN + 4 + 4 /* checksum */]; ByteUtils.writeInt32BE(packetMagic, header, 0); // The header array is initialized to zero by Java so we don't have to worry about // NULL terminating the string here. for (int i = 0; i < name.length() && i < COMMAND_LEN; i++) { header[4 + i] = (byte) (name.codePointAt(i) & 0xFF); } ByteUtils.writeInt32LE(message.length, header, 4 + COMMAND_LEN); byte[] hash = Sha256Hash.hashTwice(message); System.arraycopy(hash, 0, header, 4 + COMMAND_LEN + 4, 4); out.write(header); out.write(message); if (log.isDebugEnabled()) log.debug("Sending {} message: {}", name, ByteUtils.formatHex(header) + ByteUtils.formatHex(message)); } /** * Writes message to to the output stream. */ @Override public void serialize(Message message, OutputStream out) throws IOException { String name = names.get(message.getClass()); if (name == null) { throw new Error("BitcoinSerializer doesn't currently know how to serialize " + message.getClass()); } serialize(name, message.serialize(), out); } /** * Reads a message from the given ByteBuffer and returns it. */ @Override public Message deserialize(ByteBuffer in) throws ProtocolException, IOException { // A Bitcoin protocol message has the following format. // // - 4 byte magic number: 0xfabfb5da for the testnet or // 0xf9beb4d9 for production // - 12 byte command in ASCII // - 4 byte payload size // - 4 byte checksum // - Payload data // // The checksum is the first 4 bytes of a SHA256 hash of the message payload. It isn't // present for all messages, notably, the first one on a connection. // // Bitcoin Core ignores garbage before the magic header bytes. We have to do the same because // sometimes it sends us stuff that isn't part of any message. seekPastMagicBytes(in); BitcoinPacketHeader header = new BitcoinPacketHeader(in); // Now try to read the whole message. return deserializePayload(header, in); } /** * Deserializes only the header in case packet meta data is needed before decoding * the payload. This method assumes you have already called seekPastMagicBytes() */ @Override public BitcoinPacketHeader deserializeHeader(ByteBuffer in) throws ProtocolException, IOException { return new BitcoinPacketHeader(in); } /** * Deserialize payload only. You must provide a header, typically obtained by calling * {@link BitcoinSerializer#deserializeHeader}. */ @Override public Message deserializePayload(BitcoinPacketHeader header, ByteBuffer in) throws ProtocolException, BufferUnderflowException { byte[] payloadBytes = new byte[header.size]; in.get(payloadBytes, 0, header.size); // Verify the checksum. byte[] hash; hash = Sha256Hash.hashTwice(payloadBytes); if (header.checksum[0] != hash[0] || header.checksum[1] != hash[1] || header.checksum[2] != hash[2] || header.checksum[3] != hash[3]) { throw new ProtocolException("Checksum failed to verify, actual " + ByteUtils.formatHex(hash) + " vs " + ByteUtils.formatHex(header.checksum)); } if (log.isDebugEnabled()) { log.debug("Received {} byte '{}' message: {}", header.size, header.command, ByteUtils.formatHex(payloadBytes)); } try { return makeMessage(header.command, payloadBytes, hash); } catch (Exception e) { throw new ProtocolException("Error deserializing message " + ByteUtils.formatHex(payloadBytes) + "\n", e); } } private Message makeMessage(String command, byte[] payloadBytes, byte[] hash) throws ProtocolException { ByteBuffer payload = ByteBuffer.wrap(payloadBytes); // We use an if ladder rather than reflection because reflection is very slow on Android. if (command.equals("version")) { return VersionMessage.read(payload); } else if (command.equals("inv")) { return makeInventoryMessage(payload); } else if (command.equals("block")) { return makeBlock(payload); } else if (command.equals("merkleblock")) { return makeFilteredBlock(payload); } else if (command.equals("getdata")) { return GetDataMessage.read(payload); } else if (command.equals("getblocks")) { return GetBlocksMessage.read(payload); } else if (command.equals("getheaders")) { return GetHeadersMessage.read(payload); } else if (command.equals("tx")) { return makeTransaction(payload); } else if (command.equals("sendaddrv2")) { check(!payload.hasRemaining(), ProtocolException::new); return new SendAddrV2Message(); } else if (command.equals("addr")) { return makeAddressV1Message(payload); } else if (command.equals("addrv2")) { return makeAddressV2Message(payload); } else if (command.equals("ping")) { return Ping.read(payload); } else if (command.equals("pong")) { return Pong.read(payload); } else if (command.equals("verack")) { check(!payload.hasRemaining(), ProtocolException::new); return new VersionAck(); } else if (command.equals("headers")) { return HeadersMessage.read(payload); } else if (command.equals("filterload")) { return makeBloomFilter(payload); } else if (command.equals("notfound")) { return NotFoundMessage.read(payload); } else if (command.equals("mempool")) { return new MemoryPoolMessage(); } else if (command.equals("reject")) { return RejectMessage.read(payload); } else if (command.equals("sendheaders")) { check(!payload.hasRemaining(), ProtocolException::new); return new SendHeadersMessage(); } else if (command.equals("feefilter")) { return FeeFilterMessage.read(payload); } else { check(!payload.hasRemaining(), ProtocolException::new); return new UnknownMessage(command); } } /** * Get the network parameters for this serializer. */ public NetworkParameters getParameters() { return params; } /** * Make an address message from the payload. Extension point for alternative * serialization format support. */ @Override public AddressV1Message makeAddressV1Message(ByteBuffer payload) throws ProtocolException { return AddressV1Message.read(payload); } /** * Make an address message from the payload. Extension point for alternative * serialization format support. */ @Override public AddressV2Message makeAddressV2Message(ByteBuffer payload) throws ProtocolException { return AddressV2Message.read(payload); } /** * Make a block from the payload. Extension point for alternative * serialization format support. */ @Override public Block makeBlock(ByteBuffer payload) throws ProtocolException { return Block.read(payload); } /** * Make an filter message from the payload. Extension point for alternative * serialization format support. */ @Override public Message makeBloomFilter(ByteBuffer payload) throws ProtocolException { return BloomFilter.read(payload); } /** * Make a filtered block from the payload. Extension point for alternative * serialization format support. */ @Override public FilteredBlock makeFilteredBlock(ByteBuffer payload) throws ProtocolException { return FilteredBlock.read(payload); } /** * Make an inventory message from the payload. Extension point for alternative * serialization format support. */ @Override public InventoryMessage makeInventoryMessage(ByteBuffer payload) throws ProtocolException { return InventoryMessage.read(payload); } /** * Make a transaction from the payload. Extension point for alternative * serialization format support. */ @Override public Transaction makeTransaction(ByteBuffer payload) throws ProtocolException { return Transaction.read(payload, protocolVersion); } @Override public void seekPastMagicBytes(ByteBuffer in) throws BufferUnderflowException { int magicCursor = 3; // Which byte of the magic we're looking for currently. while (true) { byte b = in.get(); // We're looking for a run of bytes that is the same as the packet magic but we want to ignore partial // magics that aren't complete. So we keep track of where we're up to with magicCursor. byte expectedByte = (byte)(0xFF & packetMagic >>> (magicCursor * 8)); if (b == expectedByte) { magicCursor--; if (magicCursor < 0) { // We found the magic sequence. return; } else { // We still have further to go to find the next message. } } else { magicCursor = 3; } } } public static class BitcoinPacketHeader { /** The largest number of bytes that a header can represent */ public static final int HEADER_LENGTH = COMMAND_LEN + 4 + 4; public final byte[] header; public final String command; public final int size; public final byte[] checksum; public BitcoinPacketHeader(ByteBuffer in) throws ProtocolException, BufferUnderflowException { header = new byte[HEADER_LENGTH]; in.get(header, 0, header.length); int cursor = 0; // The command is a NULL terminated string, unless the command fills all twelve bytes // in which case the termination is implicit. for (; header[cursor] != 0 && cursor < COMMAND_LEN; cursor++) ; byte[] commandBytes = new byte[cursor]; System.arraycopy(header, 0, commandBytes, 0, cursor); command = new String(commandBytes, StandardCharsets.US_ASCII); cursor = COMMAND_LEN; size = (int) readUint32(header, cursor); cursor += 4; if (size > Message.MAX_SIZE || size < 0) throw new ProtocolException("Message size too large: " + size); // Old clients don't send the checksum. checksum = new byte[4]; // Note that the size read above includes the checksum bytes. System.arraycopy(header, cursor, checksum, 0, 4); } } }
15,723
38.31
133
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/FeeFilterMessage.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Coin; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import static org.bitcoinj.base.internal.Preconditions.check; /** * Represents a "feefilter" message on the P2P network, which instructs a peer to filter transaction invs for * transactions that fall below the feerate provided. * <p> * See <a href="https://github.com/bitcoin/bips/blob/master/bip-0133.mediawiki">BIP133</a> for details. * <p> * Instances of this class are immutable. */ public class FeeFilterMessage extends BaseMessage { private final Coin feeRate; /** * Create a fee filter message with a given fee rate. * * @param feeRate fee rate * @return fee filter message */ public static FeeFilterMessage of(Coin feeRate) { return new FeeFilterMessage(feeRate); } /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static FeeFilterMessage read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { Coin feeRate = Coin.read(payload); check(feeRate.signum() >= 0, () -> new ProtocolException("fee rate out of range: " + feeRate)); return new FeeFilterMessage(feeRate); } private FeeFilterMessage(Coin feeRate) { this.feeRate = feeRate; } @Override protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { stream.write(feeRate.serialize()); } /** * Gets the fee rate. * * @return fee rate */ public Coin feeRate() { return feeRate; } /** * @deprecated use {@link #feeRate()} */ @Deprecated public Coin getFeeRate() { return feeRate(); } @Override public String toString() { return "feefilter: " + feeRate.toFriendlyString() + "/kB"; } }
2,736
28.430108
112
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/UnknownMessage.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; /** * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class UnknownMessage extends EmptyMessage { private final String name; public UnknownMessage(String name) throws ProtocolException { super(); this.name = name; } @Override public String toString() { return "Unknown message [" + name + "]"; } }
1,046
27.297297
75
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/NotFoundMessage.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** * <p>Sent by a peer when a getdata request doesn't find the requested data in the mempool. It has the same format * as an inventory message and lists the hashes of the missing items.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class NotFoundMessage extends InventoryMessage { public static int MIN_PROTOCOL_VERSION = 70001; /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static NotFoundMessage read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { return new NotFoundMessage(readItems(payload)); } public NotFoundMessage() { super(); } public NotFoundMessage(List<InventoryItem> items) { super(new ArrayList<>(items)); } }
1,747
32.615385
114
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/ProtocolException.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; @SuppressWarnings("serial") public class ProtocolException extends VerificationException { public ProtocolException() { super(); } public ProtocolException(String msg) { super(msg); } public ProtocolException(Exception e) { super(e); } public ProtocolException(String msg, Exception e) { super(msg, e); } }
997
25.972973
75
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/UTXOProvider.java
/* * Copyright 2014 Kalpesh Parmar. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Network; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.store.FullPrunedBlockStore; import java.util.List; /** * A UTXOProvider encapsulates functionality for returning unspent transaction outputs, * for use by the wallet or other code that crafts spends. * * <p>A {@link FullPrunedBlockStore} is an internal implementation within bitcoinj.</p> */ public interface UTXOProvider { /** * Get the list of {@link UTXO}'s for given keys. * @param keys List of keys. * @return The list of transaction outputs. * @throws UTXOProviderException If there is an error. */ List<UTXO> getOpenTransactionOutputs(List<ECKey> keys) throws UTXOProviderException; /** * Get the height of the chain head. * @return The chain head height. * @throws UTXOProviderException If there is an error. */ int getChainHeadHeight() throws UTXOProviderException; /** * The {@link Network} of this provider. * @return the network */ Network network(); }
1,673
30.584906
88
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/TransactionBag.java
/* * Copyright 2014 Giannis Dzegoutanis * Copyright 2019 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.script.Script; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.WalletTransaction; import javax.annotation.Nullable; import java.util.Map; /** * This interface is used to abstract the {@link Wallet} and the {@link Transaction} */ public interface TransactionBag { /** * Look for a public key which hashes to the given hash and (optionally) is used for a specific script type. * @param pubKeyHash hash of the public key to look for * @param scriptType only look for given usage (currently {@link ScriptType#P2PKH} or {@link ScriptType#P2WPKH}) or {@code null} if we don't care * @return true if hash was found */ boolean isPubKeyHashMine(byte[] pubKeyHash, @Nullable ScriptType scriptType); /** Returns true if this wallet is watching transactions for outputs with the script. */ boolean isWatchedScript(Script script); /** Returns true if this wallet contains a keypair with the given public key. */ boolean isPubKeyMine(byte[] pubKey); /** Returns true if this wallet knows the script corresponding to the given hash. */ boolean isPayToScriptHashMine(byte[] payToScriptHash); /** Returns transactions from a specific pool. */ Map<Sha256Hash, Transaction> getTransactionPool(WalletTransaction.Pool pool); }
2,055
37.792453
149
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/PartialMerkleTree.java
/* * Copyright 2012 The Bitcoin Developers * Copyright 2012 Matt Corallo * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.Buffers; import org.bitcoinj.base.internal.ByteUtils; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import static org.bitcoinj.base.internal.ByteUtils.checkBitLE; import static org.bitcoinj.base.internal.ByteUtils.reverseBytes; import static org.bitcoinj.base.internal.ByteUtils.writeInt32LE; import static org.bitcoinj.base.internal.Preconditions.check; /** * <p>A data structure that contains proofs of block inclusion for one or more transactions, in an efficient manner.</p> * * <p>The encoding works as follows: we traverse the tree in depth-first order, storing a bit for each traversed node, * signifying whether the node is the parent of at least one matched leaf txid (or a matched txid itself). In case we * are at the leaf level, or this bit is 0, its merkle node hash is stored, and its children are not explored further. * Otherwise, no hash is stored, but we recurse into both (or the only) child branch. During decoding, the same * depth-first traversal is performed, consuming bits and hashes as they were written during encoding.</p> * * <p>The serialization is fixed and provides a hard guarantee about the encoded size, * {@code SIZE <= 10 + ceil(32.25*N)} where N represents the number of leaf nodes of the partial tree. N itself * is bounded by:</p> * * <p> * N &lt;= total_transactions<br> * N &lt;= 1 + matched_transactions*tree_height * </p> * * <p>The serialization format:</p> * <pre> * - uint32 total_transactions (4 bytes) * - varint number of hashes (1-3 bytes) * - uint256[] hashes in depth-first order (&lt;= 32*N bytes) * - varint number of bytes of flag bits (1-3 bytes) * - byte[] flag bits, packed per 8 in a byte, least significant bit first (&lt;= 2*N-1 bits) * </pre> * <p>The size constraints follow from this.</p> */ public class PartialMerkleTree { // the total number of transactions in the block private final int transactionCount; // txids and internal hashes private final List<Sha256Hash> hashes; // node-is-parent-of-matched-txid bits private final byte[] matchedChildBits; /** * Deserialize a partial merkle tree from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static PartialMerkleTree read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { int transactionCount = (int) ByteUtils.readUint32(payload); VarInt nHashesVarInt = VarInt.read(payload); check(nHashesVarInt.fitsInt(), BufferUnderflowException::new); int nHashes = nHashesVarInt.intValue(); List<Sha256Hash> hashes = new ArrayList<>(Math.min(nHashes, Utils.MAX_INITIAL_ARRAY_LENGTH)); for (int i = 0; i < nHashes; i++) hashes.add(Sha256Hash.read(payload)); byte[] matchedChildBits = Buffers.readLengthPrefixedBytes(payload); return new PartialMerkleTree(transactionCount, hashes, matchedChildBits); } /** * Constructs a new PMT with the given bit set (little endian) and the raw list of hashes including internal hashes, * taking ownership of the list. */ public PartialMerkleTree(int origTxCount, List<Sha256Hash> hashes, byte[] bits) { this.transactionCount = origTxCount; this.hashes = Objects.requireNonNull(hashes); this.matchedChildBits = Objects.requireNonNull(bits); } /** * 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. */ public static PartialMerkleTree buildFromLeaves(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)) ByteUtils.setBitLE(bits, i); return new PartialMerkleTree(allLeafHashes.size(), hashes, bits); } /** * Write this partial merkle tree into the given buffer. * * @param buf buffer to write into * @return the buffer * @throws BufferOverflowException if the partial merkle tree doesn't fit the remaining buffer */ public ByteBuffer write(ByteBuffer buf) throws BufferOverflowException { writeInt32LE(transactionCount, buf); VarInt.of(hashes.size()).write(buf); for (Sha256Hash hash : hashes) hash.write(buf); Buffers.writeLengthPrefixedBytes(buf, matchedChildBits); return buf; } /** * Allocates a byte array and writes this partial merkle tree into it. * * @return byte array containing the partial merkle tree */ public byte[] serialize() { return write(ByteBuffer.allocate(getMessageSize())).array(); } /** * Return the size of the serialized message. Note that if the message was deserialized from a payload, this * size can differ from the size of the original payload. * * @return size of the serialized message in bytes */ public int getMessageSize() { int size = Integer.BYTES; // transactionCount size += VarInt.sizeOf(hashes.size()); size += hashes.size() * Sha256Hash.LENGTH; size += VarInt.sizeOf(matchedChildBits.length) + matchedChildBits.length; return size; } // Based on CPartialMerkleTree::TraverseAndBuild in Bitcoin Core. private static void traverseAndBuild(int height, int pos, List<Sha256Hash> allLeafHashes, byte[] includeBits, List<Boolean> matchedChildBits, List<Sha256Hash> resultHashes) { boolean parentOfMatch = false; // Is this node a parent of at least one matched hash? for (int p = pos << height; p < (pos+1) << height && p < allLeafHashes.size(); p++) { if (ByteUtils.checkBitLE(includeBits, p)) { parentOfMatch = true; break; } } // Store as a flag bit. matchedChildBits.add(parentOfMatch); if (height == 0 || !parentOfMatch) { // If at height 0, or nothing interesting below, store hash and stop. resultHashes.add(calcHash(height, pos, allLeafHashes)); } else { // Otherwise descend into the subtrees. int h = height - 1; int p = pos * 2; traverseAndBuild(h, p, allLeafHashes, includeBits, matchedChildBits, resultHashes); if (p + 1 < getTreeWidth(allLeafHashes.size(), h)) traverseAndBuild(h, p + 1, allLeafHashes, includeBits, matchedChildBits, resultHashes); } } private static Sha256Hash calcHash(int height, int pos, List<Sha256Hash> hashes) { if (height == 0) { // Hash at height 0 is just the regular tx hash itself. return hashes.get(pos); } int h = height - 1; int p = pos * 2; Sha256Hash left = calcHash(h, p, hashes); // Calculate right hash if not beyond the end of the array - copy left hash otherwise. Sha256Hash right; if (p + 1 < getTreeWidth(hashes.size(), h)) { right = calcHash(h, p + 1, hashes); } else { right = left; } return combineLeftRight(left.getBytes(), right.getBytes()); } // helper function to efficiently calculate the number of nodes at given height in the merkle tree private static int getTreeWidth(int transactionCount, int height) { return (transactionCount + (1 << height) - 1) >> height; } private static class ValuesUsed { public int bitsUsed = 0, hashesUsed = 0; } // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild. // it returns the hash of the respective node. 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 static Sha256Hash combineLeftRight(byte[] left, byte[] right) { return Sha256Hash.wrapReversed(Sha256Hash.hashTwice(reverseBytes(left), reverseBytes(right))); } /** * 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 */ 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 int getTransactionCount() { return transactionCount; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PartialMerkleTree other = (PartialMerkleTree) o; return transactionCount == other.transactionCount && hashes.equals(other.hashes) && Arrays.equals(matchedChildBits, other.matchedChildBits); } @Override public int hashCode() { return Objects.hash(transactionCount, hashes, Arrays.hashCode(matchedChildBits)); } @Override public String toString() { return "PartialMerkleTree{" + "transactionCount=" + transactionCount + ", matchedChildBits=" + Arrays.toString(matchedChildBits) + ", hashes=" + hashes + '}'; } }
14,444
43.721362
146
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/TransactionConfidence.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.collect.Iterators; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.utils.ListenableCompletableFuture; import org.bitcoinj.utils.ListenerRegistration; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.CoinSelector; import org.bitcoinj.wallet.Wallet; import javax.annotation.Nullable; import java.time.Instant; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import static org.bitcoinj.base.internal.Preconditions.checkState; // TODO: Modify the getDepthInBlocks method to require the chain height to be specified, in preparation for ceasing to touch every tx on every block. /** * <p>A TransactionConfidence object tracks data you can use to make a confidence decision about a transaction. * It also contains some pre-canned rules for common scenarios: if you aren't really sure what level of confidence * you need, these should prove useful. You can get a confidence object using {@link Transaction#getConfidence()}. * They cannot be constructed directly.</p> * * <p>Confidence in a transaction can come in multiple ways:</p> * * <ul> * <li>Because you created it yourself and only you have the necessary keys.</li> * <li>Receiving it from a fully validating peer you know is trustworthy, for instance, because it's run by yourself.</li> * <li>Receiving it from a peer on the network you randomly chose. If your network connection is not being * intercepted, you have a pretty good chance of connecting to a node that is following the rules.</li> * <li>Receiving it from multiple peers on the network. If your network connection is not being intercepted, * hearing about a transaction from multiple peers indicates the network has accepted the transaction and * thus miners likely have too (miners have the final say in whether a transaction becomes valid or not).</li> * <li>Seeing the transaction appear in a block on the best chain. Your confidence increases as the transaction * becomes further buried under work. Work can be measured either in blocks (roughly, units of time), or * amount of work done.</li> * </ul> * * <p>Alternatively, you may know that the transaction is "dead", that is, one or more of its inputs have * been double spent and will never confirm unless there is another re-org.</p> * * <p>TransactionConfidence is updated via the {@link TransactionConfidence#incrementDepthInBlocks()} * method to ensure the block depth is up to date.</p> * To make a copy that won't be changed, use {@link TransactionConfidence#duplicate()}. */ public class TransactionConfidence { public static class Factory { public TransactionConfidence createConfidence(Sha256Hash hash) { return new TransactionConfidence(hash); } } /** * The peers that have announced the transaction to us. Network nodes don't have stable identities, so we use * IP address as an approximation. It's obviously vulnerable to being gamed if we allow arbitrary people to connect * to us, so only peers we explicitly connected to should go here. */ private CopyOnWriteArrayList<PeerAddress> broadcastBy; /** The time the transaction was last announced to us, or {@code null} if unknown. */ @Nullable private Instant lastBroadcastTime = null; /** The Transaction that this confidence object is associated with. */ private final Sha256Hash hash; // Lazily created listeners array. private CopyOnWriteArrayList<ListenerRegistration<Listener>> listeners; // The depth of the transaction on the best chain in blocks. An unconfirmed block has depth 0. private int depth; /** Describes the state of the transaction in general terms. Properties can be read to learn specifics. */ public enum ConfidenceType { /** If BUILDING, then the transaction is included in the best chain and your confidence in it is increasing. */ BUILDING(1), /** * If PENDING, then the transaction is unconfirmed and should be included shortly, as long as it is being * announced and is considered valid by the network. A pending transaction will be announced if the containing * wallet has been attached to a live {@link PeerGroup} using {@link PeerGroup#addWallet(Wallet)}. * You can estimate how likely the transaction is to be included by connecting to a bunch of nodes then measuring * how many announce it, using {@link TransactionConfidence#numBroadcastPeers()}. * Or if you saw it from a trusted peer, you can assume it's valid and will get mined sooner or later as well. */ PENDING(2), /** * If DEAD, then it means the transaction won't confirm unless there is another re-org, * because some other transaction is spending one of its inputs. Such transactions should be alerted to the user * so they can take action, eg, suspending shipment of goods if they are a merchant. * It can also mean that a coinbase transaction has been made dead from it being moved onto a side chain. */ DEAD(4), /** * If IN_CONFLICT, then it means there is another transaction (or several other transactions) spending one * (or several) of its inputs but nor this transaction nor the other/s transaction/s are included in the best chain. * The other/s transaction/s should be IN_CONFLICT too. * IN_CONFLICT can be thought as an intermediary state between a) PENDING and BUILDING or b) PENDING and DEAD. * Another common name for this situation is "double spend". */ IN_CONFLICT(5), /** * If a transaction hasn't been broadcast yet, or there's no record of it, its confidence is UNKNOWN. */ UNKNOWN(0); private final int value; ConfidenceType(int value) { this.value = value; } public int getValue() { return value; } } private ConfidenceType confidenceType = ConfidenceType.UNKNOWN; private int appearedAtChainHeight = -1; // The transaction that double spent this one, if any. private Transaction overridingTransaction; /** * Information about where the transaction was first seen (network, sent direct from peer, created by ourselves). * Useful for risk analyzing pending transactions. Probably not that useful after a tx is included in the chain, * unless re-org double spends start happening frequently. */ public enum Source { /** We don't know where the transaction came from. */ UNKNOWN, /** We got this transaction from a network peer. */ NETWORK, /** This transaction was created by our own wallet, so we know it's not a double spend. */ SELF } private Source source = Source.UNKNOWN; public TransactionConfidence(Sha256Hash hash) { // Assume a default number of peers for our set. broadcastBy = new CopyOnWriteArrayList<>(); listeners = new CopyOnWriteArrayList<>(); this.hash = hash; } /** * <p>A confidence listener is informed when the level of {@link TransactionConfidence} is updated by something, like * for example a {@link Wallet}. You can add listeners to update your user interface or manage your order tracking * system when confidence levels pass a certain threshold. <b>Note that confidence can go down as well as up.</b> * For example, this can happen if somebody is doing a double-spend attack against you. Whilst it's unlikely, your * code should be able to handle that in order to be correct.</p> * * <p>During listener execution, it's safe to remove the current listener but not others.</p> */ public interface Listener { /** An enum that describes why a transaction confidence listener is being invoked (i.e. the class of change). */ enum ChangeReason { /** * Occurs when the type returned by {@link TransactionConfidence#getConfidenceType()} * has changed. For example, if a PENDING transaction changes to BUILDING or DEAD, then this reason will * be given. It's a high level summary. */ TYPE, /** * Occurs when a transaction that is in the best known block chain gets buried by another block. If you're * waiting for a certain number of confirmations, this is the reason to watch out for. */ DEPTH, /** * Occurs when a pending transaction (not in the chain) was announced by another connected peers. By * watching the number of peers that announced a transaction go up, you can see whether it's being * accepted by the network or not. If all your peers announce, it's a pretty good bet the transaction * is considered relayable and has thus reached the miners. */ SEEN_PEERS, } void onConfidenceChanged(TransactionConfidence confidence, ChangeReason reason); } // This is used to ensure that confidence objects which aren't referenced from anywhere but which have an event // listener set on them don't become eligible for garbage collection. Otherwise the TxConfidenceTable, which only // has weak references to these objects, would not be enough to keep the event listeners working as transactions // propagate around the network - it cannot know directly if the API user is interested in the object, so it uses // heap reachability as a proxy for interest. // // We add ourselves to this set when a listener is added and remove ourselves when the listener list is empty. private static final Set<TransactionConfidence> pinnedConfidenceObjects = Collections.synchronizedSet(new HashSet<TransactionConfidence>()); /** * <p>Adds an event listener that will be run when this confidence object is updated. The listener will be locked and * is likely to be invoked on a peer thread.</p> * * <p>Note that this is NOT called when every block arrives. Instead it is called when the transaction * transitions between confidence states, ie, from not being seen in the chain to being seen (not necessarily in * the best chain). If you want to know when the transaction gets buried under another block, consider using * a future from {@link #getDepthFuture(int)}.</p> */ public void addEventListener(Executor executor, Listener listener) { Objects.requireNonNull(listener); listeners.addIfAbsent(new ListenerRegistration<>(listener, executor)); pinnedConfidenceObjects.add(this); } /** * <p>Adds an event listener that will be run when this confidence object is updated. The listener will be locked and * is likely to be invoked on a peer thread.</p> * * <p>Note that this is NOT called when every block arrives. Instead it is called when the transaction * transitions between confidence states, ie, from not being seen in the chain to being seen (not necessarily in * the best chain). If you want to know when the transaction gets buried under another block, implement * {@link org.bitcoinj.core.listeners.NewBestBlockListener} and related listeners, attach them to a * {@link BlockChain} and then use the getters on the confidence object to determine the new depth.</p> */ public void addEventListener(Listener listener) { addEventListener(Threading.USER_THREAD, listener); } public boolean removeEventListener(Listener listener) { Objects.requireNonNull(listener); boolean removed = ListenerRegistration.removeFromList(listener, listeners); if (listeners.isEmpty()) pinnedConfidenceObjects.remove(this); return removed; } /** * Returns the chain height at which the transaction appeared if confidence type is BUILDING. * @throws IllegalStateException if the confidence type is not BUILDING. */ public synchronized int getAppearedAtChainHeight() { if (getConfidenceType() != ConfidenceType.BUILDING) throw new IllegalStateException("Confidence type is " + getConfidenceType() + ", not BUILDING"); return appearedAtChainHeight; } /** * The chain height at which the transaction appeared, if it has been seen in the best chain. Automatically sets * the current type to {@link ConfidenceType#BUILDING} and depth to one. */ public synchronized void setAppearedAtChainHeight(int appearedAtChainHeight) { if (appearedAtChainHeight < 0) throw new IllegalArgumentException("appearedAtChainHeight out of range"); this.appearedAtChainHeight = appearedAtChainHeight; this.depth = 1; setConfidenceType(ConfidenceType.BUILDING); } /** * Returns a general statement of the level of confidence you can have in this transaction. */ public synchronized ConfidenceType getConfidenceType() { return confidenceType; } /** * Called by other objects in the system, like a {@link Wallet}, when new information about the confidence of a * transaction becomes available. */ public synchronized void setConfidenceType(ConfidenceType confidenceType) { if (confidenceType == this.confidenceType) return; this.confidenceType = confidenceType; if (confidenceType != ConfidenceType.DEAD) { overridingTransaction = null; } if (confidenceType == ConfidenceType.PENDING || confidenceType == ConfidenceType.IN_CONFLICT) { depth = 0; appearedAtChainHeight = -1; } } /** * Called by a {@link Peer} when a transaction is pending and announced by a peer. The more peers announce the * transaction, the more peers have validated it (assuming your internet connection is not being intercepted). * If confidence is currently unknown, sets it to {@link ConfidenceType#PENDING}. Does not run listeners. * * @param address IP address of the peer, used as a proxy for identity. * @return true if marked, false if this address was already seen */ public boolean markBroadcastBy(PeerAddress address) { lastBroadcastTime = TimeUtils.currentTime(); if (!broadcastBy.addIfAbsent(address)) return false; // Duplicate. synchronized (this) { if (getConfidenceType() == ConfidenceType.UNKNOWN) { this.confidenceType = ConfidenceType.PENDING; } } return true; } /** * Returns how many peers have been passed to {@link TransactionConfidence#markBroadcastBy}. */ public int numBroadcastPeers() { return broadcastBy.size(); } /** * Returns a snapshot of {@link PeerAddress}es that announced the transaction. */ public Set<PeerAddress> getBroadcastBy() { Set<PeerAddress> broadcastBySet = new HashSet<>(); Iterators.addAll(broadcastBySet, broadcastBy.listIterator()); return broadcastBySet; } /** Returns true if the given address has been seen via markBroadcastBy() */ public boolean wasBroadcastBy(PeerAddress address) { return broadcastBy.contains(address); } /** * Return the time the transaction was last announced to us, or empty if unknown. * @return time the transaction was last announced to us, or empty if unknown */ public Optional<Instant> lastBroadcastTime() { return Optional.ofNullable(lastBroadcastTime); } /** @deprecated use {@link #lastBroadcastTime()} */ @Deprecated @Nullable public Date getLastBroadcastedAt() { return lastBroadcastTime != null ? Date.from(lastBroadcastTime) : null; } /** * Set the time the transaction was last announced to us. * @param lastBroadcastTime time the transaction was last announced to us */ public void setLastBroadcastTime(Instant lastBroadcastTime) { this.lastBroadcastTime = Objects.requireNonNull(lastBroadcastTime); } /** @deprecated use {@link #setLastBroadcastTime(Instant)} */ @Deprecated public void setLastBroadcastedAt(Date lastBroadcastedAt) { setLastBroadcastTime(lastBroadcastedAt.toInstant()); } @Override public synchronized String toString() { StringBuilder builder = new StringBuilder(); int peers = numBroadcastPeers(); if (peers > 0) { builder.append("Seen by ").append(peers).append(peers > 1 ? " peers" : " peer"); if (lastBroadcastTime != null) builder.append(" (most recently: ").append(TimeUtils.dateTimeFormat(lastBroadcastTime)).append(")"); builder.append(". "); } switch (getConfidenceType()) { case UNKNOWN: builder.append("Unknown confidence level."); break; case DEAD: builder.append("Dead: overridden by double spend and will not confirm."); break; case PENDING: builder.append("Pending/unconfirmed."); break; case IN_CONFLICT: builder.append("In conflict."); break; case BUILDING: builder.append(String.format(Locale.US, "Appeared in best chain at height %d, depth %d.", getAppearedAtChainHeight(), getDepthInBlocks())); break; } if (source != Source.UNKNOWN) builder.append(" Source: ").append(source); return builder.toString(); } /** * Called by the wallet when the tx appears on the best chain and a new block is added to the top. Updates the * internal counter that tracks how deeply buried the block is. * * @return the new depth */ public synchronized int incrementDepthInBlocks() { return ++this.depth; } /** * <p>Depth in the chain is an approximation of how much time has elapsed since the transaction has been confirmed. * On average there is supposed to be a new block every 10 minutes, but the actual rate may vary. Bitcoin Core * considers a transaction impractical to reverse after 6 blocks, but as of EOY 2011 network * security is high enough that often only one block is considered enough even for high value transactions. For low * value transactions like songs, or other cheap items, no blocks at all may be necessary.</p> * * <p>If the transaction appears in the top block, the depth is one. If it's anything else (pending, dead, unknown) * the depth is zero.</p> */ public synchronized int getDepthInBlocks() { return depth; } /* * Set the depth in blocks. Having one block confirmation is a depth of one. */ public synchronized void setDepthInBlocks(int depth) { this.depth = depth; } /** * Erases the set of broadcast/seen peers. This cannot be called whilst the confidence is PENDING. It is useful * for saving memory and wallet space once a tx is buried so deep it doesn't seem likely to go pending again. */ public void clearBroadcastBy() { checkState(getConfidenceType() != ConfidenceType.PENDING); broadcastBy.clear(); lastBroadcastTime = null; } /** * If this transaction has been overridden by a double spend (is dead), this call returns the overriding transaction. * Note that this call <b>can return null</b> if you have migrated an old wallet, as pre-Jan 2012 wallets did not * store this information. * * @return the transaction that double spent this one * @throws IllegalStateException if confidence type is not DEAD. */ public synchronized Transaction getOverridingTransaction() { if (getConfidenceType() != ConfidenceType.DEAD) throw new IllegalStateException("Confidence type is " + getConfidenceType() + ", not DEAD"); return overridingTransaction; } /** * Called when the transaction becomes newly dead, that is, we learn that one of its inputs has already been spent * in such a way that the double-spending transaction takes precedence over this one. It will not become valid now * unless there is a re-org. Automatically sets the confidence type to DEAD. The overriding transaction may not * directly double spend this one, but could also have double spent a dependency of this tx. */ public synchronized void setOverridingTransaction(@Nullable Transaction overridingTransaction) { this.overridingTransaction = overridingTransaction; setConfidenceType(ConfidenceType.DEAD); } /** Returns a copy of this object. Event listeners are not duplicated. */ public TransactionConfidence duplicate() { TransactionConfidence c = new TransactionConfidence(hash); c.broadcastBy.addAll(broadcastBy); c.lastBroadcastTime = lastBroadcastTime; synchronized (this) { c.confidenceType = confidenceType; c.overridingTransaction = overridingTransaction; c.appearedAtChainHeight = appearedAtChainHeight; } return c; } /** * Call this after adjusting the confidence, for cases where listeners should be notified. This has to be done * explicitly rather than being done automatically because sometimes complex changes to transaction states can * result in a series of confidence changes that are not really useful to see separately. By invoking listeners * explicitly, more precise control is available. Note that this will run the listeners on the user code thread. */ public void queueListeners(final Listener.ChangeReason reason) { for (final ListenerRegistration<Listener> registration : listeners) { registration.executor.execute(() -> registration.listener.onConfidenceChanged(TransactionConfidence.this, reason)); } } /** * The source of a transaction tries to identify where it came from originally. For instance, did we download it * from the peer to peer network, or make it ourselves, or receive it via Bluetooth, or import it from another app, * and so on. This information is useful for {@link CoinSelector} implementations to risk analyze * transactions and decide when to spend them. */ public synchronized Source getSource() { return source; } /** * The source of a transaction tries to identify where it came from originally. For instance, did we download it * from the peer to peer network, or make it ourselves, or receive it via Bluetooth, or import it from another app, * and so on. This information is useful for {@link CoinSelector} implementations to risk analyze * transactions and decide when to spend them. */ public synchronized void setSource(Source source) { this.source = source; } /** * Returns a future that completes when the transaction has been confirmed by "depth" blocks. For instance setting * depth to one will wait until it appears in a block on the best chain, and zero will wait until it has been seen * on the network. */ public synchronized ListenableCompletableFuture<TransactionConfidence> getDepthFuture(final int depth, Executor executor) { final ListenableCompletableFuture<TransactionConfidence> result = new ListenableCompletableFuture<>(); if (getDepthInBlocks() >= depth) { result.complete(this); } addEventListener(executor, new Listener() { @Override public void onConfidenceChanged(TransactionConfidence confidence, ChangeReason reason) { if (getDepthInBlocks() >= depth) { removeEventListener(this); result.complete(confidence); } } }); return result; } public synchronized ListenableCompletableFuture<TransactionConfidence> getDepthFuture(final int depth) { return getDepthFuture(depth, Threading.USER_THREAD); } public Sha256Hash getTransactionHash() { return hash; } }
25,396
45.6
149
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/Utils.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.base.internal.InternalUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; /** * A collection of various utility methods that are helpful for working with the Bitcoin protocol. * To enable debug logging from the library, run with -Dbitcoinj.logging=true on your command line. */ public class Utils { /** * Joiner for concatenating words with a space inbetween. * @deprecated Use @link java.util.StringJoiner} or a direct Guava dependency */ @Deprecated public static final Joiner SPACE_JOINER = Joiner.on(" "); /** * Splitter for splitting words on whitespaces. * @deprecated Use {@link java.lang.String#split(String)} or a direct Guava dependency */ @Deprecated public static final Splitter WHITESPACE_SPLITTER = Splitter.on(Pattern.compile("\\s+")); /** * Max initial size of variable length arrays and ArrayLists that could be attacked. * Avoids this attack: Attacker sends a msg indicating it will contain a huge number (eg 2 billion) elements (eg transaction inputs) and * forces bitcoinj to try to allocate a huge piece of the memory resulting in OutOfMemoryError. */ public static final int MAX_INITIAL_ARRAY_LENGTH = 20; private static final Logger log = LoggerFactory.getLogger(Utils.class); public static String toString(List<byte[]> stack) { List<String> parts = new ArrayList<>(stack.size()); for (byte[] push : stack) parts.add('[' + ByteUtils.formatHex(push) + ']'); return InternalUtils.SPACE_JOINER.join(parts); } }
2,468
35.850746
140
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/Ping.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.internal.ByteUtils; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.Random; /** * See <a href="https://github.com/bitcoin/bips/blob/master/bip-0031.mediawiki">BIP31</a> for details. * <p> * Instances of this class are immutable. */ public class Ping extends BaseMessage { private final long nonce; /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static Ping read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { return new Ping(ByteUtils.readInt64(payload)); } /** * Create a ping with a nonce value. * Only use this if the remote node has a protocol version greater than 60000 * * @param nonce nonce value * @return ping message */ public static Ping of(long nonce) { return new Ping(nonce); } /** * Create a ping with a random nonce value. * Only use this if the remote node has a protocol version greater than 60000 * * @return ping message */ public static Ping random() { long nonce = new Random().nextLong(); return new Ping(nonce); } private Ping(long nonce) { this.nonce = nonce; } @Override public void bitcoinSerializeToStream(OutputStream stream) throws IOException { ByteUtils.writeInt64LE(nonce, stream); } /** @deprecated returns true */ @Deprecated public boolean hasNonce() { return true; } public long nonce() { return nonce; } /** * Create a {@link Pong} reply to this ping. * * @return pong message */ public Pong pong() { return Pong.of(nonce); } }
2,632
26.427083
109
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/AddressV1Message.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.InternalUtils; import org.bitcoinj.net.discovery.PeerDiscovery; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.List; /** * Represents an "addr" message on the P2P network, which contains broadcast IP addresses of other peers. This is * one of the ways peers can find each other without using the {@link PeerDiscovery} mechanism. * <p> * Instances of this class are not safe for use by multiple threads. */ public class AddressV1Message extends AddressMessage { /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static AddressV1Message read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { return new AddressV1Message(readAddresses(payload, 1)); } private AddressV1Message(List<PeerAddress> addresses) { super(addresses); } public void addAddress(PeerAddress address) { addresses.add(address); } @Override protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { if (addresses == null) return; stream.write(VarInt.of(addresses.size()).serialize()); for (PeerAddress addr : addresses) { stream.write(addr.serialize(1)); } } @Override public String toString() { return "addr: " + InternalUtils.SPACE_JOINER.join(addresses); } }
2,367
32.352113
113
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/BlockLocator.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.InternalUtils; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Represents Block Locator in GetBlocks and GetHeaders messages **/ public final class BlockLocator { private final List<Sha256Hash> hashes; // unmodifiable list public BlockLocator() { hashes = Collections.emptyList(); } /** * Creates a Block locator with defined list of hashes. */ public BlockLocator(List<Sha256Hash> hashes) { this.hashes = Collections.unmodifiableList(hashes); } // Create a new BlockLocator by copying an instance and appending an element private BlockLocator(BlockLocator old, Sha256Hash hashToAdd) { this(Stream.concat(old.hashes.stream(), Stream.of(hashToAdd)) .collect(Collectors.toList()) ); } /** * Add a {@link Sha256Hash} to a newly created block locator. */ public BlockLocator add(Sha256Hash hash) { return new BlockLocator(this, hash); } /** * Returns the number of hashes in this block locator. */ public int size() { return hashes.size(); } /** * Returns List of Block locator hashes. */ public List<Sha256Hash> getHashes() { return hashes; } /** * Get hash by index from this block locator. */ public Sha256Hash get(int i) { return hashes.get(i); } @Override public String toString() { return "Block locator with " + size() + " blocks\n " + InternalUtils.SPACE_JOINER.join(hashes); } @Override public int hashCode() { int hashCode = 0; for (Sha256Hash i : hashes) { hashCode ^= i.hashCode(); } return hashCode; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return ((BlockLocator) o).getHashes().equals(hashes); } }
2,740
26.41
103
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/InsufficientMoneyException.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Coin; import javax.annotation.Nullable; import java.util.Objects; /** * Thrown to indicate that you don't have enough money available to perform the requested operation. */ public class InsufficientMoneyException extends Exception { /** Contains the number of satoshis that would have been required to complete the operation. */ @Nullable public final Coin missing; protected InsufficientMoneyException() { this.missing = null; } public InsufficientMoneyException(Coin missing) { this(missing, "Insufficient money, missing " + missing.toFriendlyString()); } public InsufficientMoneyException(Coin missing, String message) { super(message); this.missing = Objects.requireNonNull(missing); } }
1,415
30.466667
100
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/TxConfidenceTable.java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.utils.Threading; import javax.annotation.Nullable; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.locks.ReentrantLock; /** * <p>Tracks transactions that are being announced across the network. Typically one is created for you by a * {@link PeerGroup} and then given to each Peer to update. The current purpose is to let Peers update the confidence * (number of peers broadcasting). It helps address an attack scenario in which a malicious remote peer (or several) * feeds you invalid transactions, eg, ones that spend coins which don't exist. If you don't see most of the peers * announce the transaction within a reasonable time, it may be that the TX is not valid. Alternatively, an attacker * may control your entire internet connection: in this scenario counting broadcasting peers does not help you.</p> * * <p>It is <b>not</b> at this time directly equivalent to the Bitcoin Core memory pool, which tracks * all transactions not currently included in the best chain - it's simply a cache.</p> */ public class TxConfidenceTable { protected final ReentrantLock lock = Threading.lock(TxConfidenceTable.class); private static class WeakConfidenceReference extends WeakReference<TransactionConfidence> { public Sha256Hash hash; public WeakConfidenceReference(TransactionConfidence confidence, ReferenceQueue<TransactionConfidence> queue) { super(confidence, queue); hash = confidence.getTransactionHash(); } } private final Map<Sha256Hash, WeakConfidenceReference> table; private final TransactionConfidence.Factory confidenceFactory; // This ReferenceQueue gets entries added to it when they are only weakly reachable, ie, the TxConfidenceTable is the // only thing that is tracking the confidence data anymore. We check it from time to time and delete table entries // corresponding to expired transactions. In this way memory usage of the system is in line with however many // transactions you actually care to track the confidence of. We can still end up with lots of hashes being stored // if our peers flood us with invs but the MAX_SIZE param caps this. private ReferenceQueue<TransactionConfidence> referenceQueue; /** The max size of a table created with the no-args constructor. */ public static final int MAX_SIZE = 1000; /** * Creates a table that will track at most the given number of transactions (allowing you to bound memory * usage). * @param size Max number of transactions to track. The table will fill up to this size then stop growing. */ public TxConfidenceTable(final int size) { this(size, new TransactionConfidence.Factory()); } TxConfidenceTable(final int size, TransactionConfidence.Factory confidenceFactory){ table = new LinkedHashMap<Sha256Hash, WeakConfidenceReference>() { @Override protected boolean removeEldestEntry(Map.Entry<Sha256Hash, WeakConfidenceReference> entry) { // An arbitrary choice to stop the memory used by tracked transactions getting too huge in the event // of some kind of DoS attack. return size() > size; } }; referenceQueue = new ReferenceQueue<>(); this.confidenceFactory = confidenceFactory; } /** * Creates a table that will track at most {@link TxConfidenceTable#MAX_SIZE} entries. You should normally use * this constructor. */ public TxConfidenceTable() { this(MAX_SIZE); } /** * 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. */ 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(); } } /** * Returns the number of peers that have seen the given hash recently. */ 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(); } } /** * Called by peers when they see a transaction advertised in an "inv" message. It passes the data on to the relevant * {@link TransactionConfidence} object, creating it if needed. * * @return the number of peers that have now announced this hash (including the caller) */ public TransactionConfidence seen(Sha256Hash hash, PeerAddress byPeer) { TransactionConfidence confidence; boolean fresh = false; lock.lock(); try { cleanTable(); confidence = getOrCreate(hash); fresh = confidence.markBroadcastBy(byPeer); } finally { lock.unlock(); } if (fresh) confidence.queueListeners(TransactionConfidence.Listener.ChangeReason.SEEN_PEERS); return confidence; } /** * Returns the {@link TransactionConfidence} for the given hash if we have downloaded it, or null if that tx hash * is unknown to the system at this time. */ public TransactionConfidence getOrCreate(Sha256Hash hash) { Objects.requireNonNull(hash); lock.lock(); try { WeakConfidenceReference reference = table.get(hash); if (reference != null) { TransactionConfidence confidence = reference.get(); if (confidence != null) return confidence; } TransactionConfidence newConfidence = confidenceFactory.createConfidence(hash); table.put(hash, new WeakConfidenceReference(newConfidence, referenceQueue)); return newConfidence; } finally { lock.unlock(); } } /** * Returns the {@link TransactionConfidence} for the given hash if we have downloaded it, or null if that tx hash * is unknown to the system at this time. */ @Nullable public TransactionConfidence get(Sha256Hash hash) { lock.lock(); try { WeakConfidenceReference ref = table.get(hash); if (ref == null) return null; TransactionConfidence confidence = ref.get(); if (confidence != null) return confidence; else return null; } finally { lock.unlock(); } } }
8,524
40.383495
121
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/TransactionOutput.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Address; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Network; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.Buffers; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.script.ScriptException; import org.bitcoinj.script.ScriptPattern; import org.bitcoinj.wallet.Wallet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; import java.util.Objects; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>A TransactionOutput message contains a scriptPubKey that controls who is able to spend its value. It is a sub-part * of the Transaction message.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class TransactionOutput { private static final Logger log = LoggerFactory.getLogger(TransactionOutput.class); @Nullable protected Transaction parent; // The output's value is kept as a native type in order to save class instances. private long value; // A transaction output has a script used for authenticating that the redeemer is allowed to spend // this output. private byte[] scriptBytes; // The script bytes are parsed and turned into a Script on demand. private Script scriptPubKey; // These fields are not Bitcoin serialized. They are used for tracking purposes in our wallet // only. If set to true, this output is counted towards our balance. If false and spentBy is null the tx output // was owned by us and was sent to somebody else. If false and spentBy is set it means this output was owned by // us and used in one of our own transactions (eg, because it is a change output). private boolean availableForSpending; @Nullable private TransactionInput spentBy; /** * Deserialize this transaction output from a given payload. * * @param payload payload to deserialize from * @param parentTransaction parent transaction of the output * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static TransactionOutput read(ByteBuffer payload, Transaction parentTransaction) throws BufferUnderflowException, ProtocolException { Objects.requireNonNull(parentTransaction); Coin value = Coin.read(payload); byte[] scriptBytes = Buffers.readLengthPrefixedBytes(payload); return new TransactionOutput(parentTransaction, value, scriptBytes); } /** * Creates an output that sends 'value' to the given address (public key hash). The amount should be created with * something like {@link Coin#valueOf(int, int)}. Typically you would use * {@link Transaction#addOutput(Coin, Address)} instead of creating a TransactionOutput directly. */ public TransactionOutput(@Nullable Transaction parent, Coin value, Address to) { this(parent, value, ScriptBuilder.createOutputScript(to).program()); } /** * Creates an output that sends 'value' to the given public key using a simple CHECKSIG script (no addresses). The * amount should be created with something like {@link Coin#valueOf(int, int)}. Typically you would use * {@link Transaction#addOutput(Coin, ECKey)} instead of creating an output directly. */ public TransactionOutput(@Nullable Transaction parent, Coin value, ECKey to) { this(parent, value, ScriptBuilder.createP2PKOutputScript(to).program()); } public TransactionOutput(@Nullable Transaction parent, Coin value, byte[] scriptBytes) { super(); // Negative values obviously make no sense, except for -1 which is used as a sentinel value when calculating // SIGHASH_SINGLE signatures, so unfortunately we have to allow that here. checkArgument(value.signum() >= 0 || value.equals(Coin.NEGATIVE_SATOSHI), () -> "negative values not allowed"); Objects.requireNonNull(scriptBytes); this.value = value.value; this.scriptBytes = scriptBytes; setParent(parent); availableForSpending = true; } public Script getScriptPubKey() throws ScriptException { if (scriptPubKey == null) { scriptPubKey = Script.parse(scriptBytes); } return scriptPubKey; } /** * Write this transaction output into the given buffer. * * @param buf buffer to write into * @return the buffer * @throws BufferOverflowException if the output doesn't fit the remaining buffer */ public ByteBuffer write(ByteBuffer buf) throws BufferOverflowException { Coin.valueOf(value).write(buf); Buffers.writeLengthPrefixedBytes(buf, scriptBytes); return buf; } /** * Allocates a byte array and writes this transaction output into it. * * @return byte array containing the transaction output */ public byte[] serialize() { return write(ByteBuffer.allocate(getMessageSize())).array(); } /** @deprecated use {@link #serialize()} */ @Deprecated public byte[] bitcoinSerialize() { return serialize(); } /** * Return the size of the serialized message. Note that if the message was deserialized from a payload, this * size can differ from the size of the original payload. * * @return size of the serialized message in bytes */ public int getMessageSize() { int size = Coin.BYTES; // value size += VarInt.sizeOf(scriptBytes.length) + scriptBytes.length; return size; } /** * Returns the value of this output. This is the amount of currency that the destination address * receives. */ public Coin getValue() { return Coin.valueOf(value); } /** * Sets the value of this output. */ public void setValue(Coin value) { Objects.requireNonNull(value); // Negative values obviously make no sense, except for -1 which is used as a sentinel value when calculating // SIGHASH_SINGLE signatures, so unfortunately we have to allow that here. checkArgument(value.signum() >= 0 || value.equals(Coin.NEGATIVE_SATOSHI), () -> "value out of range: " + value); this.value = value.value; } /** * Gets the index of this output in the parent transaction, or throws if this output is freestanding. Iterates * over the parents list to discover this. */ public int getIndex() { List<TransactionOutput> outputs = getParentTransaction().getOutputs(); for (int i = 0; i < outputs.size(); i++) { if (outputs.get(i) == this) return i; } throw new IllegalStateException("Output linked to wrong parent transaction?"); } /** * Will this transaction be relayable and mined by default miners? */ public boolean isDust() { // Transactions that are OP_RETURN can't be dust regardless of their value. if (ScriptPattern.isOpReturn(getScriptPubKey())) return false; return getValue().isLessThan(getMinNonDustValue()); } /** * <p>Gets the minimum value for a txout of this size to be considered non-dust by Bitcoin Core * (and thus relayed). See: CTxOut::IsDust() in Bitcoin Core.</p> * * <p>You probably should use {@link TransactionOutput#getMinNonDustValue()} which uses * a safe fee-per-kb by default.</p> * * @param feePerKb The fee required per kilobyte. Note that this is the same as Bitcoin Core's -minrelaytxfee * 3 */ public Coin getMinNonDustValue(Coin feePerKb) { // "Dust" is defined in terms of dustRelayFee, // which has units satoshis-per-kilobyte. // If you'd pay more in fees than the value of the output // to spend something, then we consider it dust. // A typical spendable non-segwit txout is 34 bytes big, and will // need a CTxIn of at least 148 bytes to spend: // so dust is a spendable txout less than // 182*dustRelayFee/1000 (in satoshis). // 546 satoshis at the default rate of 3000 sat/kB. // A typical spendable segwit txout is 31 bytes big, and will // need a CTxIn of at least 67 bytes to spend: // so dust is a spendable txout less than // 98*dustRelayFee/1000 (in satoshis). // 294 satoshis at the default rate of 3000 sat/kB. long size = this.serialize().length; final Script script = getScriptPubKey(); if (ScriptPattern.isP2PKH(script) || ScriptPattern.isP2PK(script) || ScriptPattern.isP2SH(script) || ScriptPattern.isSentToMultisig(script)) size += 32 + 4 + 1 + 107 + 4; // 148 else if (ScriptPattern.isP2WH(script)) size += 32 + 4 + 1 + (107 / 4) + 4; // 68 else return Coin.ZERO; return feePerKb.multiply(size).divide(1000); } /** * Returns the minimum value for this output to be considered "not dust", i.e. the transaction will be relayable * and mined by default miners. */ public Coin getMinNonDustValue() { return getMinNonDustValue(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE.multiply(3)); } /** * Sets this objects availableForSpending flag to false and the spentBy pointer to the given input. * If the input is null, it means this output was signed over to somebody else rather than one of our own keys. * @throws IllegalStateException if the transaction was already marked as spent. */ public void markAsSpent(TransactionInput input) { checkState(availableForSpending); availableForSpending = false; spentBy = input; if (parent != null) if (log.isDebugEnabled()) log.debug("Marked {}:{} as spent by {}", getParentTransactionHash(), getIndex(), input); else if (log.isDebugEnabled()) log.debug("Marked floating output as spent by {}", input); } /** * Resets the spent pointer / availableForSpending flag to null. */ public void markAsUnspent() { if (parent != null) if (log.isDebugEnabled()) log.debug("Un-marked {}:{} as spent by {}", getParentTransactionHash(), getIndex(), spentBy); else if (log.isDebugEnabled()) log.debug("Un-marked floating output as spent by {}", spentBy); availableForSpending = true; spentBy = null; } /** * Returns whether {@link TransactionOutput#markAsSpent(TransactionInput)} has been called on this class. A * {@link Wallet} will mark a transaction output as spent once it sees a transaction input that is connected to it. * Note that this flag can be false when an output has in fact been spent according to the rest of the network if * the spending transaction wasn't downloaded yet, and it can be marked as spent when in reality the rest of the * network believes it to be unspent if the signature or script connecting to it was not actually valid. */ public boolean isAvailableForSpending() { return availableForSpending; } /** * The backing script bytes which can be turned into a Script object. * @return the scriptBytes */ public byte[] getScriptBytes() { return scriptBytes; } /** * Returns true if this output is to a key in the wallet or to an address/script we are watching. */ public boolean isMineOrWatched(TransactionBag transactionBag) { return isMine(transactionBag) || isWatched(transactionBag); } /** * Returns true if this output is to a key, or an address we have the keys for, in the wallet. */ public boolean isWatched(TransactionBag transactionBag) { try { Script script = getScriptPubKey(); return transactionBag.isWatchedScript(script); } catch (ScriptException e) { // Just means we didn't understand the output of this transaction: ignore it. log.debug("Could not parse tx output script: {}", e.toString()); return false; } } /** * Returns true if this output is to a key, or an address we have the keys for, in the wallet. */ public boolean isMine(TransactionBag transactionBag) { try { Script script = getScriptPubKey(); if (ScriptPattern.isP2PK(script)) return transactionBag.isPubKeyMine(ScriptPattern.extractKeyFromP2PK(script)); else if (ScriptPattern.isP2SH(script)) return transactionBag.isPayToScriptHashMine(ScriptPattern.extractHashFromP2SH(script)); else if (ScriptPattern.isP2PKH(script)) return transactionBag.isPubKeyHashMine(ScriptPattern.extractHashFromP2PKH(script), ScriptType.P2PKH); else if (ScriptPattern.isP2WPKH(script)) return transactionBag.isPubKeyHashMine(ScriptPattern.extractHashFromP2WH(script), ScriptType.P2WPKH); else return false; } catch (ScriptException e) { // Just means we didn't understand the output of this transaction: ignore it. log.debug("Could not parse tx {} output script: {}", parent != null ? ((Transaction) parent).getTxId() : "(no parent)", e.toString()); return false; } } /** * Returns a human-readable debug string. * @return debug string */ @Override public String toString() { return toString(null); } /** * Returns a human-readable debug string. * @param network if provided, addresses (of that network) will be printed for standard scripts * @return debug string */ public String toString(@Nullable Network network) { StringBuilder buf = new StringBuilder("TxOut of "); buf.append(Coin.valueOf(value).toFriendlyString()); try { Script script = getScriptPubKey(); if (ScriptPattern.isP2PKH(script) || ScriptPattern.isP2WPKH(script) || ScriptPattern.isP2TR(script) || ScriptPattern.isP2SH(script)) { buf.append(" to ").append(script.getScriptType().name()); if (network != null) buf.append(" ").append(script.getToAddress(network)); } else if (ScriptPattern.isP2PK(script)) { buf.append(" to pubkey ").append(ByteUtils.formatHex(ScriptPattern.extractKeyFromP2PK(script))); } else if (ScriptPattern.isSentToMultisig(script)) { buf.append(" to multisig"); } else { buf.append(" (unknown type)"); } buf.append(" script:").append(script); } catch (ScriptException e) { buf.append(" [exception: ").append(e.getMessage()).append("]"); } return buf.toString(); } /** * Returns the connected input. */ @Nullable public TransactionInput getSpentBy() { return spentBy; } /** * Returns the transaction that owns this output. */ @Nullable public Transaction getParentTransaction() { return parent; } /** * Returns the transaction hash that owns this output. */ @Nullable public Sha256Hash getParentTransactionHash() { return parent == null ? null : ((Transaction) parent).getTxId(); } /** * Returns the depth in blocks of the parent tx. * * <p>If the transaction appears in the top block, the depth is one. If it's anything else (pending, dead, unknown) * then -1.</p> * @return The tx depth or -1. */ public int getParentTransactionDepthInBlocks() { if (getParentTransaction() != null) { TransactionConfidence confidence = getParentTransaction().getConfidence(); if (confidence.getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) { return confidence.getDepthInBlocks(); } } return -1; } /** * Returns a new {@link TransactionOutPoint}, which is essentially a structure pointing to this output. * Requires that this output is not detached. */ public TransactionOutPoint getOutPointFor() { return new TransactionOutPoint(getIndex(), getParentTransaction()); } /** Returns a copy of the output detached from its containing transaction, if need be. */ public TransactionOutput duplicateDetached() { return new TransactionOutput(null, Coin.valueOf(value), Arrays.copyOf(scriptBytes, scriptBytes.length)); } protected final void setParent(@Nullable Transaction parent) { this.parent = parent; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TransactionOutput other = (TransactionOutput) o; return value == other.value && (parent == null || (parent.equals(other.parent) && getIndex() == other.getIndex())) && Arrays.equals(scriptBytes, other.scriptBytes); } @Override public int hashCode() { return Objects.hash(value, parent, Arrays.hashCode(scriptBytes)); } }
18,473
39.424508
148
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/RejectMessage.java
/* * Copyright 2013 Matt Corallo * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.Buffers; import javax.annotation.Nullable; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Locale; import java.util.Objects; import java.util.stream.Stream; /** * A message sent by nodes when a message we sent was rejected (ie a transaction had too little fee/was invalid/etc). * See <a href="https://github.com/bitcoin/bips/blob/master/bip-0061.mediawiki">BIP61</a> for details. * <p> * Instances of this class are immutable. */ public class RejectMessage extends BaseMessage { public enum RejectCode { /** The message was not able to be parsed */ MALFORMED((byte) 0x01), /** The message described an invalid object */ INVALID((byte) 0x10), /** The message was obsolete or described an object which is obsolete (eg unsupported, old version, v1 block) */ OBSOLETE((byte) 0x11), /** * The message was relayed multiple times or described an object which is in conflict with another. * This message can describe errors in protocol implementation or the presence of an attempt to DOUBLE SPEND. */ DUPLICATE((byte) 0x12), /** * The message described an object was not standard and was thus not accepted. * Bitcoin Core has a concept of standard transaction forms, which describe scripts and encodings which * it is willing to relay further. Other transactions are neither relayed nor mined, though they are considered * valid if they appear in a block. */ NONSTANDARD((byte) 0x40), /** * This refers to a specific form of NONSTANDARD transactions, which have an output smaller than some constant * defining them as dust (this is no longer used). */ DUST((byte) 0x41), /** The messages described an object which did not have sufficient fee to be relayed further. */ INSUFFICIENTFEE((byte) 0x42), /** The message described a block which was invalid according to hard-coded checkpoint blocks. */ CHECKPOINT((byte) 0x43), OTHER((byte) 0xff); final byte code; RejectCode(byte code) { this.code = code; } static RejectCode fromCode(byte code) { return Stream.of(RejectCode.values()) .filter(r -> r.code == code) .findFirst() .orElse(OTHER); } } private final String rejectedMessage; private final RejectCode code; private final String reason; @Nullable private final Sha256Hash rejectedMessageHash; /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static RejectMessage read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { String message = Buffers.readLengthPrefixedString(payload); RejectCode code = RejectCode.fromCode(payload.get()); String reason = Buffers.readLengthPrefixedString(payload); Sha256Hash messageHash = message.equals("block") || message.equals("tx") ? Sha256Hash.read(payload) : null; return new RejectMessage(code, messageHash, message, reason); } /** Constructs a reject message that fingers the object with the given hash as rejected for the given reason. */ public RejectMessage(RejectCode code, @Nullable Sha256Hash rejectedMessageHash, String rejectedMessage, String reason) { this.rejectedMessage = Objects.requireNonNull(rejectedMessage); this.code = Objects.requireNonNull(code); this.reason = Objects.requireNonNull(reason); this.rejectedMessageHash = rejectedMessageHash; } @Override public void bitcoinSerializeToStream(OutputStream stream) throws IOException { byte[] messageBytes = rejectedMessage.getBytes(StandardCharsets.UTF_8); stream.write(VarInt.of(messageBytes.length).serialize()); stream.write(messageBytes); stream.write(code.code); byte[] reasonBytes = reason.getBytes(StandardCharsets.UTF_8); stream.write(VarInt.of(reasonBytes.length).serialize()); stream.write(reasonBytes); if ("block".equals(rejectedMessage) || "tx".equals(rejectedMessage)) stream.write(rejectedMessageHash.serialize()); } /** * Provides the type of message which was rejected by the peer. * Note that this is ENTIRELY UNTRUSTED and should be sanity-checked before it is printed or processed. * * @return rejected message type */ public String rejectedMessage() { return rejectedMessage; } /** @deprecated use {@link #rejectedMessage()} */ @Deprecated public String getRejectedMessage() { return rejectedMessage(); } /** * Provides the hash of the rejected object (if getRejectedMessage() is either "tx" or "block"), otherwise null. * * @return hash of rejected object */ public Sha256Hash rejectedMessageHash() { return rejectedMessageHash; } /** @deprecated use {@link #rejectedMessageHash()} */ @Deprecated public Sha256Hash getRejectedObjectHash() { return rejectedMessageHash(); } /** * The reason code given for why the peer rejected the message. * * @return reject reason code */ public RejectCode code() { return code; } /** @deprecated use {@link #code()} */ @Deprecated public RejectCode getReasonCode() { return code(); } /** * The reason message given for rejection. * Note that this is ENTIRELY UNTRUSTED and should be sanity-checked before it is printed or processed. * * @return reject reason */ public String reason() { return reason; } /** @deprecated use {@link #reason()} */ @Deprecated public String getReasonString() { return reason(); } /** * A String representation of the relevant details of this reject message. * Be aware that the value returned by this method includes the value returned by * {@link #getReasonString() getReasonString}, which is taken from the reject message unchecked. * Through malice or otherwise, it might contain control characters or other harmful content. */ @Override public String toString() { return String.format(Locale.US, "Reject: %s %s for reason '%s' (%d)", rejectedMessage, rejectedMessageHash != null ? rejectedMessageHash : "", reason, code.code); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RejectMessage other = (RejectMessage) o; return rejectedMessage.equals(other.rejectedMessage) && code.equals(other.code) && reason.equals(other.reason) && rejectedMessageHash.equals(other.rejectedMessageHash); } @Override public int hashCode() { return Objects.hash(rejectedMessage, code, reason, rejectedMessageHash); } }
8,154
36.75463
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/TransactionBroadcast.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.Uninterruptibles; import org.bitcoinj.base.internal.FutureUtils; import org.bitcoinj.base.internal.StreamUtils; import org.bitcoinj.base.internal.InternalUtils; import org.bitcoinj.core.listeners.PreMessageReceivedEventListener; import org.bitcoinj.utils.ListenableCompletableFuture; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.Wallet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.function.Function; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Represents a single transaction broadcast that we are performing. A broadcast occurs after a new transaction is created * (typically by a {@link Wallet}) and needs to be sent to the network. A broadcast can succeed or fail. A success is * defined as seeing the transaction be announced by peers via inv messages, thus indicating their acceptance. A failure * is defined as not reaching acceptance within a timeout period, or getting an explicit reject message from a peer * indicating that the transaction was not acceptable. */ public class TransactionBroadcast { private static final Logger log = LoggerFactory.getLogger(TransactionBroadcast.class); // This future completes when all broadcast messages were sent (to a buffer) private final CompletableFuture<TransactionBroadcast> sentFuture = new CompletableFuture<>(); // This future completes when we have verified that more than numWaitingFor Peers have seen the broadcast private final CompletableFuture<TransactionBroadcast> seenFuture = new CompletableFuture<>(); private final PeerGroup peerGroup; private final Transaction tx; private int minConnections; private boolean dropPeersAfterBroadcast = false; private int numWaitingFor; /** Used for shuffling the peers before broadcast: unit tests can replace this to make themselves deterministic. */ @VisibleForTesting public static Random random = new Random(); // Tracks which nodes sent us a reject message about this broadcast, if any. Useful for debugging. private final Map<Peer, RejectMessage> rejects = Collections.synchronizedMap(new HashMap<Peer, RejectMessage>()); TransactionBroadcast(PeerGroup peerGroup, Transaction tx) { this.peerGroup = peerGroup; this.tx = tx; this.minConnections = Math.max(1, peerGroup.getMinBroadcastConnections()); } // Only for mock broadcasts. private TransactionBroadcast(Transaction tx) { this.peerGroup = null; this.tx = tx; } public Transaction transaction() { return tx; } @VisibleForTesting public static TransactionBroadcast createMockBroadcast(Transaction tx, final CompletableFuture<Transaction> future) { return new TransactionBroadcast(tx) { @Override public ListenableCompletableFuture<Transaction> broadcast() { return ListenableCompletableFuture.of(future); } @Override public ListenableCompletableFuture<Transaction> future() { return ListenableCompletableFuture.of(future); } }; } /** * @return future that completes when some number of remote peers has rebroadcast the transaction * @deprecated Use {@link #awaitRelayed()} (and maybe {@link CompletableFuture#thenApply(Function)}) */ @Deprecated public ListenableCompletableFuture<Transaction> future() { return ListenableCompletableFuture.of(awaitRelayed().thenApply(TransactionBroadcast::transaction)); } public void setMinConnections(int minConnections) { this.minConnections = minConnections; } public void setDropPeersAfterBroadcast(boolean dropPeersAfterBroadcast) { this.dropPeersAfterBroadcast = dropPeersAfterBroadcast; } private final PreMessageReceivedEventListener rejectionListener = new PreMessageReceivedEventListener() { @Override public Message onPreMessageReceived(Peer peer, Message m) { if (m instanceof RejectMessage) { RejectMessage rejectMessage = (RejectMessage)m; if (tx.getTxId().equals(rejectMessage.getRejectedObjectHash())) { rejects.put(peer, rejectMessage); int size = rejects.size(); long threshold = Math.round(numWaitingFor / 2.0); if (size > threshold) { log.warn("Threshold for considering broadcast rejected has been reached ({}/{})", size, threshold); seenFuture.completeExceptionally(new RejectedTransactionException(tx, rejectMessage)); peerGroup.removePreMessageReceivedEventListener(this); } } } return m; } }; // TODO: Should this method be moved into the PeerGroup? /** * Broadcast this transaction to the proper calculated number of peers. Returns a future that completes when the message * has been "sent" to a set of remote peers. The {@link TransactionBroadcast} itself is the returned type/value for the future. * <p> * The complete broadcast process includes the following steps: * <ol> * <li>Wait until enough {@link org.bitcoinj.core.Peer}s are connected.</li> * <li>Broadcast the transaction to a determined number of {@link org.bitcoinj.core.Peer}s</li> * <li>Wait for confirmation from a determined number of remote peers that they have received the broadcast</li> * <li>Mark {@link TransactionBroadcast#awaitRelayed()} ()} ("seen future") as complete</li> * </ol> * The future returned from this method completes when Step 2 is completed. * <p> * It should further be noted that "broadcast" in this class means that * {@link org.bitcoinj.net.MessageWriteTarget#writeBytes} has completed successfully which means the message has * been sent to the "OS network buffer" -- see {@link org.bitcoinj.net.MessageWriteTarget#writeBytes} or its implementation. * <p> * @return A future that completes when the message has been sent (or at least buffered) to the correct number of remote Peers. The future * will complete exceptionally if <i>any</i> of the peer broadcasts fails. */ public CompletableFuture<TransactionBroadcast> broadcastOnly() { peerGroup.addPreMessageReceivedEventListener(Threading.SAME_THREAD, rejectionListener); log.info("Waiting for {} peers required for broadcast, we have {} ...", minConnections, peerGroup.getConnectedPeers().size()); final Context context = Context.get(); return peerGroup.waitForPeers(minConnections).thenComposeAsync( peerList /* not used */ -> { Context.propagate(context); // We now have enough connected peers to send the transaction. // This can be called immediately if we already have enough. Otherwise it'll be called from a peer // thread. // We will send the tx simultaneously to half the connected peers and wait to hear back from at least half // of the other half, i.e., with 4 peers connected we will send the tx to 2 randomly chosen peers, and then // wait for it to show up on one of the other two. This will be taken as sign of network acceptance. As can // be seen, 4 peers is probably too little - it doesn't taken many broken peers for tx propagation to have // a big effect. List<Peer> peers = peerGroup.getConnectedPeers(); // snapshots // Prepare to send the transaction by adding a listener that'll be called when confidence changes. tx.getConfidence().addEventListener(new ConfidenceChange()); // Bitcoin Core sends an inv in this case and then lets the peer request the tx data. We just // blast out the TX here for a couple of reasons. Firstly it's simpler: in the case where we have // just a single connection we don't have to wait for getdata to be received and handled before // completing the future in the code immediately below. Secondly, it's faster. The reason the // Bitcoin Core sends an inv is privacy - it means you can't tell if the peer originated the // transaction or not. However, we are not a fully validating node and this is advertised in // our version message, as SPV nodes cannot relay it doesn't give away any additional information // to skip the inv here - we wouldn't send invs anyway. List<Peer> broadcastPeers = chooseBroadcastPeers(peers); int numToBroadcastTo = broadcastPeers.size(); numWaitingFor = (int) Math.ceil((peers.size() - numToBroadcastTo) / 2.0); log.info("broadcastTransaction: We have {} peers, adding {} to the memory pool", peers.size(), tx.getTxId()); log.info("Sending to {} peers, will wait for {}, sending to: {}", numToBroadcastTo, numWaitingFor, InternalUtils.joiner(",").join(peers)); List<CompletableFuture<Void>> sentFutures = broadcastPeers.stream() .map(this::broadcastOne) .collect(StreamUtils.toUnmodifiableList()); // Complete successfully if ALL peer.sendMessage complete successfully, fail otherwise return CompletableFuture.allOf(sentFutures.toArray(new CompletableFuture[0])); }, Threading.SAME_THREAD) .whenComplete((v, err) -> { // Complete `sentFuture` (even though it is currently unused) if (err == null) { log.info("broadcast has been written to correct number of peers with peer.sendMessage(tx)"); sentFuture.complete(this); } else { log.error("broadcast - one ore more peers failed to send", err); sentFuture.completeExceptionally(err); } }) .thenCompose(v -> sentFuture); } /** * Broadcast the transaction and wait for confirmation that the transaction has been received by the appropriate * number of Peers before completing. * @return A future that completes when the message has been relayed by the appropriate number of remote peers */ public CompletableFuture<TransactionBroadcast> broadcastAndAwaitRelay() { return broadcastOnly() .thenCompose(broadcast -> this.seenFuture); } /** * Wait for confirmation the transaction has been relayed. * @return A future that completes when the message has been relayed by the appropriate number of remote peers */ public CompletableFuture<TransactionBroadcast> awaitRelayed() { return seenFuture; } /** * Wait for confirmation the transaction has been sent to a remote peer. (Or at least buffered to be sent to * a peer.) * @return A future that completes when the message has been relayed by the appropriate number of remote peers */ public CompletableFuture<TransactionBroadcast> awaitSent() { return sentFuture; } /** * If you migrate to {@link #broadcastAndAwaitRelay()} and need a {@link CompletableFuture} that returns * {@link Transaction} you can use: * <pre>{@code * CompletableFuture<Transaction> seenFuture = broadcast * .broadcastAndAwaitRelay() * .thenApply(TransactionBroadcast::transaction); * }</pre> * @deprecated Use {@link #broadcastAndAwaitRelay()} or {@link #broadcastOnly()} as appropriate */ @Deprecated public ListenableCompletableFuture<Transaction> broadcast() { return ListenableCompletableFuture.of( broadcastAndAwaitRelay().thenApply(TransactionBroadcast::transaction) ); } private CompletableFuture<Void> broadcastOne(Peer peer) { try { CompletableFuture<Void> future = peer.sendMessage(tx); if (dropPeersAfterBroadcast) { // We drop the peer shortly after the transaction has been sent, because this peer will not // send us back useful broadcast confirmations. future.thenRunAsync(dropPeerAfterBroadcastHandler(peer), Threading.THREAD_POOL); } // We don't record the peer as having seen the tx in the memory pool because we want to track only // how many peers announced to us. return future; } catch (Exception e) { log.error("Caught exception sending to {}", peer, e); return FutureUtils.failedFuture(e); } } private static Runnable dropPeerAfterBroadcastHandler(Peer peer) { return () -> { Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); peer.close(); }; } /** * Randomly choose a subset of connected peers to broadcast to * @param connectedPeers connected peers to chose from * @return list of chosen broadcast peers */ private List<Peer> chooseBroadcastPeers(List<Peer> connectedPeers) { int numToBroadcastTo = (int) Math.max(1, Math.round(Math.ceil(connectedPeers.size() / 2.0))); List<Peer> peerListCopy = new ArrayList<>(connectedPeers); Collections.shuffle(peerListCopy, random); return peerListCopy.subList(0, numToBroadcastTo); } private int numSeemPeers; private boolean mined; private class ConfidenceChange implements TransactionConfidence.Listener { @Override public void onConfidenceChanged(TransactionConfidence conf, ChangeReason reason) { // The number of peers that announced this tx has gone up. int numSeenPeers = conf.numBroadcastPeers() + rejects.size(); boolean mined = tx.getAppearsInHashes() != null; log.info("broadcastTransaction: {}: TX {} seen by {} peers{}", reason, tx.getTxId(), numSeenPeers, mined ? " and mined" : ""); // Progress callback on the requested thread. invokeAndRecord(numSeenPeers, mined); if (numSeenPeers >= numWaitingFor || mined) { // We've seen the min required number of peers announce the transaction, or it was included // in a block. Normally we'd expect to see it fully propagate before it gets mined, but // it can be that a block is solved very soon after broadcast, and it's also possible that // due to version skew and changes in the relay rules our transaction is not going to // fully propagate yet can get mined anyway. // // Note that we can't wait for the current number of connected peers right now because we // could have added more peers after the broadcast took place, which means they won't // have seen the transaction. In future when peers sync up their memory pools after they // connect we could come back and change this. // // We're done! It's important that the PeerGroup lock is not held (by this thread) at this // point to avoid triggering inversions when the Future completes. log.info("broadcastTransaction: {} complete", tx.getTxId()); peerGroup.removePreMessageReceivedEventListener(rejectionListener); conf.removeEventListener(this); seenFuture.complete(TransactionBroadcast.this); // RE-ENTRANCY POINT } } } private void invokeAndRecord(int numSeenPeers, boolean mined) { synchronized (this) { this.numSeemPeers = numSeenPeers; this.mined = mined; } invokeProgressCallback(numSeenPeers, mined); } private void invokeProgressCallback(int numSeenPeers, boolean mined) { final ProgressCallback callback; Executor executor; synchronized (this) { callback = this.callback; executor = this.progressCallbackExecutor; } if (callback != null) { final double progress = Math.min(1.0, mined ? 1.0 : numSeenPeers / (double) numWaitingFor); checkState(progress >= 0.0 && progress <= 1.0, () -> "" + progress); try { if (executor == null) callback.onBroadcastProgress(progress); else executor.execute(() -> callback.onBroadcastProgress(progress)); } catch (Throwable e) { log.error("Exception during progress callback", e); } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** An interface for receiving progress information on the propagation of the tx, from 0.0 to 1.0 */ public interface ProgressCallback { /** * onBroadcastProgress will be invoked on the provided executor when the progress of the transaction * broadcast has changed, because the transaction has been announced by another peer or because the transaction * was found inside a mined block (in this case progress will go to 1.0 immediately). Any exceptions thrown * by this callback will be logged and ignored. */ void onBroadcastProgress(double progress); } @Nullable private ProgressCallback callback; @Nullable private Executor progressCallbackExecutor; /** * Sets the given callback for receiving progress values, which will run on the user thread. See * {@link Threading} for details. If the broadcast has already started then the callback will * be invoked immediately with the current progress. */ public void setProgressCallback(ProgressCallback callback) { setProgressCallback(callback, Threading.USER_THREAD); } /** * Sets the given callback for receiving progress values, which will run on the given executor. If the executor * is null then the callback will run on a network thread and may be invoked multiple times in parallel. You * probably want to provide your UI thread or Threading.USER_THREAD for the second parameter. If the broadcast * has already started then the callback will be invoked immediately with the current progress. */ public void setProgressCallback(ProgressCallback callback, @Nullable Executor executor) { boolean shouldInvoke; int num; boolean mined; synchronized (this) { this.callback = callback; this.progressCallbackExecutor = executor; num = this.numSeemPeers; mined = this.mined; shouldInvoke = numWaitingFor > 0; } if (shouldInvoke) invokeProgressCallback(num, mined); } }
19,995
48.37284
150
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/AddressMessage.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.VarInt; import org.bitcoinj.net.discovery.PeerDiscovery; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.bitcoinj.base.internal.Preconditions.check; /** * Abstract superclass for address messages on the P2P network, which contain network addresses of other peers. This is * one of the ways peers can find each other without using the {@link PeerDiscovery} mechanism. */ public abstract class AddressMessage extends BaseMessage { protected static final long MAX_ADDRESSES = 1000; protected List<PeerAddress> addresses; protected static List<PeerAddress> readAddresses(ByteBuffer payload, int protocolVariant) throws BufferUnderflowException, ProtocolException { VarInt numAddressesVarInt = VarInt.read(payload); check(numAddressesVarInt.fitsInt(), BufferUnderflowException::new); int numAddresses = numAddressesVarInt.intValue(); // Guard against ultra large messages that will crash us. if (numAddresses > MAX_ADDRESSES) throw new ProtocolException("Address message too large."); List<PeerAddress> addresses = new ArrayList<>(numAddresses); for (int i = 0; i < numAddresses; i++) { addresses.add(PeerAddress.read(payload, protocolVariant)); } return addresses; } protected AddressMessage(List<PeerAddress> addresses) { this.addresses = addresses; } public abstract void addAddress(PeerAddress address); public void removeAddress(int index) { PeerAddress address = addresses.remove(index); } /** * @return An unmodifiableList view of the backing List of addresses. Addresses contained within the list may be * safely modified. */ public List<PeerAddress> getAddresses() { return Collections.unmodifiableList(addresses); } }
2,605
35.704225
146
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/StoredUndoableBlock.java
/* * Copyright 2011 Google Inc. * Copyright 2012 Matt Corallo. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import java.util.List; /** * Contains minimal data necessary to disconnect/connect the transactions * in the stored block at will. Can either store the full set of * transactions (if the inputs for the block have not been tested to work) * or the set of transaction outputs created/destroyed when the block is * connected. */ public class StoredUndoableBlock { Sha256Hash blockHash; // Only one of either txOutChanges or transactions will be set private TransactionOutputChanges txOutChanges; private List<Transaction> transactions; public StoredUndoableBlock(Sha256Hash hash, TransactionOutputChanges txOutChanges) { this.blockHash = hash; this.transactions = null; this.txOutChanges = txOutChanges; } public StoredUndoableBlock(Sha256Hash hash, List<Transaction> transactions) { this.blockHash = hash; this.txOutChanges = null; this.transactions = transactions; } /** * Get the transaction output changes if they have been calculated, otherwise null. * Only one of this and getTransactions() will return a non-null value. */ public TransactionOutputChanges getTxOutChanges() { return txOutChanges; } /** * Get the full list of transactions if it is stored, otherwise null. * Only one of this and getTxOutChanges() will return a non-null value. */ public List<Transaction> getTransactions() { return transactions; } /** * Get the hash of the represented block */ public Sha256Hash getHash() { return blockHash; } @Override public int hashCode() { return blockHash.hashCode(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return getHash().equals(((StoredUndoableBlock)o).getHash()); } @Override public String toString() { return "Undoable Block " + blockHash; } }
2,746
29.186813
88
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/GetDataMessage.java
/* * Copyright 2011 Google Inc. * Copyright 2019 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.List; /** * <p>Represents the "getdata" P2P network message, which requests the contents of blocks or transactions given their * hashes.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class GetDataMessage extends ListMessage { /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static GetDataMessage read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { return new GetDataMessage(readItems(payload)); } public GetDataMessage() { super(); } private GetDataMessage(List<InventoryItem> items) { super(items); } public void addTransaction(Sha256Hash hash, boolean includeWitness) { addItem(new InventoryItem( includeWitness ? InventoryItem.Type.WITNESS_TRANSACTION : InventoryItem.Type.TRANSACTION, hash)); } public void addBlock(Sha256Hash hash, boolean includeWitness) { addItem(new InventoryItem(includeWitness ? InventoryItem.Type.WITNESS_BLOCK : InventoryItem.Type.BLOCK, hash)); } public void addFilteredBlock(Sha256Hash hash) { addItem(new InventoryItem(InventoryItem.Type.FILTERED_BLOCK, hash)); } public Sha256Hash getHashOf(int i) { return getItems().get(i).hash; } }
2,289
32.188406
119
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/Message.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; /** * A Message is a data structure that can be serialized/deserialized using the Bitcoin serialization format. * Classes that can be serialized to the blockchain or P2P protocol should implement this interface. */ public interface Message { /** * Maximum size of a Bitcoin P2P Message (32 MB) */ int MAX_SIZE = 0x02000000; /** * Return the size of the serialized message. Note that if the message was deserialized from a payload, this * size can differ from the size of the original payload. * * @return size of this object when serialized (in bytes) */ int messageSize(); /** * @deprecated use {@link #messageSize()} */ @Deprecated default int getMessageSize() { return messageSize(); } /** * Serialize this message to a byte array that conforms to the Bitcoin wire protocol. * * @return serialized data in Bitcoin protocol format */ byte[] serialize(); /** * @deprecated use {@link #serialize()} */ @Deprecated default byte[] bitcoinSerialize() { return serialize(); } /** @deprecated use {@link #serialize()} */ @Deprecated default byte[] unsafeBitcoinSerialize() { return serialize(); } }
1,915
28.030303
112
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/TransactionBroadcaster.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; /** * A general interface which declares the ability to broadcast transactions. This is implemented * by {@link PeerGroup}. */ public interface TransactionBroadcaster { /** Broadcast the given transaction on the network */ TransactionBroadcast broadcastTransaction(final Transaction tx); }
924
33.259259
96
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/FullPrunedBlockChain.java
/* * Copyright 2012 Matt Corallo. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.params.BitcoinNetworkParams; import org.bitcoinj.script.Script; import org.bitcoinj.script.Script.VerifyFlag; import org.bitcoinj.script.ScriptPattern; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.store.FullPrunedBlockStore; import org.bitcoinj.utils.ContextPropagatingThreadFactory; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.WalletExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.File; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>A FullPrunedBlockChain works in conjunction with a {@link FullPrunedBlockStore} to verify all the rules of the * Bitcoin system, with the downside being a large cost in system resources. Fully verifying means all unspent * transaction outputs are stored. Once a transaction output is spent and that spend is buried deep enough, the data * related to it is deleted to ensure disk space usage doesn't grow forever. For this reason a pruning node cannot * serve the full block chain to other clients, but it nevertheless provides the same security guarantees as Bitcoin * Core does.</p> */ public class FullPrunedBlockChain extends AbstractBlockChain { private static final Logger log = LoggerFactory.getLogger(FullPrunedBlockChain.class); /** * Keeps a map of block hashes to StoredBlocks. */ protected final FullPrunedBlockStore blockStore; // Whether or not to execute scriptPubKeys before accepting a transaction (i.e. check signatures). private boolean runScripts = true; /** * Constructs a block chain connected to the given wallet and store. To obtain a {@link Wallet} you can construct * one from scratch, or you can deserialize a saved wallet from disk using * {@link Wallet#loadFromFile(File, WalletExtension...)} */ public FullPrunedBlockChain(NetworkParameters params, Wallet wallet, FullPrunedBlockStore blockStore) throws BlockStoreException { this(params, new ArrayList<Wallet>(), blockStore); addWallet(wallet); } /** * Constructs a block chain connected to the given store. */ public FullPrunedBlockChain(NetworkParameters params, FullPrunedBlockStore blockStore) throws BlockStoreException { this(params, new ArrayList<Wallet>(), blockStore); } /** * Constructs a block chain connected to the given list of wallets and a store. */ public FullPrunedBlockChain(NetworkParameters params, List<Wallet> listeners, FullPrunedBlockStore blockStore) throws BlockStoreException { super(params, listeners, blockStore); this.blockStore = blockStore; // Ignore upgrading for now this.chainHead = blockStore.getVerifiedChainHead(); } @Override protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block header, TransactionOutputChanges txOutChanges) throws BlockStoreException, VerificationException { StoredBlock newBlock = storedPrev.build(header); blockStore.put(newBlock, new StoredUndoableBlock(newBlock.getHeader().getHash(), txOutChanges)); return newBlock; } @Override protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block block) throws BlockStoreException, VerificationException { StoredBlock newBlock = storedPrev.build(block); blockStore.put(newBlock, new StoredUndoableBlock(newBlock.getHeader().getHash(), block.getTransactions())); return newBlock; } @Override protected void rollbackBlockStore(int height) throws BlockStoreException { throw new BlockStoreException("Unsupported"); } @Override protected boolean shouldVerifyTransactions() { return true; } /** * Whether or not to run scripts whilst accepting blocks (i.e. checking signatures, for most transactions). * If you're accepting data from an untrusted node, such as one found via the P2P network, this should be set * to true (which is the default). If you're downloading a chain from a node you control, script execution * is redundant because you know the connected node won't relay bad data to you. In that case it's safe to set * this to false and obtain a significant speedup. */ public void setRunScripts(boolean value) { this.runScripts = value; } // TODO: Remove lots of duplicated code in the two connectTransactions // TODO: execute in order of largest transaction (by input count) first ExecutorService scriptVerificationExecutor = Executors.newFixedThreadPool( Runtime.getRuntime().availableProcessors(), new ContextPropagatingThreadFactory("Script verification")); /** * A job submitted to the executor which verifies signatures. */ private static class Verifier implements Callable<VerificationException> { final Transaction tx; final List<Script> prevOutScripts; final Set<VerifyFlag> verifyFlags; public Verifier(final Transaction tx, final List<Script> prevOutScripts, final Set<VerifyFlag> verifyFlags) { this.tx = tx; this.prevOutScripts = prevOutScripts; this.verifyFlags = verifyFlags; } @Nullable @Override public VerificationException call() throws Exception { try { ListIterator<Script> prevOutIt = prevOutScripts.listIterator(); for (int index = 0; index < tx.getInputs().size(); index++) { tx.getInput(index).getScriptSig().correctlySpends(tx, index, null, null, prevOutIt.next(), verifyFlags); } } catch (VerificationException e) { return e; } return null; } } /** * Get the {@link Script} from the script bytes or return Script of empty byte array. */ private Script getScript(byte[] scriptBytes) { try { return Script.parse(scriptBytes); } catch (Exception e) { return Script.parse(new byte[0]); } } /** * Get the address from the {@link Script} if it exists otherwise return empty string "". * * @param script The script. * @return The address. */ private String getScriptAddress(@Nullable Script script) { String address = ""; try { if (script != null) { address = script.getToAddress(params.network(), true).toString(); } } catch (Exception e) { } return address; } @Override protected TransactionOutputChanges connectTransactions(int height, Block block) throws VerificationException, BlockStoreException { checkState(lock.isHeldByCurrentThread()); if (block.getTransactions() == null) throw new RuntimeException("connectTransactions called with Block that didn't have transactions!"); if (!params.passesCheckpoint(height, block.getHash())) throw new VerificationException("Block failed checkpoint lockin at " + height); blockStore.beginDatabaseBatchWrite(); LinkedList<UTXO> txOutsSpent = new LinkedList<>(); LinkedList<UTXO> txOutsCreated = new LinkedList<>(); long sigOps = 0; if (scriptVerificationExecutor.isShutdown()) scriptVerificationExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); List<Future<VerificationException>> listScriptVerificationResults = new ArrayList<>(block.getTransactions().size()); try { if (!params.isCheckpoint(height)) { // BIP30 violator blocks are ones that contain a duplicated transaction. They are all in the // checkpoints list and we therefore only check non-checkpoints for duplicated transactions here. See the // BIP30 document for more details on this: https://github.com/bitcoin/bips/blob/master/bip-0030.mediawiki for (Transaction tx : block.getTransactions()) { final Set<VerifyFlag> verifyFlags = params.getTransactionVerificationFlags(block, tx, getVersionTally(), height); Sha256Hash hash = tx.getTxId(); // If we already have unspent outputs for this hash, we saw the tx already. Either the block is // being added twice (bug) or the block is a BIP30 violator. if (blockStore.hasUnspentOutputs(hash, tx.getOutputs().size())) throw new VerificationException("Block failed BIP30 test!"); if (verifyFlags.contains(VerifyFlag.P2SH)) // We already check non-BIP16 sigops in Block.verifyTransactions(true) sigOps += tx.getSigOpCount(); } } Coin totalFees = Coin.ZERO; Coin coinbaseValue = null; for (final Transaction tx : block.getTransactions()) { boolean isCoinBase = tx.isCoinBase(); Coin valueIn = Coin.ZERO; Coin valueOut = Coin.ZERO; final List<Script> prevOutScripts = new LinkedList<>(); final Set<VerifyFlag> verifyFlags = params.getTransactionVerificationFlags(block, tx, getVersionTally(), height); if (!isCoinBase) { // For each input of the transaction remove the corresponding output from the set of unspent // outputs. for (int index = 0; index < tx.getInputs().size(); index++) { TransactionInput in = tx.getInput(index); UTXO prevOut = blockStore.getTransactionOutput(in.getOutpoint().hash(), in.getOutpoint().index()); if (prevOut == null) throw new VerificationException("Attempted to spend a non-existent or already spent output!"); // Coinbases can't be spent until they mature, to avoid re-orgs destroying entire transaction // chains. The assumption is there will ~never be re-orgs deeper than the spendable coinbase // chain depth. if (prevOut.isCoinbase()) { if (height - prevOut.getHeight() < params.getSpendableCoinbaseDepth()) { throw new VerificationException("Tried to spend coinbase at depth " + (height - prevOut.getHeight())); } } // TODO: Check we're not spending the genesis transaction here. Bitcoin Core won't allow it. valueIn = valueIn.add(prevOut.getValue()); if (verifyFlags.contains(VerifyFlag.P2SH)) { if (ScriptPattern.isP2SH(prevOut.getScript())) sigOps += Script.getP2SHSigOpCount(in.getScriptBytes()); if (sigOps > Block.MAX_BLOCK_SIGOPS) throw new VerificationException("Too many P2SH SigOps in block"); } prevOutScripts.add(prevOut.getScript()); blockStore.removeUnspentTransactionOutput(prevOut); txOutsSpent.add(prevOut); } } Sha256Hash hash = tx.getTxId(); for (TransactionOutput out : tx.getOutputs()) { valueOut = valueOut.add(out.getValue()); // For each output, add it to the set of unspent outputs so it can be consumed in future. Script script = getScript(out.getScriptBytes()); UTXO newOut = new UTXO(hash, out.getIndex(), out.getValue(), height, isCoinBase, script, getScriptAddress(script)); blockStore.addUnspentTransactionOutput(newOut); txOutsCreated.add(newOut); } // All values were already checked for being non-negative (as it is verified in Transaction.verify()) // but we check again here just for defence in depth. Transactions with zero output value are OK. if (valueOut.signum() < 0 || params.network().exceedsMaxMoney(valueOut)) throw new VerificationException("Transaction output value out of range"); if (isCoinBase) { coinbaseValue = valueOut; } else { if (valueIn.compareTo(valueOut) < 0 || params.network().exceedsMaxMoney(valueIn)) throw new VerificationException("Transaction input value out of range"); totalFees = totalFees.add(valueIn.subtract(valueOut)); } if (!isCoinBase && runScripts) { // Because correctlySpends modifies transactions, this must come after we are done with tx FutureTask<VerificationException> future = new FutureTask<>(new Verifier(tx, prevOutScripts, verifyFlags)); scriptVerificationExecutor.execute(future); listScriptVerificationResults.add(future); } } if (params.network().exceedsMaxMoney(totalFees) || getBlockInflation(height).add(totalFees).compareTo(coinbaseValue) < 0) throw new VerificationException("Transaction fees out of range"); for (Future<VerificationException> future : listScriptVerificationResults) { VerificationException e; try { e = future.get(); } catch (InterruptedException thrownE) { throw new RuntimeException(thrownE); // Shouldn't happen } catch (ExecutionException thrownE) { log.error("Script.correctlySpends threw a non-normal exception: " + thrownE.getCause()); throw new VerificationException("Bug in Script.correctlySpends, likely script malformed in some new and interesting way.", thrownE); } if (e != null) throw e; } } catch (VerificationException | BlockStoreException e) { scriptVerificationExecutor.shutdownNow(); blockStore.abortDatabaseBatchWrite(); throw e; } return new TransactionOutputChanges(txOutsCreated, txOutsSpent); } /** * Used during reorgs to connect a block previously on a fork */ @Override protected synchronized TransactionOutputChanges connectTransactions(StoredBlock newBlock) throws VerificationException, BlockStoreException, PrunedException { checkState(lock.isHeldByCurrentThread()); if (!params.passesCheckpoint(newBlock.getHeight(), newBlock.getHeader().getHash())) throw new VerificationException("Block failed checkpoint lockin at " + newBlock.getHeight()); blockStore.beginDatabaseBatchWrite(); StoredUndoableBlock block = blockStore.getUndoBlock(newBlock.getHeader().getHash()); if (block == null) { // We're trying to re-org too deep and the data needed has been deleted. blockStore.abortDatabaseBatchWrite(); throw new PrunedException(newBlock.getHeader().getHash()); } TransactionOutputChanges txOutChanges; try { List<Transaction> transactions = block.getTransactions(); if (transactions != null) { LinkedList<UTXO> txOutsSpent = new LinkedList<>(); LinkedList<UTXO> txOutsCreated = new LinkedList<>(); long sigOps = 0; if (!params.isCheckpoint(newBlock.getHeight())) { for (Transaction tx : transactions) { Sha256Hash hash = tx.getTxId(); if (blockStore.hasUnspentOutputs(hash, tx.getOutputs().size())) throw new VerificationException("Block failed BIP30 test!"); } } Coin totalFees = Coin.ZERO; Coin coinbaseValue = null; if (scriptVerificationExecutor.isShutdown()) scriptVerificationExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); List<Future<VerificationException>> listScriptVerificationResults = new ArrayList<>(transactions.size()); for (final Transaction tx : transactions) { final Set<VerifyFlag> verifyFlags = params.getTransactionVerificationFlags(newBlock.getHeader(), tx, getVersionTally(), Integer.SIZE); boolean isCoinBase = tx.isCoinBase(); Coin valueIn = Coin.ZERO; Coin valueOut = Coin.ZERO; final List<Script> prevOutScripts = new LinkedList<>(); if (!isCoinBase) { for (int index = 0; index < tx.getInputs().size(); index++) { final TransactionInput in = tx.getInput(index); final UTXO prevOut = blockStore.getTransactionOutput(in.getOutpoint().hash(), in.getOutpoint().index()); if (prevOut == null) throw new VerificationException("Attempted spend of a non-existent or already spent output!"); if (prevOut.isCoinbase() && newBlock.getHeight() - prevOut.getHeight() < params.getSpendableCoinbaseDepth()) throw new VerificationException("Tried to spend coinbase at depth " + (newBlock.getHeight() - prevOut.getHeight())); valueIn = valueIn.add(prevOut.getValue()); if (verifyFlags.contains(VerifyFlag.P2SH)) { if (ScriptPattern.isP2SH(prevOut.getScript())) sigOps += Script.getP2SHSigOpCount(in.getScriptBytes()); if (sigOps > Block.MAX_BLOCK_SIGOPS) throw new VerificationException("Too many P2SH SigOps in block"); } // TODO: Enforce DER signature format prevOutScripts.add(prevOut.getScript()); blockStore.removeUnspentTransactionOutput(prevOut); txOutsSpent.add(prevOut); } } Sha256Hash hash = tx.getTxId(); for (TransactionOutput out : tx.getOutputs()) { valueOut = valueOut.add(out.getValue()); Script script = getScript(out.getScriptBytes()); UTXO newOut = new UTXO(hash, out.getIndex(), out.getValue(), newBlock.getHeight(), isCoinBase, script, getScriptAddress(script)); blockStore.addUnspentTransactionOutput(newOut); txOutsCreated.add(newOut); } // All values were already checked for being non-negative (as it is verified in Transaction.verify()) // but we check again here just for defence in depth. Transactions with zero output value are OK. if (valueOut.signum() < 0 || params.network().exceedsMaxMoney(valueOut)) throw new VerificationException("Transaction output value out of range"); if (isCoinBase) { coinbaseValue = valueOut; } else { if (valueIn.compareTo(valueOut) < 0 || params.network().exceedsMaxMoney(valueIn)) throw new VerificationException("Transaction input value out of range"); totalFees = totalFees.add(valueIn.subtract(valueOut)); } if (!isCoinBase) { // Because correctlySpends modifies transactions, this must come after we are done with tx FutureTask<VerificationException> future = new FutureTask<>(new Verifier(tx, prevOutScripts, verifyFlags)); scriptVerificationExecutor.execute(future); listScriptVerificationResults.add(future); } } if (params.network().exceedsMaxMoney(totalFees) || getBlockInflation(newBlock.getHeight()).add(totalFees).compareTo(coinbaseValue) < 0) throw new VerificationException("Transaction fees out of range"); txOutChanges = new TransactionOutputChanges(txOutsCreated, txOutsSpent); for (Future<VerificationException> future : listScriptVerificationResults) { VerificationException e; try { e = future.get(); } catch (InterruptedException thrownE) { throw new RuntimeException(thrownE); // Shouldn't happen } catch (ExecutionException thrownE) { log.error("Script.correctlySpends threw a non-normal exception: " + thrownE.getCause()); throw new VerificationException("Bug in Script.correctlySpends, likely script malformed in some new and interesting way.", thrownE); } if (e != null) throw e; } } else { txOutChanges = block.getTxOutChanges(); if (!params.isCheckpoint(newBlock.getHeight())) for (UTXO out : txOutChanges.txOutsCreated) { Sha256Hash hash = out.getHash(); if (blockStore.getTransactionOutput(hash, out.getIndex()) != null) throw new VerificationException("Block failed BIP30 test!"); } for (UTXO out : txOutChanges.txOutsCreated) blockStore.addUnspentTransactionOutput(out); for (UTXO out : txOutChanges.txOutsSpent) blockStore.removeUnspentTransactionOutput(out); } } catch (VerificationException | BlockStoreException e) { scriptVerificationExecutor.shutdownNow(); blockStore.abortDatabaseBatchWrite(); throw e; } return txOutChanges; } /** * This is broken for blocks that do not pass BIP30, so all BIP30-failing blocks which are allowed to fail BIP30 * must be checkpointed. */ @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 | BlockStoreException e) { blockStore.abortDatabaseBatchWrite(); throw e; } } @Override protected void doSetChainHead(StoredBlock chainHead) throws BlockStoreException { checkState(lock.isHeldByCurrentThread()); blockStore.setVerifiedChainHead(chainHead); blockStore.commitDatabaseBatchWrite(); } @Override protected void notSettingChainHead() throws BlockStoreException { blockStore.abortDatabaseBatchWrite(); } @Override protected StoredBlock getStoredBlockInCurrentScope(Sha256Hash hash) throws BlockStoreException { checkState(lock.isHeldByCurrentThread()); return blockStore.getOnceUndoableStoredBlock(hash); } private Coin getBlockInflation(int height) { return ((BitcoinNetworkParams) params).getBlockInflation(height); } }
26,049
49.779727
156
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/Services.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.internal.InternalUtils; import java.nio.Buffer; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.LinkedList; import java.util.List; import java.util.Objects; /** * Wrapper for services bitfield used in various messages of the Bitcoin protocol. Each bit represents a node service, * e.g. {@link #NODE_NETWORK} if the node serves the full blockchain. * <p> * Instances of this class are immutable and should be treated as Java * <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/doc-files/ValueBased.html#Value-basedClasses">value-based</a>. */ public class Services { /** A service bit that denotes whether the peer has a full copy of the block chain or not. */ public static final int NODE_NETWORK = 1 << 0; /** A service bit that denotes whether the peer supports BIP37 bloom filters or not. The service bit is defined in BIP111. */ public static final int NODE_BLOOM = 1 << 2; /** Indicates that a node can be asked for blocks and transactions including witness data. */ public static final int NODE_WITNESS = 1 << 3; /** A service bit that denotes whether the peer has at least the last two days worth of blockchain (BIP159). */ public static final int NODE_NETWORK_LIMITED = 1 << 10; /** A service bit used by Bitcoin-ABC to announce Bitcoin Cash nodes. */ public static final int NODE_BITCOIN_CASH = 1 << 5; /** Number of bytes of this bitfield. */ public static final int BYTES = 8; private final long bits; /** * Wrap 64 bits, each representing a node service. * * @param bits bits to wrap * @return wrapped service bits */ public static Services of(long bits) { return new Services(bits); } /** * Constructs a services bitfield representing "no node services". * * @return wrapped service bits */ public static Services none() { return new Services(0); } /** * Construct a services bitfield by reading from the given buffer. * * @param buf buffer to read from * @return wrapped service bits * @throws BufferUnderflowException if the read services bitfield extends beyond the remaining bytes of the buffer */ public static Services read(ByteBuffer buf) throws BufferUnderflowException { return new Services(buf.order(ByteOrder.LITTLE_ENDIAN).getLong()); } private Services(long bits) { this.bits = bits; } /** * Gets the 64 bits of this bitfield, each representing a node service. * * @return the service bits */ public long bits() { return bits; } /** * Checks if this bitfield signals any node services at all. * * @return true if at least one service is signaled, false otherwise */ public boolean hasAny() { return bits != 0; } /** * Checks if given specific node services are signaled by this bitfield. * * @param bitmask bitmask representing the services to be checked for * @return true if the given services are all signaled, false otherwise */ public boolean has(long bitmask) { return (bits & bitmask) == bitmask; } /** * Checks if at least one of the given node services is signaled by this bitfield. * * @param bitmask bitmask representing the services to be checked for * @return true if at least one of the given services is signaled, false otherwise */ public boolean anyOf(long bitmask) { return (bits & bitmask) != 0; } /** * Write the node service bits into the given buffer. * * @param buf buffer to write into * @return the buffer * @throws BufferOverflowException if the service bits don't fit the remaining buffer */ public ByteBuffer write(ByteBuffer buf) throws BufferOverflowException { buf.order(ByteOrder.LITTLE_ENDIAN).putLong(bits); return buf; } /** * Allocates a byte array and writes the node service bits into it. * * @return byte array containing the service bits */ public byte[] serialize() { return write(ByteBuffer.allocate(BYTES)).array(); } public String toString() { long bits = this.bits; List<String> strings = new LinkedList<>(); if ((bits & NODE_NETWORK) == NODE_NETWORK) { strings.add("NETWORK"); bits &= ~NODE_NETWORK; } if ((bits & NODE_BLOOM) == NODE_BLOOM) { strings.add("BLOOM"); bits &= ~NODE_BLOOM; } if ((bits & NODE_WITNESS) == NODE_WITNESS) { strings.add("WITNESS"); bits &= ~NODE_WITNESS; } if ((bits & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) { strings.add("NETWORK_LIMITED"); bits &= ~NODE_NETWORK_LIMITED; } if (bits != 0) strings.add("remaining: " + Long.toBinaryString(bits)); return InternalUtils.joiner(", ").join(strings); } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return this.bits == ((Services) o).bits; } @Override public int hashCode() { return Objects.hash(this.bits); } }
6,117
32.431694
145
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/Peer.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.base.MoreObjects; import com.google.common.base.Strings; import com.google.common.base.Throwables; import net.jcip.annotations.GuardedBy; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.listeners.AddressEventListener; import org.bitcoinj.core.listeners.BlocksDownloadedEventListener; import org.bitcoinj.core.listeners.ChainDownloadStartedEventListener; import org.bitcoinj.core.listeners.GetDataEventListener; import org.bitcoinj.core.listeners.OnTransactionBroadcastListener; import org.bitcoinj.core.listeners.PeerConnectedEventListener; import org.bitcoinj.core.listeners.PeerDisconnectedEventListener; import org.bitcoinj.core.listeners.PreMessageReceivedEventListener; import org.bitcoinj.net.NioClient; import org.bitcoinj.net.NioClientManager; import org.bitcoinj.net.StreamConnection; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.base.internal.FutureUtils; import org.bitcoinj.utils.ListenableCompletableFuture; import org.bitcoinj.utils.ListenerRegistration; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.Wallet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.net.SocketAddress; import java.time.Duration; import java.time.Instant; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>A Peer handles the high level communication with a Bitcoin node, extending a {@link PeerSocketHandler} which * handles low-level message (de)serialization.</p> * * <p>Note that timeouts are handled by the implemented * {@link org.bitcoinj.net.TimeoutHandler} and timeout is automatically disabled (using * {@link org.bitcoinj.net.TimeoutHandler#setTimeoutEnabled(boolean)}) once the version * handshake completes.</p> */ public class Peer extends PeerSocketHandler { private static final Logger log = LoggerFactory.getLogger(Peer.class); protected final ReentrantLock lock = Threading.lock(Peer.class); private final NetworkParameters params; private final AbstractBlockChain blockChain; private final long requiredServices; private final Context context; private final CopyOnWriteArrayList<ListenerRegistration<BlocksDownloadedEventListener>> blocksDownloadedEventListeners = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<ListenerRegistration<ChainDownloadStartedEventListener>> chainDownloadStartedEventListeners = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<ListenerRegistration<PeerConnectedEventListener>> connectedEventListeners = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<ListenerRegistration<PeerDisconnectedEventListener>> disconnectedEventListeners = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<ListenerRegistration<GetDataEventListener>> getDataEventListeners = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<ListenerRegistration<PreMessageReceivedEventListener>> preMessageReceivedEventListeners = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<ListenerRegistration<OnTransactionBroadcastListener>> onTransactionEventListeners = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<ListenerRegistration<AddressEventListener>> addressEventListeners = new CopyOnWriteArrayList<>(); // Whether to try and download blocks and transactions from this peer. Set to false by PeerGroup if not the // primary peer. This is to avoid redundant work and concurrency problems with downloading the same chain // in parallel. private volatile boolean vDownloadData; // The version data to announce to the other side of the connections we make: useful for setting our "user agent" // equivalent and other things. private final VersionMessage versionMessage; // Maximum depth up to which pending transaction dependencies are downloaded, or 0 for disabled. private volatile int vDownloadTxDependencyDepth; // How many block messages the peer has announced to us. Peers only announce blocks that attach to their best chain // so we can use this to calculate the height of the peers chain, by adding it to the initial height in the version // message. This method can go wrong if the peer re-orgs onto a shorter (but harder) chain, however, this is rare. private final AtomicInteger blocksAnnounced = new AtomicInteger(); // Each wallet added to the peer will be notified of downloaded transaction data. private final CopyOnWriteArrayList<Wallet> wallets; // A time before which we only download block headers, after that point we download block bodies. @GuardedBy("lock") private Instant fastCatchupTime; // Whether we are currently downloading headers only or block bodies. Starts at true. If the fast catchup time is // set AND our best block is before that date, switch to false until block headers beyond that point have been // received at which point it gets set to true again. This isn't relevant unless vDownloadData is true. @GuardedBy("lock") private boolean downloadBlockBodies = true; // Whether to request filtered blocks instead of full blocks if the protocol version allows for them. @GuardedBy("lock") private boolean useFilteredBlocks = false; // The current Bloom filter set on the connection, used to tell the remote peer what transactions to send us. private volatile BloomFilter vBloomFilter; // The last filtered block we received, we're waiting to fill it out with transactions. private FilteredBlock currentFilteredBlock = null; // If non-null, we should discard incoming filtered blocks because we ran out of keys and are awaiting a new filter // to be calculated by the PeerGroup. The discarded block hashes should be added here so we can re-request them // once we've recalculated and resent a new filter. @GuardedBy("lock") @Nullable private List<Sha256Hash> awaitingFreshFilter; // Keeps track of things we requested internally with getdata but didn't receive yet, so we can avoid re-requests. // It's not quite the same as getDataFutures, as this is used only for getdatas done as part of downloading // the chain and so is lighter weight (we just keep a bunch of hashes not futures). // // It is important to avoid a nasty edge case where we can end up with parallel chain downloads proceeding // simultaneously if we were to receive a newly solved block whilst parts of the chain are streaming to us. private final HashSet<Sha256Hash> pendingBlockDownloads = new HashSet<>(); // Keep references to TransactionConfidence objects for transactions that were announced by a remote peer, but // which we haven't downloaded yet. These objects are de-duplicated by the TxConfidenceTable class. // Once the tx is downloaded (by some peer), the Transaction object that is created will have a reference to // the confidence object held inside it, and it's then up to the event listeners that receive the Transaction // to keep it pinned to the root set if they care about this data. @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") private final HashSet<TransactionConfidence> pendingTxDownloads = new HashSet<>(); private static final int PENDING_TX_DOWNLOADS_LIMIT = 100; // The lowest version number we're willing to accept. Lower than this will result in an immediate disconnect. private volatile int vMinProtocolVersion; // When an API user explicitly requests a block or transaction from a peer, the InventoryItem is put here // whilst waiting for the response. Is not used for downloads Peer generates itself. private static class GetDataRequest extends CompletableFuture { final Sha256Hash hash; public GetDataRequest(Sha256Hash hash) { this.hash = hash; } } // TODO: The types/locking should be rationalised a bit. private final Queue<GetDataRequest> getDataFutures; @GuardedBy("getAddrFutures") private final LinkedList<CompletableFuture<AddressMessage>> getAddrFutures; // Outstanding pings against this peer and how long the last one took to complete. private final ReentrantLock pingIntervalsLock = new ReentrantLock(); @GuardedBy("pingIntervalsLock") private final Deque<Duration> pingIntervals = new ArrayDeque<>(PING_MOVING_AVERAGE_WINDOW); private volatile Duration lastPing = null; // should only be written while holding pingIntervalsLock private volatile Duration averagePing = null; // should only be written while holding pingIntervalsLock private final CopyOnWriteArrayList<PendingPing> pendingPings; // Disconnect from a peer that is not responding to Pings private static final int PENDING_PINGS_LIMIT = 50; private static final int PING_MOVING_AVERAGE_WINDOW = 20; private volatile VersionMessage vPeerVersionMessage; private volatile Coin vFeeFilter; // A future which completes (with this) when the connection is open private final CompletableFuture<Peer> connectionOpenFuture = new CompletableFuture<>(); private final CompletableFuture<Peer> outgoingVersionHandshakeFuture = new CompletableFuture<>(); private final CompletableFuture<Peer> incomingVersionHandshakeFuture = new CompletableFuture<>(); private final CompletableFuture<Peer> versionHandshakeFuture = outgoingVersionHandshakeFuture .thenCombine(incomingVersionHandshakeFuture, (peer1, peer2) -> { Objects.requireNonNull(peer1); checkState(peer1 == peer2); return peer1; }); /** @deprecated Use {@link #Peer(NetworkParameters, VersionMessage, PeerAddress, AbstractBlockChain)}. */ @Deprecated public Peer(NetworkParameters params, VersionMessage ver, @Nullable AbstractBlockChain chain, PeerAddress remoteAddress) { this(params, ver, remoteAddress, chain); } /** * <p>Construct a peer that reads/writes from the given block chain. Transactions stored in a {@link TxConfidenceTable} * will have their confidence levels updated when a peer announces it, to reflect the greater likelihood that * the transaction is valid.</p> * * <p>Note that this does <b>NOT</b> make a connection to the given remoteAddress, it only creates a handler for a * connection. If you want to create a one-off connection, create a Peer and pass it to * {@link NioClientManager#openConnection(SocketAddress, StreamConnection)} * or * {@link NioClient#NioClient(SocketAddress, StreamConnection, Duration)}.</p> * * <p>The remoteAddress provided should match the remote address of the peer which is being connected to, and is * used to keep track of which peers relayed transactions and offer more descriptive logging.</p> */ public Peer(NetworkParameters params, VersionMessage ver, PeerAddress remoteAddress, @Nullable AbstractBlockChain chain) { this(params, ver, remoteAddress, chain, 0, Integer.MAX_VALUE); } /** * <p>Construct a peer that reads/writes from the given block chain. Transactions stored in a {@link TxConfidenceTable} * will have their confidence levels updated when a peer announces it, to reflect the greater likelihood that * the transaction is valid.</p> * * <p>Note that this does <b>NOT</b> make a connection to the given remoteAddress, it only creates a handler for a * connection. If you want to create a one-off connection, create a Peer and pass it to * {@link NioClientManager#openConnection(SocketAddress, StreamConnection)} * or * {@link NioClient#NioClient(SocketAddress, StreamConnection, Duration)}.</p> * * <p>The remoteAddress provided should match the remote address of the peer which is being connected to, and is * used to keep track of which peers relayed transactions and offer more descriptive logging.</p> */ public Peer(NetworkParameters params, VersionMessage ver, PeerAddress remoteAddress, @Nullable AbstractBlockChain chain, long requiredServices, int downloadTxDependencyDepth) { super(params, remoteAddress); this.params = Objects.requireNonNull(params); this.versionMessage = Objects.requireNonNull(ver); this.vDownloadTxDependencyDepth = chain != null ? downloadTxDependencyDepth : 0; this.blockChain = chain; // Allowed to be null. this.requiredServices = requiredServices; this.vDownloadData = chain != null; this.getDataFutures = new ConcurrentLinkedQueue<>(); this.getAddrFutures = new LinkedList<>(); this.fastCatchupTime = params.getGenesisBlock().time(); this.pendingPings = new CopyOnWriteArrayList<>(); this.vMinProtocolVersion = ProtocolVersion.MINIMUM.intValue(); this.wallets = new CopyOnWriteArrayList<>(); this.context = Context.get(); this.versionHandshakeFuture.thenRunAsync(this::versionHandshakeComplete, Threading.SAME_THREAD); } /** * <p>Construct a peer that reads/writes from the given chain. Automatically creates a VersionMessage for you from * the given software name/version strings, which should be something like "MySimpleTool", "1.0" and which will tell * the remote node to relay transaction inv messages before it has received a filter.</p> * * <p>Note that this does <b>NOT</b> make a connection to the given remoteAddress, it only creates a handler for a * connection. If you want to create a one-off connection, create a Peer and pass it to * {@link NioClientManager#openConnection(SocketAddress, StreamConnection)} * or * {@link NioClient#NioClient(SocketAddress, StreamConnection, Duration)}.</p> * * <p>The remoteAddress provided should match the remote address of the peer which is being connected to, and is * used to keep track of which peers relayed transactions and offer more descriptive logging.</p> */ public Peer(NetworkParameters params, AbstractBlockChain blockChain, PeerAddress peerAddress, String thisSoftwareName, String thisSoftwareVersion) { this(params, new VersionMessage(params, blockChain.getBestChainHeight()), blockChain, peerAddress); this.versionMessage.appendToSubVer(thisSoftwareName, thisSoftwareVersion, null); } /** Registers a listener that is invoked when new blocks are downloaded. */ public void addBlocksDownloadedEventListener(BlocksDownloadedEventListener listener) { addBlocksDownloadedEventListener(Threading.USER_THREAD, listener); } /** Registers a listener that is invoked when new blocks are downloaded. */ public void addBlocksDownloadedEventListener(Executor executor, BlocksDownloadedEventListener listener) { blocksDownloadedEventListeners.add(new ListenerRegistration(listener, executor)); } /** Registers a listener that is invoked when a blockchain downloaded starts. */ public void addChainDownloadStartedEventListener(ChainDownloadStartedEventListener listener) { addChainDownloadStartedEventListener(Threading.USER_THREAD, listener); } /** Registers a listener that is invoked when a blockchain downloaded starts. */ public void addChainDownloadStartedEventListener(Executor executor, ChainDownloadStartedEventListener listener) { chainDownloadStartedEventListeners.add(new ListenerRegistration(listener, executor)); } /** Registers a listener that is invoked when a peer is connected. */ public void addConnectedEventListener(PeerConnectedEventListener listener) { addConnectedEventListener(Threading.USER_THREAD, listener); } /** Registers a listener that is invoked when a peer is connected. */ public void addConnectedEventListener(Executor executor, PeerConnectedEventListener listener) { connectedEventListeners.add(new ListenerRegistration(listener, executor)); } /** Registers a listener that is invoked when a peer is disconnected. */ public void addDisconnectedEventListener(PeerDisconnectedEventListener listener) { addDisconnectedEventListener(Threading.USER_THREAD, listener); } /** Registers a listener that is invoked when a peer is disconnected. */ public void addDisconnectedEventListener(Executor executor, PeerDisconnectedEventListener listener) { disconnectedEventListeners.add(new ListenerRegistration(listener, executor)); } /** Registers a listener that is called when messages are received. */ public void addGetDataEventListener(GetDataEventListener listener) { addGetDataEventListener(Threading.USER_THREAD, listener); } /** Registers a listener that is called when messages are received. */ public void addGetDataEventListener(Executor executor, GetDataEventListener listener) { getDataEventListeners.add(new ListenerRegistration<>(listener, executor)); } /** Registers a listener that is called when a transaction is broadcast across the network */ public void addOnTransactionBroadcastListener(OnTransactionBroadcastListener listener) { addOnTransactionBroadcastListener(Threading.USER_THREAD, listener); } /** Registers a listener that is called when a transaction is broadcast across the network */ public void addOnTransactionBroadcastListener(Executor executor, OnTransactionBroadcastListener listener) { onTransactionEventListeners.add(new ListenerRegistration<>(listener, executor)); } /** Registers a listener that is called immediately before a message is received */ public void addPreMessageReceivedEventListener(PreMessageReceivedEventListener listener) { addPreMessageReceivedEventListener(Threading.USER_THREAD, listener); } /** Registers a listener that is called immediately before a message is received */ public void addPreMessageReceivedEventListener(Executor executor, PreMessageReceivedEventListener listener) { preMessageReceivedEventListeners.add(new ListenerRegistration<>(listener, executor)); } /** Registers a listener that is called when addr or addrv2 messages are received. */ public void addAddressEventListener(AddressEventListener listener) { addAddressEventListener(Threading.USER_THREAD, listener); } /** Registers a listener that is called when addr or addrv2 messages are received. */ public void addAddressEventListener(Executor executor, AddressEventListener listener) { addressEventListeners.add(new ListenerRegistration<>(listener, executor)); } public boolean removeBlocksDownloadedEventListener(BlocksDownloadedEventListener listener) { return ListenerRegistration.removeFromList(listener, blocksDownloadedEventListeners); } public boolean removeChainDownloadStartedEventListener(ChainDownloadStartedEventListener listener) { return ListenerRegistration.removeFromList(listener, chainDownloadStartedEventListeners); } public boolean removeConnectedEventListener(PeerConnectedEventListener listener) { return ListenerRegistration.removeFromList(listener, connectedEventListeners); } public boolean removeDisconnectedEventListener(PeerDisconnectedEventListener listener) { return ListenerRegistration.removeFromList(listener, disconnectedEventListeners); } public boolean removeGetDataEventListener(GetDataEventListener listener) { return ListenerRegistration.removeFromList(listener, getDataEventListeners); } public boolean removeOnTransactionBroadcastListener(OnTransactionBroadcastListener listener) { return ListenerRegistration.removeFromList(listener, onTransactionEventListeners); } public boolean removePreMessageReceivedEventListener(PreMessageReceivedEventListener listener) { return ListenerRegistration.removeFromList(listener, preMessageReceivedEventListeners); } public boolean removeAddressEventListener(AddressEventListener listener) { return ListenerRegistration.removeFromList(listener, addressEventListeners); } @Override public String toString() { final MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues(); helper.addValue(getAddress()); helper.add("version", vPeerVersionMessage.clientVersion); helper.add("subVer", vPeerVersionMessage.subVer); if (vPeerVersionMessage.localServices.hasAny()) helper.add("services", vPeerVersionMessage.localServices.toString()); helper.add("time", TimeUtils.dateTimeFormat(vPeerVersionMessage.time)); helper.add("height", vPeerVersionMessage.bestHeight); return helper.toString(); } @Override protected void timeoutOccurred() { super.timeoutOccurred(); if (!connectionOpenFuture.isDone()) { connectionClosed(); // Invoke the event handlers to tell listeners e.g. PeerGroup that we never managed to connect. } } @Override public void connectionClosed() { for (final ListenerRegistration<PeerDisconnectedEventListener> registration : disconnectedEventListeners) { registration.executor.execute(() -> registration.listener.onPeerDisconnected(Peer.this, 0)); } } @Override public void connectionOpened() { // Announce ourselves. This has to come first to connect to clients beyond v0.3.20.2 which wait to hear // from us until they send their version message back. PeerAddress address = getAddress(); log.info("Announcing to {} as: {}", address == null ? "Peer" : address.toSocketAddress(), versionMessage.subVer); sendMessage(versionMessage); connectionOpenFuture.complete(this); // When connecting, the remote peer sends us a version message with various bits of // useful data in it. We need to know the peer protocol version before we can talk to it. } /** * Provides a ListenableCompletableFuture that can be used to wait for the socket to connect. A socket connection does not * mean that protocol handshake has occurred. */ public ListenableCompletableFuture<Peer> getConnectionOpenFuture() { return ListenableCompletableFuture.of(connectionOpenFuture); } public ListenableCompletableFuture<Peer> getVersionHandshakeFuture() { return ListenableCompletableFuture.of(versionHandshakeFuture); } @Override protected void processMessage(Message m) throws Exception { // Allow event listeners to filter the message stream. Listeners are allowed to drop messages by // returning null. for (ListenerRegistration<PreMessageReceivedEventListener> registration : preMessageReceivedEventListeners) { // Skip any listeners that are supposed to run in another thread as we don't want to block waiting // for it, which might cause circular deadlock. if (registration.executor == Threading.SAME_THREAD) { m = registration.listener.onPreMessageReceived(this, m); if (m == null) break; } } if (m == null) return; // If we are in the middle of receiving transactions as part of a filtered block push from the remote node, // and we receive something that's not a transaction, then we're done. if (currentFilteredBlock != null && !(m instanceof Transaction)) { endFilteredBlock(currentFilteredBlock); currentFilteredBlock = null; } // No further communication is possible until version handshake is complete. if (!(m instanceof VersionMessage || m instanceof VersionAck || m instanceof SendAddrV2Message || (versionHandshakeFuture.isDone() && !versionHandshakeFuture.isCancelled()))) throw new ProtocolException( "Received " + m.getClass().getSimpleName() + " before version handshake is complete."); if (m instanceof Ping) { processPing((Ping) m); } else if (m instanceof Pong) { processPong((Pong) m); } else if (m instanceof NotFoundMessage) { // This is sent to us when we did a getdata on some transactions that aren't in the peers memory pool. // Because NotFoundMessage is a subclass of InventoryMessage, the test for it must come before the next. processNotFoundMessage((NotFoundMessage) m); } else if (m instanceof InventoryMessage) { processInv((InventoryMessage) m); } else if (m instanceof Block) { processBlock((Block) m); } else if (m instanceof FilteredBlock) { startFilteredBlock((FilteredBlock) m); } else if (m instanceof Transaction) { processTransaction((Transaction) m); } else if (m instanceof GetDataMessage) { processGetData((GetDataMessage) m); } else if (m instanceof AddressMessage) { processAddressMessage((AddressMessage) m); } else if (m instanceof HeadersMessage) { processHeaders((HeadersMessage) m); } else if (m instanceof VersionMessage) { processVersionMessage((VersionMessage) m); } else if (m instanceof VersionAck) { processVersionAck((VersionAck) m); } else if (m instanceof RejectMessage) { log.error("{} {}: Received {}", this, getPeerVersionMessage().subVer, m); } else if (m instanceof SendHeadersMessage) { // We ignore this message, because we don't announce new blocks. } else if (m instanceof FeeFilterMessage) { processFeeFilter((FeeFilterMessage) m); } else { log.warn("{}: Received unhandled message: {}", this, m); } } private void processAddressMessage(AddressMessage message) { for (final ListenerRegistration<AddressEventListener> registration : addressEventListeners) { registration.executor.execute(() -> registration.listener.onAddr(Peer.this, message)); } CompletableFuture<AddressMessage> future; synchronized (getAddrFutures) { future = getAddrFutures.poll(); if (future == null) // Not an addr message we are waiting for. return; } future.complete(message); } private void processVersionMessage(VersionMessage peerVersionMessage) throws ProtocolException { if (vPeerVersionMessage != null) throw new ProtocolException("Got two version messages from peer"); vPeerVersionMessage = peerVersionMessage; // Switch to the new protocol version. log.info(toString()); // bitcoinj is a client mode implementation. That means there's not much point in us talking to other client // mode nodes because we can't download the data from them we need to find/verify transactions. Some bogus // implementations claim to have a block chain in their services field but then report a height of zero, filter // them out here. Services services = peerVersionMessage.services(); if (!services.anyOf(Services.NODE_NETWORK | Services.NODE_NETWORK_LIMITED) || (!params.allowEmptyPeerChain() && peerVersionMessage.bestHeight == 0)) { // Shut down the channel gracefully. log.info("{}: Peer does not have at least a recent part of the block chain.", this); close(); return; } if (!services.has(requiredServices)) { log.info("{}: Peer doesn't support these required services: {}", this, Services.of(requiredServices & ~peerVersionMessage.localServices.bits()).toString()); // Shut down the channel gracefully. close(); return; } if (services.has(Services.NODE_BITCOIN_CASH)) { log.info("{}: Peer follows an incompatible block chain.", this); // Shut down the channel gracefully. close(); return; } if (peerVersionMessage.bestHeight < 0) // In this case, it's a protocol violation. throw new ProtocolException("Peer reports invalid best height: " + peerVersionMessage.bestHeight); // Now it's our turn ... // Send a sendaddrv2 message, indicating that we prefer to receive addrv2 messages. sendMessage(new SendAddrV2Message()); // Send an ACK message stating we accept the peers protocol version. sendMessage(new VersionAck()); if (log.isDebugEnabled()) log.debug("{}: Incoming version handshake complete.", this); incomingVersionHandshakeFuture.complete(this); } private void processVersionAck(VersionAck m) throws ProtocolException { if (vPeerVersionMessage == null) { throw new ProtocolException("got a version ack before version"); } if (outgoingVersionHandshakeFuture.isDone()) { throw new ProtocolException("got more than one version ack"); } if (log.isDebugEnabled()) log.debug("{}: Outgoing version handshake complete.", this); outgoingVersionHandshakeFuture.complete(this); } private void versionHandshakeComplete() { if (log.isDebugEnabled()) log.debug("{}: Handshake complete.", this); setTimeoutEnabled(false); for (final ListenerRegistration<PeerConnectedEventListener> registration : connectedEventListeners) { registration.executor.execute(() -> registration.listener.onPeerConnected(Peer.this, 1)); } // We check min version after onPeerConnected as channel.close() will // call onPeerDisconnected, and we should probably call onPeerConnected first. final int version = vMinProtocolVersion; if (vPeerVersionMessage.clientVersion < version) { log.warn("Connected to a peer speaking protocol version {} but need {}, closing", vPeerVersionMessage.clientVersion, version); close(); } } protected void startFilteredBlock(FilteredBlock m) { // Filtered blocks come before the data that they refer to, so stash it here and then fill it out as // messages stream in. We'll call endFilteredBlock when a non-tx message arrives (eg, another // FilteredBlock) or when a tx that isn't needed by that block is found. A ping message is sent after // a getblocks, to force the non-tx message path. currentFilteredBlock = m; } protected void processNotFoundMessage(NotFoundMessage m) { // This is received when we previously did a getdata but the peer couldn't find what we requested in it's // memory pool. Typically, because we are downloading dependencies of a relevant transaction and reached // the bottom of the dependency tree (where the unconfirmed transactions connect to transactions that are // in the chain). // // We go through and cancel the pending getdata futures for the items we were told weren't found. for (GetDataRequest req : getDataFutures) { for (InventoryItem item : m.getItems()) { if (item.hash.equals(req.hash)) { log.info("{}: Bottomed out dep tree at {}", this, req.hash); req.cancel(true); getDataFutures.remove(req); break; } } } } protected void processHeaders(HeadersMessage m) throws ProtocolException { // Runs in network loop thread for this peer. // // This method can run if a peer just randomly sends us a "headers" message (should never happen), or more // likely when we've requested them as part of chain download using fast catchup. We need to add each block to // the chain if it pre-dates the fast catchup time. If we go past it, we can stop processing the headers and // request the full blocks from that point on instead. boolean downloadBlockBodies; Instant fastCatchupTime; lock.lock(); try { if (blockChain == null) { // Can happen if we are receiving unrequested data, or due to programmer error. log.warn("Received headers when Peer is not configured with a chain."); return; } fastCatchupTime = this.fastCatchupTime; downloadBlockBodies = this.downloadBlockBodies; } finally { lock.unlock(); } try { checkState(!downloadBlockBodies, () -> toString()); for (int i = 0; i < m.getBlockHeaders().size(); i++) { Block header = m.getBlockHeaders().get(i); // Process headers until we pass the fast catchup time, or are about to catch up with the head // of the chain - always process the last block as a full/filtered block to kick us out of the // fast catchup mode (in which we ignore new blocks). boolean passedTime = header.time().compareTo(fastCatchupTime) >= 0; boolean reachedTop = blockChain.getBestChainHeight() >= vPeerVersionMessage.bestHeight; if (!passedTime && !reachedTop) { if (!vDownloadData) { // Not download peer anymore, some other peer probably became better. log.info("Lost download peer status, throwing away downloaded headers."); return; } if (blockChain.add(header)) { // The block was successfully linked into the chain. Notify the user of our progress. invokeOnBlocksDownloaded(header, null); } else { // This block is unconnected - we don't know how to get from it back to the genesis block yet. // That must mean that the peer is buggy or malicious because we specifically requested for // headers that are part of the best chain. throw new ProtocolException("Got unconnected header from peer: " + header.getHashAsString()); } } else { lock.lock(); try { log.info( "Passed the fast catchup time ({}) at height {}, discarding {} headers and requesting full blocks", TimeUtils.dateTimeFormat(fastCatchupTime), blockChain.getBestChainHeight() + 1, m.getBlockHeaders().size() - i); this.downloadBlockBodies = true; // Prevent this request being seen as a duplicate. this.lastGetBlocksBegin = Sha256Hash.ZERO_HASH; blockChainDownloadLocked(Sha256Hash.ZERO_HASH); } finally { lock.unlock(); } return; } } // We added all headers in the message to the chain. Request some more if we got up to the limit, otherwise // we are at the end of the chain. if (m.getBlockHeaders().size() >= HeadersMessage.MAX_HEADERS) { lock.lock(); try { blockChainDownloadLocked(Sha256Hash.ZERO_HASH); } finally { lock.unlock(); } } } catch (VerificationException e) { log.warn("Block header verification failed", e); } catch (PrunedException e) { // Unreachable when in SPV mode. throw new RuntimeException(e); } } protected void processGetData(GetDataMessage getdata) { log.info("{}: Received getdata message: {}", getAddress(), getdata.toString()); ArrayList<Message> items = new ArrayList<>(); for (ListenerRegistration<GetDataEventListener> registration : getDataEventListeners) { if (registration.executor != Threading.SAME_THREAD) continue; List<Message> listenerItems = registration.listener.getData(this, getdata); if (listenerItems == null) continue; items.addAll(listenerItems); } if (items.isEmpty()) { return; } log.info("{}: Sending {} items gathered from listeners to peer", getAddress(), items.size()); for (Message item : items) { sendMessage(item); } } protected void processTransaction(final Transaction tx) throws VerificationException { // Check a few basic syntax issues to ensure the received TX isn't nonsense. tx.verify(params.network(), tx); lock.lock(); try { if (log.isDebugEnabled()) log.debug("{}: Received tx {}", getAddress(), tx.getTxId()); // Label the transaction as coming in from the P2P network (as opposed to being created by us, direct import, // etc). This helps the wallet decide how to risk analyze it later. // // Additionally, by invoking tx.getConfidence(), this tx now pins the confidence data into the heap, meaning // we can stop holding a reference to the confidence object ourselves. It's up to event listeners on the // Peer to stash the tx object somewhere if they want to keep receiving updates about network propagation // and so on. TransactionConfidence confidence = tx.getConfidence(); confidence.setSource(TransactionConfidence.Source.NETWORK); pendingTxDownloads.remove(confidence); if (maybeHandleRequestedData(tx, tx.getTxId())) { return; } if (currentFilteredBlock != null) { if (!currentFilteredBlock.provideTransaction(tx)) { // Got a tx that didn't fit into the filtered block, so we must have received everything. endFilteredBlock(currentFilteredBlock); currentFilteredBlock = null; } // Don't tell wallets or listeners about this tx as they'll learn about it when the filtered block is // fully downloaded instead. return; } // It's a broadcast transaction. Tell all wallets about this tx so they can check if it's relevant or not. for (final Wallet wallet : wallets) { try { if (wallet.isPendingTransactionRelevant(tx)) { if (vDownloadTxDependencyDepth > 0) { // This transaction seems interesting to us, so let's download its dependencies. This has // several purposes: we can check that the sender isn't attacking us by engaging in protocol // abuse games, like depending on a time-locked transaction that will never confirm, or // building huge chains of unconfirmed transactions (again - so they don't confirm and the // money can be taken back with a Finney attack). Knowing the dependencies also lets us // store them in a serialized wallet so we always have enough data to re-announce to the // network and get the payment into the chain, in case the sender goes away and the network // starts to forget. // // TODO: Not all the above things are implemented. // // Note that downloading of dependencies can end up walking around 15 minutes back even // through transactions that have confirmed, as getdata on the remote peer also checks // relay memory not only the mempool. Unfortunately we have no way to know that here. In // practice it should not matter much. downloadDependencies(tx).whenComplete((List<Transaction> dependencies, Throwable throwable) -> { if (throwable == null) { try { log.info("{}: Dependency download complete!", getAddress()); wallet.receivePending(tx, dependencies); } catch (VerificationException e) { log.error("{}: Wallet failed to process pending transaction {}", getAddress(), tx.getTxId()); log.error("Error was: ", e); // Not much more we can do at this point. } } else { log.error("Could not download dependencies of tx {}", tx.getTxId()); log.error("Error was: ", throwable); // Not much more we can do at this point. } }); } else { wallet.receivePending(tx, null); } } } catch (VerificationException e) { log.error("Wallet failed to verify tx", e); // Carry on, listeners may still want to know. } } } finally { lock.unlock(); } // Tell all listeners about this tx so they can decide whether to keep it or not. If no listener keeps a // reference around then the memory pool will forget about it after a while too because it uses weak references. for (final ListenerRegistration<OnTransactionBroadcastListener> registration : onTransactionEventListeners) { registration.executor.execute(() -> registration.listener.onTransaction(Peer.this, tx)); } } /** * <p>Returns a future that wraps a list of all transactions that the given transaction depends on, recursively. * Only transactions in peers memory pools are included; the recursion stops at transactions that are in the * current best chain. So it doesn't make much sense to provide a tx that was already in the best chain and * a precondition checks this.</p> * * <p>For example, if tx has 2 inputs that connect to transactions A and B, and transaction B is unconfirmed and * has one input connecting to transaction C that is unconfirmed, and transaction C connects to transaction D * that is in the chain, then this method will return either {B, C} or {C, B}. No ordering is guaranteed.</p> * * <p>This method is useful for apps that want to learn about how long an unconfirmed transaction might take * to confirm, by checking for unexpectedly time locked transactions, unusually deep dependency trees or fee-paying * transactions that depend on unconfirmed free transactions.</p> * * <p>Note that dependencies downloaded this way will not trigger the onTransaction method of event listeners.</p> * * @param tx The transaction * @return A Future for a list of dependent transactions */ public ListenableCompletableFuture<List<Transaction>> downloadDependencies(Transaction tx) { TransactionConfidence.ConfidenceType txConfidence = tx.getConfidence().getConfidenceType(); checkArgument(txConfidence != TransactionConfidence.ConfidenceType.BUILDING); log.info("{}: Downloading dependencies of {}", getAddress(), tx.getTxId()); // future will be invoked when the entire dependency tree has been walked and the results compiled. return ListenableCompletableFuture.of(downloadDependenciesInternal(tx, vDownloadTxDependencyDepth, 0)); } /** * Internal, recursive dependency downloader * @param rootTx The root transaction * @param maxDepth maximum recursion depth * @param depth current recursion depth (starts at 0) * @return A Future for a list of dependent transactions */ protected CompletableFuture<List<Transaction>> downloadDependenciesInternal(Transaction rootTx, int maxDepth, int depth) { final CompletableFuture<List<Transaction>> resultFuture = new CompletableFuture<>(); // We want to recursively grab its dependencies. This is so listeners can learn important information like // whether a transaction is dependent on a timelocked transaction or has an unexpectedly deep dependency tree // or depends on a no-fee transaction. // We may end up requesting transactions that we've already downloaded and thrown away here. // There may be multiple inputs that connect to the same transaction. Set<Sha256Hash> txIdsToRequest = rootTx.getInputs().stream() .map(input -> input.getOutpoint().hash()) .collect(Collectors.toSet()); lock.lock(); try { if (txIdsToRequest.size() > 1) log.info("{}: Requesting {} transactions for depth {} dep resolution", getAddress(), txIdsToRequest.size(), depth + 1); // Build the request for the missing dependencies. GetDataMessage getdata = buildMultiTransactionDataMessage(txIdsToRequest); // Create futures for each TxId this request will produce List<GetDataRequest> futures = txIdsToRequest.stream() .map(GetDataRequest::new) .collect(Collectors.toList()); // Add the futures to the queue of outstanding requests getDataFutures.addAll(futures); CompletableFuture<List<Transaction>> successful = FutureUtils.successfulAsList((List) futures); successful.whenComplete((transactionsWithNulls, throwable) -> { if (throwable == null) { // If no exception/throwable, then success // Note that transactionsWithNulls will contain "null" for any positions that weren't successful. List<Transaction> transactions = transactionsWithNulls.stream() .filter(Objects::nonNull) .peek(tx -> log.info("{}: Downloaded dependency of {}: {}", getAddress(), rootTx.getTxId(), tx.getTxId())) .collect(Collectors.toList()); // Once all transactions either were received, or we know there are no more to come ... List<CompletableFuture<List<Transaction>>> childFutures = (depth + 1 >= maxDepth) ? Collections.emptyList() : // if not at max depth, build a list of child transaction-list futures transactions.stream() .map(tx -> downloadDependenciesInternal(tx, maxDepth, depth + 1)) .collect(Collectors.toList()); if (childFutures.size() == 0) { // Short-circuit: we're at the bottom of this part of the tree. resultFuture.complete(transactions); } else { // There are some children to download. Wait until it's done (and their children and their // children...) to inform the caller that we're finished. CompletableFuture<List<List<Transaction>>> allSuccessfulChildren = FutureUtils.successfulAsList(childFutures); allSuccessfulChildren.whenComplete((successfulChildrenWithNulls, nestedThrowable) -> { if (nestedThrowable == null) { // If no exception/throwable, then success resultFuture.complete(concatDependencies(transactions, successfulChildrenWithNulls)); } else { // nestedThrowable is not null, an exception occurred resultFuture.completeExceptionally(nestedThrowable); } }); } } else { // throwable is not null, an exception occurred resultFuture.completeExceptionally(throwable); } }); // Start the operation. sendMessage(getdata); } catch (Exception e) { log.error("{}: Couldn't send getdata in downloadDependencies({})", this, rootTx.getTxId(), e); resultFuture.completeExceptionally(e); return resultFuture; } finally { lock.unlock(); } return resultFuture; } /** * Build a GetDataMessage to query multiple transactions by ID * @param txIds A set of transaction IDs to query * @return A GetDataMessage that will query those IDs */ private GetDataMessage buildMultiTransactionDataMessage(Set<Sha256Hash> txIds) { GetDataMessage getdata = new GetDataMessage(); txIds.forEach(txId -> getdata.addTransaction(txId, vPeerVersionMessage.services().has(Services.NODE_WITNESS))); return getdata; } /** * Combine the direct results and the child dependencies. Make sure to filter out nulls from * {@code Futures.successfulAsList}. * @param results direct dependencies of a given transaction * @param children A list of lists of child dependencies * @return A list of all dependencies */ private List<Transaction> concatDependencies(List<Transaction> results, List<List<Transaction>> children) { return Stream.concat( results.stream(), children.stream().filter(Objects::nonNull).flatMap(Collection::stream) ) .filter(Objects::nonNull) .collect(Collectors.toList()); } protected void processBlock(Block m) { if (log.isDebugEnabled()) log.debug("{}: Received broadcast block {}", getAddress(), m.getHashAsString()); // Was this block requested by getBlock()? if (maybeHandleRequestedData(m, m.getHash())) return; if (blockChain == null) { if (log.isDebugEnabled()) log.debug("Received block but was not configured with an AbstractBlockChain"); return; } // Did we lose download peer status after requesting block data? if (!vDownloadData) { if (log.isDebugEnabled()) log.debug("{}: Received block we did not ask for: {}", getAddress(), m.getHashAsString()); return; } pendingBlockDownloads.remove(m.getHash()); try { // Otherwise it's a block sent to us because the peer thought we needed it, so add it to the block chain. if (blockChain.add(m)) { // The block was successfully linked into the chain. Notify the user of our progress. invokeOnBlocksDownloaded(m, null); } else { // This block is an orphan - we don't know how to get from it back to the genesis block yet. That // must mean that there are blocks we are missing, so do another getblocks with a new block locator // to ask the peer to send them to us. This can happen during the initial block chain download where // the peer will only send us 500 at a time and then sends us the head block expecting us to request // the others. // // We must do two things here: // (1) Request from current top of chain to the oldest ancestor of the received block in the orphan set // (2) Filter out duplicate getblock requests (done in blockChainDownloadLocked). // // The reason for (1) is that otherwise if new blocks were solved during the middle of chain download // we'd do a blockChainDownloadLocked() on the new best chain head, which would cause us to try and grab the // chain twice (or more!) on the same connection! The block chain would filter out the duplicates but // only at a huge speed penalty. By finding the orphan root we ensure every getblocks looks the same // no matter how many blocks are solved, and therefore that the (2) duplicate filtering can work. // // We only do this if we are not currently downloading headers. If we are then we don't want to kick // off a request for lots more headers in parallel. lock.lock(); try { if (downloadBlockBodies) { final Block orphanRoot = Objects.requireNonNull(blockChain.getOrphanRoot(m.getHash())); blockChainDownloadLocked(orphanRoot.getHash()); } else { log.info("Did not start chain download on solved block due to in-flight header download."); } } finally { lock.unlock(); } } } catch (VerificationException e) { // We don't want verification failures to kill the thread. log.warn("{}: Block verification failed", getAddress(), e); } catch (PrunedException e) { // Unreachable when in SPV mode. throw new RuntimeException(e); } } // TODO: Fix this duplication. protected void endFilteredBlock(FilteredBlock m) { if (log.isDebugEnabled()) log.debug("{}: Received broadcast filtered block {}", getAddress(), m.getHash().toString()); if (!vDownloadData) { if (log.isDebugEnabled()) log.debug("{}: Received block we did not ask for: {}", getAddress(), m.getHash().toString()); return; } if (blockChain == null) { if (log.isDebugEnabled()) log.debug("Received filtered block but was not configured with an AbstractBlockChain"); return; } // Note that we currently do nothing about peers which maliciously do not include transactions which // actually match our filter or which simply do not send us all the transactions we need: it can be fixed // by cross-checking peers against each other. pendingBlockDownloads.remove(m.getBlockHeader().getHash()); try { // It's a block sent to us because the peer thought we needed it, so maybe add it to the block chain. // The FilteredBlock m here contains a list of hashes, and may contain Transaction objects for a subset // of the hashes (those that were sent to us by the remote peer). Any hashes that haven't had a tx // provided in processTransaction are ones that were announced to us previously via an 'inv' so the // assumption is we have already downloaded them and either put them in the wallet, or threw them away // for being false positives. // // TODO: Fix the following protocol race. // It is possible for this code to go wrong such that we miss a confirmation. If the remote peer announces // a relevant transaction via an 'inv' and then it immediately announces the block that confirms // the tx before we had a chance to download it+its dependencies and provide them to the wallet, then we // will add the block to the chain here without the tx being in the wallet and thus it will miss its // confirmation and become stuck forever. The fix is to notice that there's a pending getdata for a tx // that appeared in this block and delay processing until it arrived ... it's complicated by the fact that // the data may be requested by a different peer to this one. // Ask each wallet attached to the peer/blockchain if this block exhausts the list of data items // (keys/addresses) that were used to calculate the previous filter. If so, then it's possible this block // is only partial. Check for discarding first so we don't check for exhaustion on blocks we already know // we're going to discard, otherwise redundant filters might end up being queued and calculated. lock.lock(); try { if (awaitingFreshFilter != null) { log.info("Discarding block {} because we're still waiting for a fresh filter", m.getHash()); // We must record the hashes of blocks we discard because you cannot do getblocks twice on the same // range of blocks and get an inv both times, due to the codepath in Bitcoin Core hitting // CPeer::PushInventory() which checks CPeer::setInventoryKnown and thus deduplicates. awaitingFreshFilter.add(m.getHash()); return; // Chain download process is restarted via a call to setBloomFilter. } else if (checkForFilterExhaustion(m)) { // Yes, so we must abandon the attempt to process this block and any further blocks we receive, // then wait for the Bloom filter to be recalculated, sent to this peer and for the peer to acknowledge // that the new filter is now in use (which we have to simulate with a ping/pong), and then we can // safely restart the chain download with the new filter that contains a new set of lookahead keys. log.info("Bloom filter exhausted whilst processing block {}, discarding", m.getHash()); awaitingFreshFilter = new LinkedList<>(); awaitingFreshFilter.add(m.getHash()); awaitingFreshFilter.addAll(blockChain.drainOrphanBlocks()); return; // Chain download process is restarted via a call to setBloomFilter. } } finally { lock.unlock(); } if (blockChain.add(m)) { // The block was successfully linked into the chain. Notify the user of our progress. invokeOnBlocksDownloaded(m.getBlockHeader(), m); } else { // This block is an orphan - we don't know how to get from it back to the genesis block yet. That // must mean that there are blocks we are missing, so do another getblocks with a new block locator // to ask the peer to send them to us. This can happen during the initial block chain download where // the peer will only send us 500 at a time and then sends us the head block expecting us to request // the others. // // We must do two things here: // (1) Request from current top of chain to the oldest ancestor of the received block in the orphan set // (2) Filter out duplicate getblock requests (done in blockChainDownloadLocked). // // The reason for (1) is that otherwise if new blocks were solved during the middle of chain download // we'd do a blockChainDownloadLocked() on the new best chain head, which would cause us to try and grab the // chain twice (or more!) on the same connection! The block chain would filter out the duplicates but // only at a huge speed penalty. By finding the orphan root we ensure every getblocks looks the same // no matter how many blocks are solved, and therefore that the (2) duplicate filtering can work. lock.lock(); try { final Block orphanRoot = Objects.requireNonNull(blockChain.getOrphanRoot(m.getHash())); blockChainDownloadLocked(orphanRoot.getHash()); } finally { lock.unlock(); } } } catch (VerificationException e) { // We don't want verification failures to kill the thread. log.warn("{}: FilteredBlock verification failed", getAddress(), e); } catch (PrunedException e) { // We pruned away some of the data we need to properly handle this block. We need to request the needed // data from the remote peer and fix things. Or just give up. // TODO: Request e.getHash() and submit it to the block store before any other blocks throw new RuntimeException(e); } } private boolean checkForFilterExhaustion(FilteredBlock m) { boolean exhausted = false; for (Wallet wallet : wallets) { exhausted |= wallet.checkForFilterExhaustion(m); } return exhausted; } private boolean maybeHandleRequestedData(Message m, Sha256Hash hash) { boolean found = false; for (GetDataRequest req : getDataFutures) { if (hash.equals(req.hash)) { req.complete(m); getDataFutures.remove(req); found = true; // Keep going in case there are more. } } return found; } private void invokeOnBlocksDownloaded(final Block block, @Nullable final FilteredBlock fb) { // It is possible for the peer block height difference to be negative when blocks have been solved and broadcast // since the time we first connected to the peer. However, it's weird and unexpected to receive a callback // with negative "blocks left" in this case, so we clamp to zero so the API user doesn't have to think about it. final int blocksLeft = Math.max(0, (int) vPeerVersionMessage.bestHeight - Objects.requireNonNull(blockChain).getBestChainHeight()); for (final ListenerRegistration<BlocksDownloadedEventListener> registration : blocksDownloadedEventListeners) { registration.executor.execute(() -> registration.listener.onBlocksDownloaded(Peer.this, block, fb, blocksLeft)); } } protected void processInv(InventoryMessage inv) { List<InventoryItem> items = inv.getItems(); // Separate out the blocks and transactions, we'll handle them differently List<InventoryItem> transactions = new LinkedList<>(); List<InventoryItem> blocks = new LinkedList<>(); for (InventoryItem item : items) { switch (item.type) { case TRANSACTION: transactions.add(item); break; case BLOCK: blocks.add(item); break; default: throw new IllegalStateException("Not implemented: " + item.type); } } if (log.isDebugEnabled()) log.debug("{}: processing 'inv' with {} items: {} blocks, {} txns", this, items.size(), blocks.size(), transactions.size()); final boolean downloadData = this.vDownloadData; if (transactions.size() == 0 && blocks.size() == 1) { // Single block announcement. If we're downloading the chain this is just a tickle to make us continue // (the block chain download protocol is very implicit and not well thought out). If we're not downloading // the chain then this probably means a new block was solved and the peer believes it connects to the best // chain, so count it. This way getBestChainHeight() can be accurate. if (downloadData && blockChain != null) { if (!blockChain.isOrphan(blocks.get(0).hash)) { blocksAnnounced.incrementAndGet(); } } else { blocksAnnounced.incrementAndGet(); } } GetDataMessage getdata = new GetDataMessage(); Iterator<InventoryItem> it = transactions.iterator(); while (it.hasNext()) { InventoryItem item = it.next(); // Only download the transaction if we are the first peer that saw it be advertised. Other peers will also // see it be advertised in inv packets asynchronously, they co-ordinate via the memory pool. We could // potentially download transactions faster by always asking every peer for a tx when advertised, as remote // peers run at different speeds. However to conserve bandwidth on mobile devices we try to only download a // transaction once. This means we can miss broadcasts if the peer disconnects between sending us an inv and // sending us the transaction: currently we'll never try to re-fetch after a timeout. // // The line below can trigger confidence listeners. TransactionConfidence conf = context.getConfidenceTable().seen(item.hash, this.getAddress()); if (conf.numBroadcastPeers() > 1) { // Some other peer already announced this so don't download. it.remove(); } else if (conf.getSource().equals(TransactionConfidence.Source.SELF)) { // We created this transaction ourselves, so don't download. it.remove(); } else { if (log.isDebugEnabled()) log.debug("{}: getdata on tx {}", getAddress(), item.hash); getdata.addTransaction(item.hash, vPeerVersionMessage.services().has(Services.NODE_WITNESS)); if (pendingTxDownloads.size() > PENDING_TX_DOWNLOADS_LIMIT) { log.info("{}: Too many pending transactions, disconnecting", this); close(); return; } // Register with the garbage collector that we care about the confidence data for a while. pendingTxDownloads.add(conf); } } // If we are requesting filteredblocks we have to send a ping after the getdata so that we have a clear // end to the final FilteredBlock's transactions (in the form of a pong) sent to us boolean pingAfterGetData = false; lock.lock(); try { if (blocks.size() > 0 && downloadData && blockChain != null) { // Ideally, we'd only ask for the data here if we actually needed it. However that can imply a lot of // disk IO to figure out what we've got. Normally peers will not send us inv for things we already have // so we just re-request it here, and if we get duplicates the block chain / wallet will filter them out. for (InventoryItem item : blocks) { if (blockChain.isOrphan(item.hash) && downloadBlockBodies) { // If an orphan was re-advertised, ask for more blocks unless we are not currently downloading // full block data because we have a getheaders outstanding. final Block orphanRoot = Objects.requireNonNull(blockChain.getOrphanRoot(item.hash)); blockChainDownloadLocked(orphanRoot.getHash()); } else { // Don't re-request blocks we already requested. Normally this should not happen. However there is // an edge case: if a block is solved and we complete the inv<->getdata<->block<->getblocks cycle // whilst other parts of the chain are streaming in, then the new getblocks request won't match the // previous one: whilst the stopHash is the same (because we use the orphan root), the start hash // will be different and so the getblocks req won't be dropped as a duplicate. We'll end up // requesting a subset of what we already requested, which can lead to parallel chain downloads // and other nastiness. So we just do a quick removal of redundant getdatas here too. // // Note that as of June 2012 Bitcoin Core won't actually ever interleave blocks pushed as // part of chain download with newly announced blocks, so it should always be taken care of by // the duplicate check in blockChainDownloadLocked(). But Bitcoin Core may change in future so // it's better to be safe here. if (!pendingBlockDownloads.contains(item.hash)) { if (isBloomFilteringSupported(vPeerVersionMessage) && useFilteredBlocks) { getdata.addFilteredBlock(item.hash); pingAfterGetData = true; } else { getdata.addBlock(item.hash, vPeerVersionMessage.services().has(Services.NODE_WITNESS)); } pendingBlockDownloads.add(item.hash); } } } // If we're downloading the chain, doing a getdata on the last block we were told about will cause the // peer to advertize the head block to us in a single-item inv. When we download THAT, it will be an // orphan block, meaning we'll re-enter blockChainDownloadLocked() to trigger another getblocks between the // current best block we have and the orphan block. If more blocks arrive in the meantime they'll also // become orphan. } } finally { lock.unlock(); } if (!getdata.getItems().isEmpty()) { // This will cause us to receive a bunch of block or tx messages. sendMessage(getdata); } if (pingAfterGetData) sendMessage(Ping.random()); } /** * Asks the connected peer for the block of the given hash, and returns a future representing the answer. * If you want the block right away and don't mind waiting for it, just call .get() on the result. Your thread * will block until the peer answers. */ @SuppressWarnings("unchecked") // The 'unchecked conversion' warning being suppressed here comes from the sendSingleGetData() formally returning // ListenableCompletableFuture instead of ListenableCompletableFuture<Block>. This is okay as sendSingleGetData() actually returns // ListenableCompletableFuture<Block> in this context. Note that sendSingleGetData() is also used for Transactions. public ListenableCompletableFuture<Block> getBlock(Sha256Hash blockHash) { // This does not need to be locked. log.info("Request to fetch block {}", blockHash); GetDataMessage getdata = new GetDataMessage(); getdata.addBlock(blockHash, true); return ListenableCompletableFuture.of(sendSingleGetData(getdata)); } /** * Asks the connected peer for the given transaction from its memory pool. Transactions in the chain cannot be * retrieved this way because peers don't have a transaction ID to transaction-pos-on-disk index, and besides, * in future many peers will delete old transaction data they don't need. */ @SuppressWarnings("unchecked") // The 'unchecked conversion' warning being suppressed here comes from the sendSingleGetData() formally returning // ListenableCompletableFuture instead of ListenableCompletableFuture<Transaction>. This is okay as sendSingleGetData() actually returns // ListenableCompletableFuture<Transaction> in this context. Note that sendSingleGetData() is also used for Blocks. public ListenableCompletableFuture<Transaction> getPeerMempoolTransaction(Sha256Hash hash) { // This does not need to be locked. // TODO: Unit test this method. log.info("Request to fetch peer mempool tx {}", hash); GetDataMessage getdata = new GetDataMessage(); getdata.addTransaction(hash, vPeerVersionMessage.services().has(Services.NODE_WITNESS)); return ListenableCompletableFuture.of(sendSingleGetData(getdata)); } /** Sends a getdata with a single item in it. */ private CompletableFuture sendSingleGetData(GetDataMessage getdata) { // This does not need to be locked. checkArgument(getdata.getItems().size() == 1); GetDataRequest req = new GetDataRequest(getdata.getItems().get(0).hash); getDataFutures.add(req); sendMessage(getdata); return req; } /** Sends a getaddr request to the peer and returns a future that completes with the answer once the peer has replied. */ public ListenableCompletableFuture<AddressMessage> getAddr() { ListenableCompletableFuture<AddressMessage> future = new ListenableCompletableFuture<>(); synchronized (getAddrFutures) { getAddrFutures.add(future); } sendMessage(new GetAddrMessage()); return future; } /** * When downloading the block chain, the bodies will be skipped for blocks created before the given date. Any * transactions relevant to the wallet will therefore not be found, but if you know your wallet has no such * transactions it doesn't matter and can save a lot of bandwidth and processing time. Note that the times of blocks * isn't known until their headers are available and they are requested in chunks, so some headers may be downloaded * twice using this scheme, but this optimization can still be a large win for newly created wallets. * * @param useFilteredBlocks whether to request filtered blocks if the protocol version allows for them * @param fastCatchupTime time before which block bodies are skipped */ public void setFastDownloadParameters(boolean useFilteredBlocks, Instant fastCatchupTime) { lock.lock(); try { this.fastCatchupTime = fastCatchupTime; // If the given time is before the current chains head block time, then this has no effect (we already // downloaded everything we need). if (blockChain != null && this.fastCatchupTime.isAfter(blockChain.getChainHead().getHeader().time())) downloadBlockBodies = false; this.useFilteredBlocks = useFilteredBlocks; } finally { lock.unlock(); } } /** * Always download full blocks. * @param useFilteredBlocks whether to request filtered blocks if the protocol version allows for them */ public void setDownloadParameters(boolean useFilteredBlocks) { lock.lock(); try { this.fastCatchupTime = params.getGenesisBlock().time(); downloadBlockBodies = true; this.useFilteredBlocks = useFilteredBlocks; } finally { lock.unlock(); } } /** @deprecated use {@link #setDownloadParameters(boolean)} or {@link #setFastDownloadParameters(boolean, Instant)} */ @Deprecated public void setDownloadParameters(long fastCatchupTimeSecs, boolean useFilteredBlocks) { if (fastCatchupTimeSecs > 0) setFastDownloadParameters(useFilteredBlocks, Instant.ofEpochSecond(fastCatchupTimeSecs)); else setDownloadParameters(useFilteredBlocks); } /** * Links the given wallet to this peer. If you have multiple peers, you should use a {@link PeerGroup} to manage * them and use the {@link PeerGroup#addWallet(Wallet)} method instead of registering the wallet with each peer * independently, otherwise the wallet will receive duplicate notifications. */ public void addWallet(Wallet wallet) { wallets.add(wallet); } /** Unlinks the given wallet from peer. See {@link Peer#addWallet(Wallet)}. */ public void removeWallet(Wallet wallet) { wallets.remove(wallet); } // Keep track of the last request we made to the peer in blockChainDownloadLocked so we can avoid redundant and harmful // getblocks requests. @GuardedBy("lock") private Sha256Hash lastGetBlocksBegin, lastGetBlocksEnd; @GuardedBy("lock") private void blockChainDownloadLocked(Sha256Hash toHash) { checkState(lock.isHeldByCurrentThread()); // The block chain download process is a bit complicated. Basically, we start with one or more blocks in a // chain that we have from a previous session. We want to catch up to the head of the chain BUT we don't know // where that chain is up to or even if the top block we have is even still in the chain - we // might have got ourselves onto a fork that was later resolved by the network. // // To solve this, we send the peer a block locator which is just a list of block hashes. It contains the // blocks we know about, but not all of them, just enough of them so the peer can figure out if we did end up // on a fork and if so, what the earliest still valid block we know about is likely to be. // // Once it has decided which blocks we need, it will send us an inv with up to 500 block messages. We may // have some of them already if we already have a block chain and just need to catch up. Once we request the // last block, if there are still more to come it sends us an "inv" containing only the hash of the head // block. // // That causes us to download the head block but then we find (in processBlock) that we can't connect // it to the chain yet because we don't have the intermediate blocks. So we rerun this function building a // new block locator describing where we're up to. // // The getblocks with the new locator gets us another inv with another bunch of blocks. We download them once // again. This time when the peer sends us an inv with the head block, we already have it so we won't download // it again - but we recognize this case as special and call back into blockChainDownloadLocked to continue the // process. // // So this is a complicated process but it has the advantage that we can download a chain of enormous length // in a relatively stateless manner and with constant memory usage. // // All this is made more complicated by the desire to skip downloading the bodies of blocks that pre-date the // 'fast catchup time', which is usually set to the creation date of the earliest key in the wallet. Because // we know there are no transactions using our keys before that date, we need only the headers. To do that we // use the "getheaders" command. Once we find we've gone past the target date, we throw away the downloaded // headers and then request the blocks from that point onwards. "getheaders" does not send us an inv, it just // sends us the data we requested in a "headers" message. BlockLocator blockLocator = new BlockLocator(); // For now we don't do the exponential thinning as suggested here: // // https://en.bitcoin.it/wiki/Protocol_specification#getblocks // // This is because it requires scanning all the block chain headers, which is very slow. Instead we add the top // 100 block headers. If there is a re-org deeper than that, we'll end up downloading the entire chain. We // must always put the genesis block as the first entry. BlockStore store = Objects.requireNonNull(blockChain).getBlockStore(); StoredBlock chainHead = blockChain.getChainHead(); Sha256Hash chainHeadHash = chainHead.getHeader().getHash(); // Did we already make this request? If so, don't do it again. if (Objects.equals(lastGetBlocksBegin, chainHeadHash) && Objects.equals(lastGetBlocksEnd, toHash)) { log.info("blockChainDownloadLocked({}): ignoring duplicated request: {}", toHash, chainHeadHash); for (Sha256Hash hash : pendingBlockDownloads) log.info("Pending block download: {}", hash); log.info(Throwables.getStackTraceAsString(new Throwable())); return; } if (log.isDebugEnabled()) log.debug("{}: blockChainDownloadLocked({}) current head = {}", this, toHash, chainHead.getHeader().getHashAsString()); StoredBlock cursor = chainHead; for (int i = 100; cursor != null && i > 0; i--) { blockLocator = blockLocator.add(cursor.getHeader().getHash()); try { cursor = cursor.getPrev(store); } catch (BlockStoreException e) { log.error("Failed to walk the block chain whilst constructing a locator"); throw new RuntimeException(e); } } // Only add the locator if we didn't already do so. If the chain is < 50 blocks we already reached it. if (cursor != null) blockLocator = blockLocator.add(params.getGenesisBlock().getHash()); // Record that we requested this range of blocks so we can filter out duplicate requests in the event of a // block being solved during chain download. lastGetBlocksBegin = chainHeadHash; lastGetBlocksEnd = toHash; long protocolVersion = params.getSerializer().getProtocolVersion(); if (downloadBlockBodies) { GetBlocksMessage message = new GetBlocksMessage(protocolVersion, blockLocator, toHash); sendMessage(message); } else { // Downloading headers for a while instead of full blocks. GetHeadersMessage message = new GetHeadersMessage(protocolVersion, blockLocator, toHash); sendMessage(message); } } /** * Starts an asynchronous download of the block chain. The chain download is deemed to be complete once we've * downloaded the same number of blocks that the peer advertised having in its version handshake message. */ public void startBlockChainDownload() { setDownloadData(true); // TODO: peer might still have blocks that we don't have, and even have a heavier // chain even if the chain block count is lower. final int blocksLeft = getPeerBlockHeightDifference(); if (blocksLeft >= 0) { for (final ListenerRegistration<ChainDownloadStartedEventListener> registration : chainDownloadStartedEventListeners) { registration.executor.execute(() -> registration.listener.onChainDownloadStarted(Peer.this, blocksLeft)); } // When we just want as many blocks as possible, we can set the target hash to zero. lock.lock(); try { blockChainDownloadLocked(Sha256Hash.ZERO_HASH); } finally { lock.unlock(); } } } private class PendingPing { // The future that will be invoked when the pong is heard back. public final CompletableFuture<Duration> future; // The random nonce that lets us tell apart overlapping pings/pongs. public final long nonce; // Measurement of the time elapsed. public final Instant startTime; public PendingPing(long nonce) { this.future = new CompletableFuture<>(); this.nonce = nonce; this.startTime = TimeUtils.currentTime(); } public void complete() { if (!future.isDone()) { Duration elapsed = TimeUtils.elapsedTime(startTime); Peer.this.addPingInterval(elapsed); if (log.isDebugEnabled()) log.debug("{}: ping time is {} ms", Peer.this.toString(), elapsed.toMillis()); future.complete(elapsed); } } } /** Adds a ping time sample to the averaging window. */ private void addPingInterval(Duration sample) { pingIntervalsLock.lock(); try { if (pingIntervals.size() >= PING_MOVING_AVERAGE_WINDOW) { // Remove oldest sample from front of queue pingIntervals.remove(); } // Add new sample to end of queue pingIntervals.add(sample); // calculate last and average pings (while we have the lock and are loaded in cache) lastPing = sample; averagePing = pingIntervals.stream() .reduce(Duration::plus) .map(d -> d.dividedBy(pingIntervals.size())) .orElse(null); } finally { pingIntervalsLock.unlock(); } } /** * Sends the peer a ping message and returns a future that will be completed when the pong is received back. * The future provides a {@link Duration} which contains the time elapsed between the ping and the pong. * Once the pong is received the value returned by {@link Peer#lastPingInterval()} is updated. * The future completes exceptionally with a {@link ProtocolException} if the peer version is too low to support measurable pings. * @return A future for the duration representing elapsed time */ public CompletableFuture<Duration> sendPing() { return sendPing((long) (Math.random() * Long.MAX_VALUE)); } protected CompletableFuture<Duration> sendPing(long nonce) { final VersionMessage ver = vPeerVersionMessage; if (pendingPings.size() > PENDING_PINGS_LIMIT) { log.info("{}: Too many pending pings, disconnecting", this); close(); } PendingPing pendingPing = new PendingPing(nonce); pendingPings.add(pendingPing); sendMessage(Ping.of(pendingPing.nonce)); return pendingPing.future; } /** * @deprecated Use {@link #sendPing()} */ @Deprecated public ListenableCompletableFuture<Long> ping() { return ListenableCompletableFuture.of(sendPing().thenApply(Duration::toMillis)); } /** * Returns the elapsed time of the last ping/pong cycle. If {@link Peer#sendPing()} has never * been called or we did not hear back the "pong" message yet, returns empty. * @return last ping, or empty */ public Optional<Duration> lastPingInterval() { return Optional.ofNullable(lastPing); } /** @deprecated use {@link #lastPingInterval()} */ @Deprecated public long getLastPingTime() { return lastPingInterval() .map(Duration::toMillis) .orElse(Long.MAX_VALUE); } /** * Returns a moving average of the last N ping/pong cycles. If {@link Peer#sendPing()} has never * been called or we did not hear back the "pong" message yet, returns empty. The moving average * window is {@link #PING_MOVING_AVERAGE_WINDOW} buckets. * @return moving average, or empty */ public Optional<Duration> pingInterval() { return Optional.ofNullable(averagePing); } /** @deprecated use {@link #pingInterval()} */ @Deprecated public long getPingTime() { return pingInterval() .map(Duration::toMillis) .orElse(Long.MAX_VALUE); } private void processPing(Ping m) { sendMessage(m.pong()); } protected void processPong(Pong m) { // Iterates over a snapshot of the list, so we can run unlocked here. for (PendingPing ping : pendingPings) { if (m.nonce() == ping.nonce) { pendingPings.remove(ping); // This line may trigger an event listener that re-runs ping(). ping.complete(); return; } } } private void processFeeFilter(FeeFilterMessage m) { log.info("{}: Announced fee filter: {}/kB", this, m.feeRate().toFriendlyString()); vFeeFilter = m.feeRate(); } /** * Returns the difference between our best chain height and the peers, which can either be positive if we are * behind the peer, or negative if the peer is ahead of us. */ public int getPeerBlockHeightDifference() { Objects.requireNonNull(blockChain, "No block chain configured"); // Chain will overflow signed int blocks in ~41,000 years. int chainHeight = (int) getBestHeight(); // chainHeight should not be zero/negative because we shouldn't have given the user a Peer that is to another // client-mode node, nor should it be unconnected. If that happens it means the user overrode us somewhere or // there is a bug in the peer management code. checkState(params.allowEmptyPeerChain() || chainHeight > 0, () -> "connected to peer with zero/negative chain height: " + chainHeight); return chainHeight - blockChain.getBestChainHeight(); } /** * Returns true if this peer will try and download things it is sent in "inv" messages. Normally you only need * one peer to be downloading data. Defaults to true. */ public boolean isDownloadData() { return vDownloadData; } /** * If set to false, the peer won't try and fetch blocks and transactions it hears about. Normally, only one * peer should download missing blocks. Defaults to true. Changing this value from false to true may trigger * a request to the remote peer for the contents of its memory pool, if Bloom filtering is active. */ public void setDownloadData(boolean downloadData) { this.vDownloadData = downloadData; } /** Returns version data announced by the remote peer. */ public VersionMessage getPeerVersionMessage() { return vPeerVersionMessage; } /** Returns the fee filter announced by the remote peer, interpreted as satoshis per kB. */ public Coin getFeeFilter() { return vFeeFilter; } /** Returns version data we announce to our remote peers. */ public VersionMessage getVersionMessage() { return versionMessage; } /** * @return the height of the best chain as claimed by peer: sum of its ver announcement and blocks announced since. */ public long getBestHeight() { return vPeerVersionMessage.bestHeight + blocksAnnounced.get(); } /** * The minimum P2P protocol version that is accepted. If the peer speaks a protocol version lower than this, it * will be disconnected. * @return true if the peer was disconnected as a result */ public boolean setMinProtocolVersion(int minProtocolVersion) { this.vMinProtocolVersion = minProtocolVersion; VersionMessage ver = getPeerVersionMessage(); if (ver != null && ver.clientVersion < minProtocolVersion) { log.warn("{}: Disconnecting due to new min protocol version {}, got: {}", this, minProtocolVersion, ver.clientVersion); close(); return true; } return false; } /** * <p>Sets a Bloom filter on this connection. This will cause the given {@link BloomFilter} object to be sent to the * remote peer and if either a memory pool has been set using the constructor or the * vDownloadData property is true, a {@link MemoryPoolMessage} is sent as well to trigger downloading of any * pending transactions that may be relevant.</p> * * <p>The Peer does not automatically request filters from any wallets added using {@link Peer#addWallet(Wallet)}. * This is to allow callers to avoid redundantly recalculating the same filter repeatedly when using multiple peers * and multiple wallets together.</p> * * <p>Therefore, you should not use this method if your app uses a {@link PeerGroup}. It is called for you.</p> * * <p>If the remote peer doesn't support Bloom filtering, then this call is ignored. Once set you presently cannot * unset a filter, though the underlying p2p protocol does support it.</p> */ public void setBloomFilter(BloomFilter filter) { setBloomFilter(filter, true); } /** * <p>Sets a Bloom filter on this connection. This will cause the given {@link BloomFilter} object to be sent to the * remote peer and if requested, a {@link MemoryPoolMessage} is sent as well to trigger downloading of any * pending transactions that may be relevant.</p> * * <p>The Peer does not automatically request filters from any wallets added using {@link Peer#addWallet(Wallet)}. * This is to allow callers to avoid redundantly recalculating the same filter repeatedly when using multiple peers * and multiple wallets together.</p> * * <p>Therefore, you should not use this method if your app uses a {@link PeerGroup}. It is called for you.</p> * * <p>If the remote peer doesn't support Bloom filtering, then this call is ignored. Once set you presently cannot * unset a filter, though the underlying p2p protocol does support it.</p> */ public void setBloomFilter(BloomFilter filter, boolean andQueryMemPool) { Objects.requireNonNull(filter, "Clearing filters is not currently supported"); final VersionMessage version = vPeerVersionMessage; Objects.requireNonNull(version, "Cannot set filter before version handshake is complete"); if (isBloomFilteringSupported(version)) { vBloomFilter = filter; log.info("{}: Sending Bloom filter{}", this, andQueryMemPool ? " and querying mempool" : ""); sendMessage(filter); if (andQueryMemPool) sendMessage(new MemoryPoolMessage()); maybeRestartChainDownload(); } else { log.info("{}: Peer does not support bloom filtering.", this); close(); } } private void maybeRestartChainDownload() { lock.lock(); try { if (awaitingFreshFilter == null) return; if (!vDownloadData) { // This branch should be harmless but I want to know how often it happens in reality. log.warn("Lost download peer status whilst awaiting fresh filter."); return; } // Ping/pong to wait for blocks that are still being streamed to us to finish being downloaded and // discarded. sendPing().thenRunAsync(() -> { lock.lock(); Objects.requireNonNull(awaitingFreshFilter); GetDataMessage getdata = new GetDataMessage(); for (Sha256Hash hash : awaitingFreshFilter) getdata.addFilteredBlock(hash); awaitingFreshFilter = null; lock.unlock(); log.info("Restarting chain download"); sendMessage(getdata); // TODO: This bizarre ping-after-getdata hack probably isn't necessary. // It's to ensure we know when the end of a filtered block stream of txns is, but we should just be // able to match txns with the merkleblock. Ask Matt why it's written this way. sendMessage(Ping.random()); }, Threading.SAME_THREAD); } finally { lock.unlock(); } } /** * Returns the last {@link BloomFilter} set by {@link Peer#setBloomFilter(BloomFilter)}. Bloom filters tell * the remote node what transactions to send us, in a compact manner. */ public BloomFilter getBloomFilter() { return vBloomFilter; } /** * Returns true if this peer will use getdata/notfound messages to walk backwards through transaction dependencies * before handing the transaction off to the wallet. The wallet can do risk analysis on pending/recent transactions * to try and discover if a pending tx might be at risk of double spending. */ public boolean isDownloadTxDependencies() { return vDownloadTxDependencyDepth > 0; } /** * Sets if this peer will use getdata/notfound messages to walk backwards through transaction dependencies * before handing the transaction off to the wallet. The wallet can do risk analysis on pending/recent transactions * to try and discover if a pending tx might be at risk of double spending. */ public void setDownloadTxDependencies(boolean enable) { vDownloadTxDependencyDepth = enable ? Integer.MAX_VALUE : 0; } /** * Sets if this peer will use getdata/notfound messages to walk backwards through transaction dependencies * before handing the transaction off to the wallet. The wallet can do risk analysis on pending/recent transactions * to try and discover if a pending tx might be at risk of double spending. */ public void setDownloadTxDependencies(int depth) { vDownloadTxDependencyDepth = depth; } /** * Returns true if the peer supports bloom filtering according to BIP37 and BIP111. */ private boolean isBloomFilteringSupported(VersionMessage version) { int clientVersion = version.clientVersion(); if (clientVersion >= ProtocolVersion.BLOOM_FILTER.intValue() && clientVersion < ProtocolVersion.BLOOM_FILTER_BIP111.intValue()) return true; if (version.services().has(Services.NODE_BLOOM)) return true; return false; } }
99,792
53.591357
152
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/RejectedTransactionException.java
/* * Copyright 2014 Adam Mackler * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; /** * This exception is used by the TransactionBroadcast class to indicate that a broadcast * Transaction has been rejected by the network, for example because it violates a * protocol rule. Note that not all invalid transactions generate a reject message, and * some peers may never do so. */ public class RejectedTransactionException extends Exception { private Transaction tx; private RejectMessage rejectMessage; public RejectedTransactionException(Transaction tx, RejectMessage rejectMessage) { super(rejectMessage.toString()); this.tx = tx; this.rejectMessage = rejectMessage; } /** Return the original Transaction object whose broadcast was rejected. */ public Transaction getTransaction() { return tx; } /** Return the RejectMessage object representing the broadcast rejection. */ public RejectMessage getRejectMessage() { return rejectMessage; } }
1,545
36.707317
88
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/FilteredBlock.java
/* * Copyright 2012 Matt Corallo * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.Buffers; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; /** * <p>A FilteredBlock is used to relay a block with its transactions filtered using a {@link BloomFilter}. It consists * of the block header and a {@link PartialMerkleTree} which contains the transactions which matched the filter.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class FilteredBlock extends BaseMessage { private Block header; private PartialMerkleTree merkleTree; private List<Sha256Hash> cachedTransactionHashes = null; // A set of transactions whose hashes are a subset of getTransactionHashes() // These were relayed as a part of the filteredblock getdata, ie likely weren't previously received as loose transactions private Map<Sha256Hash, Transaction> associatedTransactions = new HashMap<>(); /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static FilteredBlock read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { byte[] headerBytes = Buffers.readBytes(payload, Block.HEADER_SIZE); Block header = Block.read(ByteBuffer.wrap(headerBytes)); PartialMerkleTree merkleTree = PartialMerkleTree.read(payload); return new FilteredBlock(header, merkleTree); } public FilteredBlock(Block header, PartialMerkleTree pmt) { super(); this.header = header; this.merkleTree = pmt; } @Override public void bitcoinSerializeToStream(OutputStream stream) throws IOException { if (header.getTransactions() == null) header.bitcoinSerializeToStream(stream); else header.cloneAsHeader().bitcoinSerializeToStream(stream); stream.write(merkleTree.serialize()); } /** * Gets a list of leaf hashes which are contained in the partial merkle tree in this filtered block * * @throws ProtocolException If the partial merkle block is invalid or the merkle root of the partial merkle block doesn't match the block header */ public List<Sha256Hash> getTransactionHashes() throws VerificationException { if (cachedTransactionHashes != null) return Collections.unmodifiableList(cachedTransactionHashes); List<Sha256Hash> hashesMatched = new LinkedList<>(); if (header.getMerkleRoot().equals(merkleTree.getTxnHashAndMerkleRoot(hashesMatched))) { cachedTransactionHashes = hashesMatched; return Collections.unmodifiableList(cachedTransactionHashes); } else throw new VerificationException("Merkle root of block header does not match merkle root of partial merkle tree."); } /** * Gets a copy of the block header */ public Block getBlockHeader() { return header.cloneAsHeader(); } /** Gets the hash of the block represented in this Filtered Block */ public Sha256Hash getHash() { return header.getHash(); } /** * Provide this FilteredBlock with a transaction which is in its Merkle tree. * @return false if the tx is not relevant to this FilteredBlock */ public boolean provideTransaction(Transaction tx) throws VerificationException { Sha256Hash hash = tx.getTxId(); if (getTransactionHashes().contains(hash)) { associatedTransactions.put(hash, tx); return true; } return false; } /** Returns the {@link PartialMerkleTree} object that provides the mathematical proof of transaction inclusion in the block. */ public PartialMerkleTree getPartialMerkleTree() { return merkleTree; } /** Gets the set of transactions which were provided using provideTransaction() which match in getTransactionHashes() */ public Map<Sha256Hash, Transaction> getAssociatedTransactions() { return Collections.unmodifiableMap(associatedTransactions); } /** Number of transactions in this block, before it was filtered */ public int getTransactionCount() { return merkleTree.getTransactionCount(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FilteredBlock other = (FilteredBlock) o; return associatedTransactions.equals(other.associatedTransactions) && header.equals(other.header) && merkleTree.equals(other.merkleTree); } @Override public int hashCode() { return Objects.hash(associatedTransactions, header, merkleTree); } @Override public String toString() { return "FilteredBlock{merkleTree=" + merkleTree + ", header=" + header + '}'; } }
5,907
37.363636
149
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/Pong.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.internal.ByteUtils; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; /** * See <a href="https://github.com/bitcoin/bips/blob/master/bip-0031.mediawiki">BIP31</a> for details. * <p> * Instances of this class are immutable. */ public class Pong extends BaseMessage { private final long nonce; /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static Pong read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { return new Pong(ByteUtils.readInt64(payload)); } /** * Create a pong with a nonce value. * * @param nonce nonce value * @return pong message */ public static Pong of(long nonce) { return new Pong(nonce); } private Pong(long nonce) { this.nonce = nonce; } @Override public void bitcoinSerializeToStream(OutputStream stream) throws IOException { ByteUtils.writeInt64LE(nonce, stream); } /** Returns the nonce sent by the remote peer. */ public long nonce() { return nonce; } }
2,008
28.115942
109
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/VersionAck.java
/* * Copyright 2011 Noa Resare. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; /** * <p>The verack message, sent by a client accepting the version message they * received from their peer.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class VersionAck extends EmptyMessage { public VersionAck() { } }
903
30.172414
77
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/StoredBlock.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.store.SPVBlockStore; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.Locale; import java.util.Objects; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Wraps a {@link Block} object with extra data that can be derived from the block chain but is slow or inconvenient to * calculate. By storing it alongside the block header we reduce the amount of work required significantly. * Recalculation is slow because the fields are cumulative - to find the chainWork you have to iterate over every * block in the chain back to the genesis block, which involves lots of seeking/loading etc. So we just keep a * running total: it's a disk space vs cpu/io tradeoff.<p> * * StoredBlocks are put inside a {@link BlockStore} which saves them to memory or disk. */ public class StoredBlock { // A BigInteger representing the total amount of work done so far on this chain. As of May 2011 it takes 8 // bytes to represent this field, so 12 bytes should be plenty for now. private static final int CHAIN_WORK_BYTES = 12; private static final byte[] EMPTY_BYTES = new byte[CHAIN_WORK_BYTES]; public static final int COMPACT_SERIALIZED_SIZE = Block.HEADER_SIZE + CHAIN_WORK_BYTES + 4; // for height private final Block header; private final BigInteger chainWork; private final int height; /** * Create a StoredBlock from a (header-only) {@link Block}, chain work value, and block height * * @param header A Block object with only a header (no transactions should be included) * @param chainWork Calculated chainWork for this block * @param height block height for this block */ public StoredBlock(Block header, BigInteger chainWork, int height) { this.header = header; this.chainWork = chainWork; this.height = height; } /** * The block header this object wraps. The referenced block object must not have any transactions in it. */ public Block getHeader() { return header; } /** * The total sum of work done in this block, and all the blocks below it in the chain. Work is a measure of how * many tries are needed to solve a block. If the target is set to cover 10% of the total hash value space, * then the work represented by a block is 10. */ public BigInteger getChainWork() { return chainWork; } /** * Position in the chain for this block. The genesis block has a height of zero. */ public int getHeight() { return height; } /** Returns true if this objects chainWork is higher than the others. */ public boolean moreWorkThan(StoredBlock other) { return chainWork.compareTo(other.chainWork) > 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StoredBlock other = (StoredBlock) o; return header.equals(other.header) && chainWork.equals(other.chainWork) && height == other.height; } @Override public int hashCode() { return Objects.hash(header, chainWork, height); } /** * Creates a new StoredBlock, calculating the additional fields by adding to the values in this block. */ 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); } /** * Given a block store, looks up the previous block in this chain. Convenience method for doing * {@code store.get(this.getHeader().getPrevBlockHash())}. * * @return the previous block in the chain or null if it was not found in the store. */ public StoredBlock getPrev(BlockStore store) throws BlockStoreException { return store.get(getHeader().getPrevBlockHash()); } /** Serializes the stored block to a custom packed format. Used by {@link CheckpointManager}. */ public void serializeCompact(ByteBuffer buffer) { byte[] chainWorkBytes = getChainWork().toByteArray(); checkState(chainWorkBytes.length <= CHAIN_WORK_BYTES, () -> "ran out of space to store chain work!"); if (chainWorkBytes.length < CHAIN_WORK_BYTES) { // Pad to the right size. buffer.put(EMPTY_BYTES, 0, CHAIN_WORK_BYTES - chainWorkBytes.length); } buffer.put(chainWorkBytes); buffer.putInt(getHeight()); // Using unsafeBitcoinSerialize here can give us direct access to the same bytes we read off the wire, // avoiding serialization round-trips. byte[] bytes = getHeader().serialize(); buffer.put(bytes, 0, Block.HEADER_SIZE); // Trim the trailing 00 byte (zero transactions). } /** * Deserializes the stored block from a custom packed format. Used by {@link CheckpointManager} and * {@link SPVBlockStore}. * * @param buffer data to deserialize * @return deserialized stored block */ public static StoredBlock deserializeCompact(ByteBuffer buffer) throws ProtocolException { byte[] chainWorkBytes = new byte[StoredBlock.CHAIN_WORK_BYTES]; buffer.get(chainWorkBytes); BigInteger chainWork = ByteUtils.bytesToBigInteger(chainWorkBytes); int height = buffer.getInt(); // +4 bytes byte[] header = new byte[Block.HEADER_SIZE + 1]; // Extra byte for the 00 transactions length. buffer.get(header, 0, Block.HEADER_SIZE); return new StoredBlock(Block.read(ByteBuffer.wrap(header)), chainWork, height); } /** @deprecated use {@link #deserializeCompact(ByteBuffer)} */ @Deprecated public static StoredBlock deserializeCompact(MessageSerializer serializer, ByteBuffer buffer) throws ProtocolException { return deserializeCompact(buffer); } @Override public String toString() { return String.format(Locale.US, "Block %s at height %d: %s", getHeader().getHashAsString(), getHeight(), getHeader().toString()); } }
7,125
40.190751
124
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/InventoryItem.java
/* * Copyright 2011 Google Inc. * Copyright 2019 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import java.util.Objects; public class InventoryItem { /** * 4 byte uint32 type field + 32 byte hash */ static final int MESSAGE_LENGTH = 36; public enum Type { ERROR(0x0), TRANSACTION(0x1), BLOCK(0x2), // BIP37 extension: FILTERED_BLOCK(0x3), // BIP44 extensions: WITNESS_TRANSACTION(0x40000001), WITNESS_BLOCK(0x40000002), WITNESS_FILTERED_BLOCK(0x40000003); public final int code; Type(int code) { this.code = code; } public static Type ofCode(int code) { for (Type type : values()) if (type.code == code) return type; return null; } } public final Type type; public final Sha256Hash hash; public InventoryItem(Type type, Sha256Hash hash) { this.type = type; this.hash = hash; } @Override public String toString() { return type + ": " + hash; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InventoryItem other = (InventoryItem) o; return type == other.type && hash.equals(other.hash); } @Override public int hashCode() { return Objects.hash(type, hash); } }
2,058
25.397436
103
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/GetBlocksMessage.java
/* * Copyright 2011 Google Inc. * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.ByteUtils; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import static org.bitcoinj.base.internal.Preconditions.check; /** * <p>Represents the "getblocks" P2P network message, which requests the hashes of the parts of the block chain we're * missing. Those blocks can then be downloaded with a {@link GetDataMessage}.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class GetBlocksMessage extends BaseMessage { protected long version; protected BlockLocator locator; protected Sha256Hash stopHash; /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static GetBlocksMessage read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { long version = ByteUtils.readUint32(payload); VarInt startCountVarInt = VarInt.read(payload); check(startCountVarInt.fitsInt(), BufferUnderflowException::new); int startCount = startCountVarInt.intValue(); if (startCount > 500) throw new ProtocolException("Number of locators cannot be > 500, received: " + startCount); BlockLocator locator = new BlockLocator(); for (int i = 0; i < startCount; i++) { locator = locator.add(Sha256Hash.read(payload)); } Sha256Hash stopHash = Sha256Hash.read(payload); return new GetBlocksMessage(version, locator, stopHash); } public GetBlocksMessage(long protocolVersion, BlockLocator locator, Sha256Hash stopHash) { this.version = protocolVersion; this.locator = locator; this.stopHash = stopHash; } public BlockLocator getLocator() { return locator; } public Sha256Hash getStopHash() { return stopHash; } @Override public String toString() { return "getblocks: " + locator.toString(); } @Override protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { // Version, for some reason. ByteUtils.writeInt32LE(version, stream); // Then a vector of block hashes. This is actually a "block locator", a set of block // identifiers that spans the entire chain with exponentially increasing gaps between // them, until we end up at the genesis block. See CBlockLocator::Set() stream.write(VarInt.of(locator.size()).serialize()); for (Sha256Hash hash : locator.getHashes()) { // Have to reverse as wire format is little endian. stream.write(hash.serialize()); } // Next, a block ID to stop at. stream.write(stopHash.serialize()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GetBlocksMessage other = (GetBlocksMessage) o; return version == other.version && stopHash.equals(other.stopHash) && locator.size() == other.locator.size() && locator.equals(other.locator); // ignores locator ordering } @Override public int hashCode() { int hashCode = (int) version ^ "getblocks".hashCode() ^ stopHash.hashCode(); return hashCode ^= locator.hashCode(); } }
4,274
36.173913
117
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/MessageSerializer.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * Copyright 2015 Ross Nicoll * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import java.io.IOException; import java.io.OutputStream; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; /** * Generic interface for classes which serialize/deserialize messages. Implementing * classes should be immutable. */ public abstract class MessageSerializer { /** * Create a new serializer with a specific protocol version. Mainly used to disable segwit when parsing transactions. */ public abstract MessageSerializer withProtocolVersion(int protocolVersion); /** * Get the protocol version of this serializer. */ public abstract int getProtocolVersion(); /** * Reads a message from the given ByteBuffer and returns it. */ public abstract Message deserialize(ByteBuffer in) throws ProtocolException, IOException, UnsupportedOperationException; /** * Deserializes only the header in case packet meta data is needed before decoding * the payload. This method assumes you have already called seekPastMagicBytes() */ public abstract BitcoinSerializer.BitcoinPacketHeader deserializeHeader(ByteBuffer in) throws ProtocolException, IOException, UnsupportedOperationException; /** * Deserialize payload only. You must provide a header, typically obtained by calling * {@link BitcoinSerializer#deserializeHeader}. */ public abstract Message deserializePayload(BitcoinSerializer.BitcoinPacketHeader header, ByteBuffer in) throws ProtocolException, BufferUnderflowException, UnsupportedOperationException; /** * Make an address message from the payload. Extension point for alternative * serialization format support. */ public abstract AddressV1Message makeAddressV1Message(ByteBuffer payload) throws ProtocolException, UnsupportedOperationException; /** * Make an address message from the payload. Extension point for alternative * serialization format support. */ public abstract AddressV2Message makeAddressV2Message(ByteBuffer payload) throws ProtocolException, UnsupportedOperationException; /** * Make a block from the payload. Extension point for alternative * serialization format support. */ public abstract Block makeBlock(ByteBuffer payload) throws ProtocolException, UnsupportedOperationException; /** * Make an filter message from the payload. Extension point for alternative * serialization format support. */ public abstract Message makeBloomFilter(ByteBuffer payload) throws ProtocolException, UnsupportedOperationException; /** * Make a filtered block from the payload. Extension point for alternative * serialization format support. */ public abstract FilteredBlock makeFilteredBlock(ByteBuffer payload) throws ProtocolException, UnsupportedOperationException; /** * Make an inventory message from the payload. Extension point for alternative * serialization format support. */ public abstract InventoryMessage makeInventoryMessage(ByteBuffer payload) throws ProtocolException, UnsupportedOperationException; /** * Make a transaction from the payload. Extension point for alternative * serialization format support. * * @throws UnsupportedOperationException if this serializer/deserializer * does not support deserialization. This can occur either because it's a dummy * serializer (i.e. for messages with no network parameters), or because * it does not support deserializing transactions. */ public abstract Transaction makeTransaction(ByteBuffer payload) throws ProtocolException, UnsupportedOperationException; public abstract void seekPastMagicBytes(ByteBuffer in) throws BufferUnderflowException; /** * Writes message to to the output stream. * * @throws UnsupportedOperationException if this serializer/deserializer * does not support serialization. This can occur either because it's a dummy * serializer (i.e. for messages with no network parameters), or because * it does not support serializing the given message. */ public abstract void serialize(String name, byte[] message, OutputStream out) throws IOException, UnsupportedOperationException; /** * Writes message to to the output stream. * * @throws UnsupportedOperationException if this serializer/deserializer * does not support serialization. This can occur either because it's a dummy * serializer (i.e. for messages with no network parameters), or because * it does not support serializing the given message. */ public abstract void serialize(Message message, OutputStream out) throws IOException, UnsupportedOperationException; }
5,436
41.147287
190
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/SendHeadersMessage.java
/* * Copyright 2017 Anton Kumaigorodski * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; /** * <p> * A new message, "sendheaders", which indicates that a node prefers to receive new block announcements via a "headers" * message rather than an "inv". * </p> * * <p> * See <a href="https://github.com/bitcoin/bips/blob/master/bip-0130.mediawiki">BIP 130</a>. * </p> */ public class SendHeadersMessage extends EmptyMessage { public SendHeadersMessage() { } }
1,015
29.787879
119
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/GetAddrMessage.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Address; /** * <p>Represents the "getaddr" P2P protocol message, which requests network {@link AddressMessage}s from a peer. Not to * be confused with {@link Address} which is sort of like an account number.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class GetAddrMessage extends EmptyMessage { public GetAddrMessage() { super(); } }
1,054
30.969697
119
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/PeerSocketHandler.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.annotations.VisibleForTesting; import org.bitcoinj.net.MessageWriteTarget; import org.bitcoinj.net.NioClient; import org.bitcoinj.net.NioClientManager; import org.bitcoinj.net.SocketTimeoutTask; import org.bitcoinj.net.StreamConnection; import org.bitcoinj.net.TimeoutHandler; import org.bitcoinj.utils.ListenableCompletableFuture; import org.bitcoinj.utils.Threading; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.nio.Buffer; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.channels.NotYetConnectedException; import java.time.Duration; import java.util.Objects; import java.util.concurrent.locks.Lock; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Handles high-level message (de)serialization for peers, acting as the bridge between the * {@code org.bitcoinj.net} classes and {@link Peer}. */ public abstract class PeerSocketHandler implements TimeoutHandler, StreamConnection { private static final Logger log = LoggerFactory.getLogger(PeerSocketHandler.class); private final Lock lock = Threading.lock(PeerSocketHandler.class); private final SocketTimeoutTask timeoutTask; private final MessageSerializer serializer; protected final PeerAddress peerAddress; // If we close() before we know our writeTarget, set this to true to call writeTarget.closeConnection() right away. private boolean closePending = false; // writeTarget will be thread-safe, and may call into PeerGroup, which calls us, so we should call it unlocked @VisibleForTesting protected MessageWriteTarget writeTarget = null; // The ByteBuffers passed to us from the writeTarget are static in size, and usually smaller than some messages we // will receive. For SPV clients, this should be rare (ie we're mostly dealing with small transactions), but for // messages which are larger than the read buffer, we have to keep a temporary buffer with its bytes. private byte[] largeReadBuffer; private int largeReadBufferPos; private BitcoinSerializer.BitcoinPacketHeader header; public PeerSocketHandler(NetworkParameters params, InetSocketAddress remoteIp) { this(params, PeerAddress.simple(remoteIp)); } public PeerSocketHandler(NetworkParameters params, PeerAddress peerAddress) { Objects.requireNonNull(params); serializer = params.getDefaultSerializer(); this.peerAddress = Objects.requireNonNull(peerAddress); this.timeoutTask = new SocketTimeoutTask(this::timeoutOccurred); } @Override public void setTimeoutEnabled(boolean timeoutEnabled) { timeoutTask.setTimeoutEnabled(timeoutEnabled); } @Override public void setSocketTimeout(Duration timeout) { timeoutTask.setSocketTimeout(timeout); } /** * Sends the given message to the peer. Due to the asynchronousness of network programming, there is no guarantee * the peer will have received it. Throws NotYetConnectedException if we are not yet connected to the remote peer. * TODO: Maybe use something other than the unchecked NotYetConnectedException here */ public ListenableCompletableFuture<Void> sendMessage(Message message) throws NotYetConnectedException { lock.lock(); try { if (writeTarget == null) throw new NotYetConnectedException(); } finally { lock.unlock(); } // TODO: Some round-tripping could be avoided here ByteArrayOutputStream out = new ByteArrayOutputStream(); try { serializer.serialize(message, out); return writeTarget.writeBytes(out.toByteArray()); } catch (IOException e) { exceptionCaught(e); return ListenableCompletableFuture.failedFuture(e); } } /** * Closes the connection to the peer if one exists, or immediately closes the connection as soon as it opens */ public void close() { lock.lock(); try { if (writeTarget == null) { closePending = true; return; } } finally { lock.unlock(); } writeTarget.closeConnection(); } protected void timeoutOccurred() { log.info("{}: Timed out", getAddress()); close(); } /** * Called every time a message is received from the network */ protected abstract void processMessage(Message m) throws Exception; @Override public int receiveBytes(ByteBuffer buff) { checkArgument(buff.position() == 0 && buff.capacity() >= BitcoinSerializer.BitcoinPacketHeader.HEADER_LENGTH + 4); try { // Repeatedly try to deserialize messages until we hit a BufferUnderflowException boolean firstMessage = true; while (true) { // If we are in the middle of reading a message, try to fill that one first, before we expect another if (largeReadBuffer != null) { // This can only happen in the first iteration checkState(firstMessage); // Read new bytes into the largeReadBuffer int bytesToGet = Math.min(buff.remaining(), largeReadBuffer.length - largeReadBufferPos); buff.get(largeReadBuffer, largeReadBufferPos, bytesToGet); largeReadBufferPos += bytesToGet; // Check the largeReadBuffer's status if (largeReadBufferPos == largeReadBuffer.length) { // ...processing a message if one is available processMessage(serializer.deserializePayload(header, ByteBuffer.wrap(largeReadBuffer))); largeReadBuffer = null; header = null; firstMessage = false; } else // ...or just returning if we don't have enough bytes yet return buff.position(); } // Now try to deserialize any messages left in buff Message message; int preSerializePosition = buff.position(); try { message = serializer.deserialize(buff); } catch (BufferUnderflowException e) { // If we went through the whole buffer without a full message, we need to use the largeReadBuffer if (firstMessage && buff.limit() == buff.capacity()) { // ...so reposition the buffer to 0 and read the next message header ((Buffer) buff).position(0); try { serializer.seekPastMagicBytes(buff); header = serializer.deserializeHeader(buff); // Initialize the largeReadBuffer with the next message's size and fill it with any bytes // left in buff largeReadBuffer = new byte[header.size]; largeReadBufferPos = buff.remaining(); buff.get(largeReadBuffer, 0, largeReadBufferPos); } catch (BufferUnderflowException e1) { // If we went through a whole buffer's worth of bytes without getting a header, give up // In cases where the buff is just really small, we could create a second largeReadBuffer // that we use to deserialize the magic+header, but that is rather complicated when the buff // should probably be at least that big anyway (for efficiency) throw new ProtocolException("No magic bytes+header after reading " + buff.capacity() + " bytes"); } } else { // Reposition the buffer to its original position, which saves us from skipping messages by // seeking past part of the magic bytes before all of them are in the buffer ((Buffer) buff).position(preSerializePosition); } return buff.position(); } // Process our freshly deserialized message processMessage(message); firstMessage = false; } } catch (Exception e) { exceptionCaught(e); return -1; // Returning -1 also throws an IllegalStateException upstream and kills the connection } } /** * Sets the {@link MessageWriteTarget} used to write messages to the peer. This should almost never be called, it is * called automatically by {@link NioClient} or * {@link NioClientManager} once the socket finishes initialization. */ @Override public void setWriteTarget(MessageWriteTarget writeTarget) { checkArgument(writeTarget != null); lock.lock(); boolean closeNow = false; try { checkArgument(this.writeTarget == null); closeNow = closePending; this.writeTarget = writeTarget; } finally { lock.unlock(); } if (closeNow) writeTarget.closeConnection(); } @Override public int getMaxMessageSize() { return Message.MAX_SIZE; } /** * @return the IP address and port of peer. */ public PeerAddress getAddress() { return peerAddress; } /** Catch any exceptions, logging them and then closing the channel. */ private void exceptionCaught(Exception e) { PeerAddress addr = getAddress(); String s = addr == null ? "?" : addr.toString(); if (e instanceof ConnectException || e instanceof IOException) { // Short message for network errors log.info(s + " - " + e.getMessage()); } else { log.warn(s + " - ", e); Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler; if (handler != null) handler.uncaughtException(Thread.currentThread(), e); } close(); } }
11,138
42.174419
125
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/TransactionWitness.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.Buffers; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.base.internal.InternalUtils; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.script.Script; import javax.annotation.Nullable; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import static org.bitcoinj.base.internal.Preconditions.check; import static org.bitcoinj.base.internal.Preconditions.checkArgument; public class TransactionWitness { public static final TransactionWitness EMPTY = TransactionWitness.of(Collections.emptyList()); /** * Creates the stack pushes necessary to redeem a P2WPKH output. If given signature is null, an empty push will be * used as a placeholder. */ public static TransactionWitness redeemP2WPKH(@Nullable TransactionSignature signature, ECKey pubKey) { checkArgument(pubKey.isCompressed(), () -> "only compressed keys allowed"); List<byte[]> pushes = new ArrayList<>(2); pushes.add(signature != null ? signature.encodeToBitcoin() : new byte[0]); // signature pushes.add(pubKey.getPubKey()); // pubkey return TransactionWitness.of(pushes); } /** * Creates the stack pushes necessary to redeem a P2WSH output. */ public static TransactionWitness redeemP2WSH(Script witnessScript, TransactionSignature... signatures) { List<byte[]> pushes = new ArrayList<>(signatures.length + 2); pushes.add(new byte[] {}); for (TransactionSignature signature : signatures) pushes.add(signature.encodeToBitcoin()); pushes.add(witnessScript.getProgram()); return TransactionWitness.of(pushes); } /** * Construct a transaction witness from a given list of arbitrary pushes. * * @param pushes list of pushes * @return constructed transaction witness */ public static TransactionWitness of(List<byte[]> pushes) { return new TransactionWitness(pushes); } /** * Construct a transaction witness from a given list of arbitrary pushes. * * @param pushes list of pushes * @return constructed transaction witness */ public static TransactionWitness of(byte[]... pushes) { return of(Arrays.asList(pushes)); } /** * Deserialize this transaction witness from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static TransactionWitness read(ByteBuffer payload) throws BufferUnderflowException { VarInt pushCountVarInt = VarInt.read(payload); check(pushCountVarInt.fitsInt(), BufferUnderflowException::new); int pushCount = pushCountVarInt.intValue(); List<byte[]> pushes = new ArrayList<>(Math.min(pushCount, Utils.MAX_INITIAL_ARRAY_LENGTH)); for (int y = 0; y < pushCount; y++) pushes.add(Buffers.readLengthPrefixedBytes(payload)); return new TransactionWitness(pushes); } private final List<byte[]> pushes; private TransactionWitness(List<byte[]> pushes) { for (byte[] push : pushes) Objects.requireNonNull(push); this.pushes = pushes; } public byte[] getPush(int i) { return pushes.get(i); } public int getPushCount() { return pushes.size(); } /** * Write this transaction witness into the given buffer. * * @param buf buffer to write into * @return the buffer * @throws BufferOverflowException if the serialized data doesn't fit the remaining buffer */ public ByteBuffer write(ByteBuffer buf) throws BufferOverflowException { VarInt.of(pushes.size()).write(buf); for (byte[] push : pushes) Buffers.writeLengthPrefixedBytes(buf, push); return buf; } /** * Allocates a byte array and writes this transaction witness into it. * * @return byte array containing the transaction witness */ public byte[] serialize() { return write(ByteBuffer.allocate(getMessageSize())).array(); } /** * Return the size of the serialized message. Note that if the message was deserialized from a payload, this * size can differ from the size of the original payload. * * @return size of the serialized message in bytes */ public int getMessageSize() { int size = VarInt.sizeOf(pushes.size()); for (byte[] push : pushes) size += VarInt.sizeOf(push.length) + push.length; return size; } @Override public String toString() { List<String> stringPushes = new ArrayList<>(pushes.size()); for (byte[] push : pushes) { if (push.length == 0) { stringPushes.add("EMPTY"); } else { stringPushes.add(ByteUtils.formatHex(push)); } } return InternalUtils.SPACE_JOINER.join(stringPushes); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TransactionWitness other = (TransactionWitness) o; if (pushes.size() != other.pushes.size()) return false; for (int i = 0; i < pushes.size(); i++) { if (!Arrays.equals(pushes.get(i), other.pushes.get(i))) return false; } return true; } @Override public int hashCode() { int hashCode = 1; for (byte[] push : pushes) { hashCode = 31 * hashCode + Arrays.hashCode(push); } return hashCode; } }
6,652
33.832461
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/PeerException.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; /** * Thrown when a problem occurs in communicating with a peer, and we should * retry. */ @SuppressWarnings("serial") public class PeerException extends Exception { public PeerException(String msg) { super(msg); } public PeerException(Exception e) { super(e); } public PeerException(String msg, Exception e) { super(msg, e); } }
1,006
26.216216
75
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/PeerGroup.java
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.Runnables; import com.google.common.util.concurrent.Uninterruptibles; import net.jcip.annotations.GuardedBy; import org.bitcoinj.base.Network; import org.bitcoinj.base.internal.PlatformUtils; import org.bitcoinj.base.internal.Stopwatch; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.listeners.AddressEventListener; import org.bitcoinj.core.listeners.BlockchainDownloadEventListener; import org.bitcoinj.core.listeners.BlocksDownloadedEventListener; import org.bitcoinj.core.listeners.ChainDownloadStartedEventListener; import org.bitcoinj.core.listeners.DownloadProgressTracker; import org.bitcoinj.core.listeners.GetDataEventListener; import org.bitcoinj.core.listeners.OnTransactionBroadcastListener; import org.bitcoinj.core.listeners.PeerConnectedEventListener; import org.bitcoinj.core.listeners.PeerDisconnectedEventListener; import org.bitcoinj.core.listeners.PeerDiscoveredEventListener; import org.bitcoinj.core.listeners.PreMessageReceivedEventListener; import org.bitcoinj.net.ClientConnectionManager; import org.bitcoinj.net.FilterMerger; import org.bitcoinj.net.NioClientManager; import org.bitcoinj.net.discovery.MultiplexingDiscovery; import org.bitcoinj.net.discovery.PeerDiscovery; import org.bitcoinj.net.discovery.PeerDiscoveryException; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptPattern; import org.bitcoinj.utils.ContextPropagatingThreadFactory; import org.bitcoinj.utils.ExponentialBackoff; import org.bitcoinj.utils.ListenableCompletableFuture; import org.bitcoinj.utils.ListenerRegistration; import org.bitcoinj.utils.Threading; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.listeners.KeyChainEventListener; import org.bitcoinj.wallet.listeners.ScriptsChangeEventListener; import org.bitcoinj.wallet.listeners.WalletCoinsReceivedEventListener; import org.bitcoinj.wallet.listeners.WalletCoinsSentEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.IOException; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NoRouteToHostException; import java.net.Socket; import java.net.SocketAddress; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.PriorityQueue; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>Runs a set of connections to the P2P network, brings up connections to replace disconnected nodes and manages * the interaction between them all. Most applications will want to use one of these.</p> * * <p>PeerGroup tries to maintain a constant number of connections to a set of distinct peers. * Each peer runs a network listener in its own thread. When a connection is lost, a new peer * will be tried after a delay as long as the number of connections less than the maximum.</p> * * <p>Connections are made to addresses from a provided list. When that list is exhausted, * we start again from the head of the list.</p> * * <p>The PeerGroup can broadcast a transaction to the currently connected set of peers. It can * also handle download of the blockchain from peers, restarting the process when peers die.</p> * * <p>A PeerGroup won't do anything until you call the {@link PeerGroup#start()} method * which will block until peer discovery is completed and some outbound connections * have been initiated (it will return before handshaking is done, however). * You should call {@link PeerGroup#stop()} when finished. Note that not all methods * of PeerGroup are safe to call from a UI thread as some may do network IO, * but starting and stopping the service should be fine.</p> */ public class PeerGroup implements TransactionBroadcaster { private static final Logger log = LoggerFactory.getLogger(PeerGroup.class); protected final ReentrantLock lock = Threading.lock(PeerGroup.class); // All members in this class should be marked with final, volatile, @GuardedBy or a mix as appropriate to define // their thread safety semantics. Volatile requires a Hungarian-style v prefix. // By default we don't require any services because any peer will do. private long requiredServices = 0; /** * The default number of connections to the p2p network the library will try to build. This is set to 12 empirically. * It used to be 4, but because we divide the connection pool in two for broadcasting transactions, that meant we * were only sending transactions to two peers and sometimes this wasn't reliable enough: transactions wouldn't * get through. */ public static final int DEFAULT_CONNECTIONS = 12; private volatile int vMaxPeersToDiscoverCount = 100; private static final Duration DEFAULT_PEER_DISCOVERY_TIMEOUT = Duration.ofSeconds(5); private volatile Duration vPeerDiscoveryTimeout = DEFAULT_PEER_DISCOVERY_TIMEOUT; protected final NetworkParameters params; @Nullable protected final AbstractBlockChain chain; // This executor is used to queue up jobs: it's used when we don't want to use locks for mutual exclusion, // typically because the job might call in to user provided code that needs/wants the freedom to use the API // however it wants, or because a job needs to be ordered relative to other jobs like that. protected final ScheduledExecutorService executor; // Whether the peer group is currently running. Once shut down it cannot be restarted. private volatile boolean vRunning; // Whether the peer group has been started or not. An unstarted PG does not try to access the network. private volatile boolean vUsedUp; // Addresses to try to connect to, excluding active peers. @GuardedBy("lock") private final PriorityQueue<PeerAddress> inactives; @GuardedBy("lock") private final Map<PeerAddress, ExponentialBackoff> backoffMap; @GuardedBy("lock") private final Map<PeerAddress, Integer> priorityMap; // Currently active peers. This is an ordered list rather than a set to make unit tests predictable. private final CopyOnWriteArrayList<Peer> peers; // Currently connecting peers. private final CopyOnWriteArrayList<Peer> pendingPeers; private final ClientConnectionManager channels; // The peer that has been selected for the purposes of downloading announced data. @GuardedBy("lock") private Peer downloadPeer; // Callback for events related to chain download. @Nullable @GuardedBy("lock") private BlockchainDownloadEventListener downloadListener; private final CopyOnWriteArrayList<ListenerRegistration<BlocksDownloadedEventListener>> peersBlocksDownloadedEventListeners = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<ListenerRegistration<ChainDownloadStartedEventListener>> peersChainDownloadStartedEventListeners = new CopyOnWriteArrayList<>(); /** Callbacks for events related to peers connecting */ protected final CopyOnWriteArrayList<ListenerRegistration<PeerConnectedEventListener>> peerConnectedEventListeners = new CopyOnWriteArrayList<>(); /** Callbacks for events related to peer connection/disconnection */ protected final CopyOnWriteArrayList<ListenerRegistration<PeerDiscoveredEventListener>> peerDiscoveredEventListeners = new CopyOnWriteArrayList<>(); /** Callbacks for events related to peers disconnecting */ protected final CopyOnWriteArrayList<ListenerRegistration<PeerDisconnectedEventListener>> peerDisconnectedEventListeners = new CopyOnWriteArrayList<>(); /** Callbacks for events related to peer data being received */ private final CopyOnWriteArrayList<ListenerRegistration<GetDataEventListener>> peerGetDataEventListeners = new CopyOnWriteArrayList<>(); private final CopyOnWriteArrayList<ListenerRegistration<PreMessageReceivedEventListener>> peersPreMessageReceivedEventListeners = new CopyOnWriteArrayList<>(); protected final CopyOnWriteArrayList<ListenerRegistration<OnTransactionBroadcastListener>> peersTransactionBroadastEventListeners = new CopyOnWriteArrayList<>(); // Discover peers via addr and addrv2 messages? private volatile boolean vDiscoverPeersViaP2P = false; // Peer discovery sources, will be polled occasionally if there aren't enough inactives. private final CopyOnWriteArraySet<PeerDiscovery> peerDiscoverers; // The version message to use for new connections. @GuardedBy("lock") private VersionMessage versionMessage; // Maximum depth up to which pending transaction dependencies are downloaded, or 0 for disabled. @GuardedBy("lock") private int downloadTxDependencyDepth; // How many connections we want to have open at the current time. If we lose connections, we'll try opening more // until we reach this count. @GuardedBy("lock") private int maxConnections; // Minimum protocol version we will allow ourselves to connect to: require Bloom filtering. private volatile int vMinRequiredProtocolVersion; /** How many milliseconds to wait after receiving a pong before sending another ping. */ public static final long DEFAULT_PING_INTERVAL_MSEC = 2000; @GuardedBy("lock") private long pingIntervalMsec = DEFAULT_PING_INTERVAL_MSEC; @GuardedBy("lock") private boolean useLocalhostPeerWhenPossible = true; @GuardedBy("lock") private boolean ipv6Unreachable = false; @GuardedBy("lock") private Instant fastCatchupTime; private final CopyOnWriteArrayList<Wallet> wallets; private final CopyOnWriteArrayList<PeerFilterProvider> peerFilterProviders; // This event listener is added to every peer. It's here so when we announce transactions via an "inv", every // peer can fetch them. private final PeerListener peerListener = new PeerListener(); private int minBroadcastConnections = 0; private final ScriptsChangeEventListener walletScriptsEventListener = (wallet, scripts, isAddingScripts) -> recalculateFastCatchupAndFilter(FilterRecalculateMode.SEND_IF_CHANGED); private final KeyChainEventListener walletKeyEventListener = keys -> recalculateFastCatchupAndFilter(FilterRecalculateMode.SEND_IF_CHANGED); private final WalletCoinsReceivedEventListener walletCoinsReceivedEventListener = (wallet, tx, prevBalance, newBalance) -> onCoinsReceivedOrSent(wallet, tx); private final WalletCoinsSentEventListener walletCoinsSentEventListener = (wallet, tx, prevBalance, newBalance) -> onCoinsReceivedOrSent(wallet, tx); public static final int MAX_ADDRESSES_PER_ADDR_MESSAGE = 16; private void onCoinsReceivedOrSent(Wallet wallet, Transaction tx) { // We received a relevant transaction. We MAY need to recalculate and resend the Bloom filter, but only // if we have received a transaction that includes a relevant P2PK or P2WPKH output. // // The reason is that P2PK and P2WPKH outputs, when spent, will not repeat any data we can predict in their // inputs. So a remote peer will update the Bloom filter for us when such an output is seen matching the // existing filter, so that it includes the tx hash in which the P2PK/P2WPKH output was observed. Thus // the spending transaction will always match (due to the outpoint structure). // // Unfortunately, whilst this is required for correct sync of the chain in blocks, there are two edge cases. // // (1) If a wallet receives a relevant, confirmed P2PK/P2WPKH output that was not broadcast across the network, // for example in a coinbase transaction, then the node that's serving us the chain will update its filter // but the rest will not. If another transaction then spends it, the other nodes won't match/relay it. // // (2) If we receive a P2PK/P2WPKH output broadcast across the network, all currently connected nodes will see // it and update their filter themselves, but any newly connected nodes will receive the last filter we // calculated, which would not include this transaction. // // For this reason we check if the transaction contained any relevant P2PKs or P2WPKHs and force a recalc // and possibly retransmit if so. The recalculation process will end up including the tx hash into the // filter. In case (1), we need to retransmit the filter to the connected peers. In case (2), we don't // and shouldn't, we should just recalculate and cache the new filter for next time. for (TransactionOutput output : tx.getOutputs()) { Script scriptPubKey = output.getScriptPubKey(); if (ScriptPattern.isP2PK(scriptPubKey) || ScriptPattern.isP2WPKH(scriptPubKey)) { if (output.isMine(wallet)) { if (tx.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) recalculateFastCatchupAndFilter(FilterRecalculateMode.SEND_IF_CHANGED); else recalculateFastCatchupAndFilter(FilterRecalculateMode.DONT_SEND); return; } } } } // Exponential backoff for peers starts at 1 second and maxes at 10 minutes. private final ExponentialBackoff.Params peerBackoffParams = new ExponentialBackoff.Params(Duration.ofSeconds(1), 1.5f, Duration.ofMinutes(10)); // Tracks failures globally in case of a network failure. @GuardedBy("lock") private ExponentialBackoff groupBackoff = new ExponentialBackoff(new ExponentialBackoff.Params(Duration.ofSeconds(1), 1.5f, Duration.ofSeconds(10))); // This is a synchronized set, so it locks on itself. We use it to prevent TransactionBroadcast objects from // being garbage collected if nothing in the apps code holds on to them transitively. See the discussion // in broadcastTransaction. private final Set<TransactionBroadcast> runningBroadcasts; private class PeerListener implements GetDataEventListener, BlocksDownloadedEventListener, AddressEventListener { public PeerListener() { } @Override public List<Message> getData(Peer peer, GetDataMessage m) { return handleGetData(m); } @Override public void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) { if (chain == null) return; final double rate = chain.getFalsePositiveRate(); final double target = bloomFilterMerger.getBloomFilterFPRate() * MAX_FP_RATE_INCREASE; if (rate > target) { // TODO: Avoid hitting this path if the remote peer didn't acknowledge applying a new filter yet. log.info("Force update Bloom filter due to high false positive rate ({} vs {})", rate, target); recalculateFastCatchupAndFilter(FilterRecalculateMode.FORCE_SEND_FOR_REFRESH); } } /** * Called when a peer receives an {@code addr} or {@code addrv2} message, usually in response to a * {@code getaddr} message. * * @param peer the peer that received the addr or addrv2 message * @param message the addr or addrv2 message that was received */ @Override public void onAddr(Peer peer, AddressMessage message) { if (!vDiscoverPeersViaP2P) return; List<PeerAddress> addresses = new LinkedList<>(message.getAddresses()); // Make sure we pick random addresses. Collections.shuffle(addresses); int numAdded = 0; for (PeerAddress address : addresses) { // Add to inactive pool. boolean added = addInactive(address, 0); if (added) numAdded++; // Limit addresses picked per message. if (numAdded >= MAX_ADDRESSES_PER_ADDR_MESSAGE) break; } log.info("{} gossiped {} addresses, added {} of them to the inactive pool", peer.getAddress(), addresses.size(), numAdded); } } private class PeerStartupListener implements PeerConnectedEventListener, PeerDisconnectedEventListener { @Override public void onPeerConnected(Peer peer, int peerCount) { handleNewPeer(peer); } @Override public void onPeerDisconnected(Peer peer, int peerCount) { // The channel will be automatically removed from channels. handlePeerDeath(peer, null); } } private final PeerStartupListener startupListener = new PeerStartupListener(); /** * The default Bloom filter false positive rate, which is selected to be extremely low such that you hardly ever * download false positives. This provides maximum performance. Although this default can be overridden to push * the FP rate higher, due to <a href="https://groups.google.com/forum/#!msg/bitcoinj/Ys13qkTwcNg/9qxnhwnkeoIJ"> * various complexities</a> there are still ways a remote peer can deanonymize the users wallet. This is why the * FP rate is chosen for performance rather than privacy. If a future version of bitcoinj fixes the known * de-anonymization attacks this FP rate may rise again (or more likely, become expressed as a bandwidth allowance). */ public static final double DEFAULT_BLOOM_FILTER_FP_RATE = 0.00001; /** Maximum increase in FP rate before forced refresh of the bloom filter */ public static final double MAX_FP_RATE_INCREASE = 10.0f; // An object that calculates bloom filters given a list of filter providers, whilst tracking some state useful // for privacy purposes. private final FilterMerger bloomFilterMerger; /** The default timeout between when a connection attempt begins and version message exchange completes */ public static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(5); private volatile Duration vConnectTimeout = DEFAULT_CONNECT_TIMEOUT; /** Whether bloom filter support is enabled when using a non FullPrunedBlockchain*/ private volatile boolean vBloomFilteringEnabled = true; /** * Creates a PeerGroup for the given network. No chain is provided so this node will report its chain height * as zero to other peers. This constructor is useful if you just want to explore the network but aren't interested * in downloading block data. * @param network the P2P network to connect to */ public PeerGroup(Network network) { this(network, null); } /** * Creates a PeerGroup with the given network. No chain is provided so this node will report its chain height * as zero to other peers. This constructor is useful if you just want to explore the network but aren't interested * in downloading block data. * @deprecated Use {@link #PeerGroup(Network)} */ @Deprecated public PeerGroup(NetworkParameters params) { this(params.network()); } /** * Creates a PeerGroup for the given network and chain. Blocks will be passed to the chain as they are broadcast * and downloaded. This is probably the constructor you want to use. * @param network the P2P network to connect to * @param chain used to process blocks */ public PeerGroup(Network network, @Nullable AbstractBlockChain chain) { this(network, chain, new NioClientManager()); } /** * Creates a PeerGroup for the given network and chain. Blocks will be passed to the chain as they are broadcast * and downloaded. * @deprecated Use {@link PeerGroup#PeerGroup(Network, AbstractBlockChain)} */ @Deprecated public PeerGroup(NetworkParameters params, @Nullable AbstractBlockChain chain) { this(params.network(), chain); } /** * Create a PeerGroup for the given network, chain and connection manager. * @param network the P2P network to connect to * @param chain used to process blocks * @param connectionManager used to create new connections and keep track of existing ones. */ protected PeerGroup(Network network, @Nullable AbstractBlockChain chain, ClientConnectionManager connectionManager) { this(NetworkParameters.of(Objects.requireNonNull(network)), chain, connectionManager); } /** * Create a PeerGroup for the given network, chain and connection manager. * @param params the P2P network to connect to * @param chain used to process blocks * @param connectionManager used to create new connections and keep track of existing ones. */ @VisibleForTesting protected PeerGroup(NetworkParameters params, @Nullable AbstractBlockChain chain, ClientConnectionManager connectionManager) { Objects.requireNonNull(params); Context.getOrCreate(); // create a context for convenience this.params = params; this.chain = chain; fastCatchupTime = params.getGenesisBlock().time(); wallets = new CopyOnWriteArrayList<>(); peerFilterProviders = new CopyOnWriteArrayList<>(); executor = createPrivateExecutor(); // This default sentinel value will be overridden by one of two actions: // - adding a peer discovery source sets it to the default // - using connectTo() will increment it by one maxConnections = 0; int height = chain == null ? 0 : chain.getBestChainHeight(); versionMessage = new VersionMessage(params, height); // We never request that the remote node wait for a bloom filter yet, as we have no wallets versionMessage.relayTxesBeforeFilter = true; downloadTxDependencyDepth = Integer.MAX_VALUE; inactives = new PriorityQueue<>(1, new Comparator<PeerAddress>() { @SuppressWarnings("FieldAccessNotGuarded") // only called when inactives is accessed, and lock is held then. @Override public int compare(PeerAddress a, PeerAddress b) { checkState(lock.isHeldByCurrentThread()); int result = backoffMap.get(a).compareTo(backoffMap.get(b)); if (result != 0) return result; result = Integer.compare(getPriority(a), getPriority(b)); if (result != 0) return result; // Sort by port if otherwise equals - for testing result = Integer.compare(a.getPort(), b.getPort()); return result; } }); backoffMap = new HashMap<>(); priorityMap = new ConcurrentHashMap<>(); peers = new CopyOnWriteArrayList<>(); pendingPeers = new CopyOnWriteArrayList<>(); channels = connectionManager; peerDiscoverers = new CopyOnWriteArraySet<>(); runningBroadcasts = Collections.synchronizedSet(new HashSet<TransactionBroadcast>()); bloomFilterMerger = new FilterMerger(DEFAULT_BLOOM_FILTER_FP_RATE); vMinRequiredProtocolVersion = ProtocolVersion.BLOOM_FILTER.intValue(); } private CountDownLatch executorStartupLatch = new CountDownLatch(1); protected ScheduledExecutorService createPrivateExecutor() { ScheduledExecutorService result = new ScheduledThreadPoolExecutor(1, new ContextPropagatingThreadFactory("PeerGroup Thread")); // Hack: jam the executor so jobs just queue up until the user calls start() on us. For example, adding a wallet // results in a bloom filter recalc being queued, but we don't want to do that until we're actually started. result.execute(() -> Uninterruptibles.awaitUninterruptibly(executorStartupLatch)); return result; } /** * This is how long we wait for peer discoveries to return their results. */ public void setPeerDiscoveryTimeout(Duration peerDiscoveryTimeout) { this.vPeerDiscoveryTimeout = peerDiscoveryTimeout; } /** * This is how many milliseconds we wait for peer discoveries to return their results. * @deprecated use {@link #setPeerDiscoveryTimeout(Duration)} */ @Deprecated public void setPeerDiscoveryTimeoutMillis(long peerDiscoveryTimeoutMillis) { setPeerDiscoveryTimeout(Duration.ofMillis(peerDiscoveryTimeoutMillis)); } /** * 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. */ 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); } /** * Configure download of pending transaction dependencies. A change of values only takes effect for newly connected * peers. */ public void setDownloadTxDependencies(int depth) { lock.lock(); try { this.downloadTxDependencyDepth = depth; } finally { lock.unlock(); } } private Runnable triggerConnectionsJob = new Runnable() { private boolean firstRun = true; private final Duration MIN_PEER_DISCOVERY_INTERVAL = Duration.ofSeconds(1); @Override public void run() { try { go(); } catch (Throwable e) { log.error("Exception when trying to build connections", e); // The executor swallows exceptions :( } } public void go() { if (!vRunning) return; boolean doDiscovery = false; Instant now = TimeUtils.currentTime(); lock.lock(); try { // First run: try and use a local node if there is one, for the additional security it can provide. // But, not on Android as there are none for this platform: it could only be a malicious app trying // to hijack our traffic. if (!PlatformUtils.isAndroidRuntime() && useLocalhostPeerWhenPossible && maybeCheckForLocalhostPeer() && firstRun) { log.info("Localhost peer detected, trying to use it instead of P2P discovery"); maxConnections = 0; connectToLocalHost(); return; } boolean havePeerWeCanTry = !inactives.isEmpty() && backoffMap.get(inactives.peek()).retryTime().isBefore(now); doDiscovery = !havePeerWeCanTry; } finally { firstRun = false; lock.unlock(); } // Don't hold the lock across discovery as this process can be very slow. boolean discoverySuccess = false; if (doDiscovery) { discoverySuccess = discoverPeers() > 0; } lock.lock(); try { if (doDiscovery) { // Require that we have enough connections, to consider this // a success, or we just constantly test for new peers if (discoverySuccess && countConnectedAndPendingPeers() >= getMaxConnections()) { groupBackoff.trackSuccess(); } else { groupBackoff.trackFailure(); } } // Inactives is sorted by backoffMap time. if (inactives.isEmpty()) { if (countConnectedAndPendingPeers() < getMaxConnections()) { Duration interval = TimeUtils.longest(Duration.between(now, groupBackoff.retryTime()), MIN_PEER_DISCOVERY_INTERVAL); log.info("Peer discovery didn't provide us any more peers, will try again in " + interval.toMillis() + " ms."); executor.schedule(this, interval.toMillis(), TimeUnit.MILLISECONDS); } else { // We have enough peers and discovery provided no more, so just settle down. Most likely we // were given a fixed set of addresses in some test scenario. } return; } PeerAddress addrToTry; do { addrToTry = inactives.poll(); } while (ipv6Unreachable && addrToTry.getAddr() instanceof Inet6Address); if (addrToTry == null) { // We have exhausted the queue of reachable peers, so just settle down. // Most likely we were given a fixed set of addresses in some test scenario. return; } Instant retryTime = backoffMap.get(addrToTry).retryTime(); retryTime = TimeUtils.later(retryTime, groupBackoff.retryTime()); if (retryTime.isAfter(now)) { Duration delay = Duration.between(now, retryTime); log.info("Waiting {} ms before next connect attempt to {}", delay.toMillis(), addrToTry); inactives.add(addrToTry); executor.schedule(this, delay.toMillis(), TimeUnit.MILLISECONDS); return; } connectTo(addrToTry, false, vConnectTimeout); } finally { lock.unlock(); } if (countConnectedAndPendingPeers() < getMaxConnections()) { executor.execute(this); // Try next peer immediately. } } }; private void triggerConnections() { // Run on a background thread due to the need to potentially retry and back off in the background. if (!executor.isShutdown()) executor.execute(triggerConnectionsJob); } /** The maximum number of connections that we will create to peers. */ public int getMaxConnections() { lock.lock(); try { return maxConnections; } finally { lock.unlock(); } } private List<Message> handleGetData(GetDataMessage m) { // Scans the wallets and memory pool for transactions in the getdata message and returns them. // Runs on peer threads. lock.lock(); try { LinkedList<Message> transactions = new LinkedList<>(); LinkedList<InventoryItem> items = new LinkedList<>(m.getItems()); Iterator<InventoryItem> it = items.iterator(); while (it.hasNext()) { InventoryItem item = it.next(); // Check the wallets. for (Wallet w : wallets) { Transaction tx = w.getTransaction(item.hash); if (tx == null) continue; transactions.add(tx); it.remove(); break; } } return transactions; } finally { lock.unlock(); } } /** * Sets the {@link VersionMessage} that will be announced on newly created connections. A version message is * primarily interesting because it lets you customize the "subVer" field which is used a bit like the User-Agent * field from HTTP. It means your client tells the other side what it is, see * <a href="https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki">BIP 14</a>. * * The VersionMessage you provide is copied and the best chain height/time filled in for each new connection, * therefore you don't have to worry about setting that. The provided object is really more of a template. */ public void setVersionMessage(VersionMessage ver) { lock.lock(); try { versionMessage = ver; } finally { lock.unlock(); } } /** * Returns the version message provided by setVersionMessage or a default if none was given. */ public VersionMessage getVersionMessage() { lock.lock(); try { return versionMessage; } finally { lock.unlock(); } } /** * Sets information that identifies this software to remote nodes. This is a convenience wrapper for creating * a new {@link VersionMessage}, calling {@link VersionMessage#appendToSubVer(String, String, String)} on it, * and then calling {@link PeerGroup#setVersionMessage(VersionMessage)} on the result of that. See the docs for * {@link VersionMessage#appendToSubVer(String, String, String)} for information on what the fields should contain. */ public void setUserAgent(String name, String version, @Nullable String comments) { //TODO Check that height is needed here (it wasnt, but it should be, no?) int height = chain == null ? 0 : chain.getBestChainHeight(); VersionMessage ver = new VersionMessage(params, height); ver.relayTxesBeforeFilter = false; updateVersionMessageRelayTxesBeforeFilter(ver); ver.appendToSubVer(name, version, comments); setVersionMessage(ver); } // Updates the relayTxesBeforeFilter flag of ver 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(); } } /** * Sets information that identifies this software to remote nodes. This is a convenience wrapper for creating * a new {@link VersionMessage}, calling {@link VersionMessage#appendToSubVer(String, String, String)} on it, * and then calling {@link PeerGroup#setVersionMessage(VersionMessage)} on the result of that. See the docs for * {@link VersionMessage#appendToSubVer(String, String, String)} for information on what the fields should contain. */ public void setUserAgent(String name, String version) { setUserAgent(name, version, null); } /** See {@link Peer#addBlocksDownloadedEventListener(BlocksDownloadedEventListener)} */ public void addBlocksDownloadedEventListener(BlocksDownloadedEventListener listener) { addBlocksDownloadedEventListener(Threading.USER_THREAD, listener); } /** * <p>Adds a listener that will be notified on the given executor when * blocks are downloaded by the download peer.</p> * @see Peer#addBlocksDownloadedEventListener(Executor, BlocksDownloadedEventListener) */ public void addBlocksDownloadedEventListener(Executor executor, BlocksDownloadedEventListener listener) { peersBlocksDownloadedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor)); for (Peer peer : getConnectedPeers()) peer.addBlocksDownloadedEventListener(executor, listener); for (Peer peer : getPendingPeers()) peer.addBlocksDownloadedEventListener(executor, listener); } /** See {@link Peer#addBlocksDownloadedEventListener(BlocksDownloadedEventListener)} */ public void addChainDownloadStartedEventListener(ChainDownloadStartedEventListener listener) { addChainDownloadStartedEventListener(Threading.USER_THREAD, listener); } /** * <p>Adds a listener that will be notified on the given executor when * chain download starts.</p> */ public void addChainDownloadStartedEventListener(Executor executor, ChainDownloadStartedEventListener listener) { peersChainDownloadStartedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor)); for (Peer peer : getConnectedPeers()) peer.addChainDownloadStartedEventListener(executor, listener); for (Peer peer : getPendingPeers()) peer.addChainDownloadStartedEventListener(executor, listener); } /** See {@link Peer#addConnectedEventListener(PeerConnectedEventListener)} */ public void addConnectedEventListener(PeerConnectedEventListener listener) { addConnectedEventListener(Threading.USER_THREAD, listener); } /** * <p>Adds a listener that will be notified on the given executor when * new peers are connected to.</p> */ public void addConnectedEventListener(Executor executor, PeerConnectedEventListener listener) { peerConnectedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor)); for (Peer peer : getConnectedPeers()) peer.addConnectedEventListener(executor, listener); for (Peer peer : getPendingPeers()) peer.addConnectedEventListener(executor, listener); } /** See {@link Peer#addDisconnectedEventListener(PeerDisconnectedEventListener)} */ public void addDisconnectedEventListener(PeerDisconnectedEventListener listener) { addDisconnectedEventListener(Threading.USER_THREAD, listener); } /** * <p>Adds a listener that will be notified on the given executor when * peers are disconnected from.</p> */ public void addDisconnectedEventListener(Executor executor, PeerDisconnectedEventListener listener) { peerDisconnectedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor)); for (Peer peer : getConnectedPeers()) peer.addDisconnectedEventListener(executor, listener); for (Peer peer : getPendingPeers()) peer.addDisconnectedEventListener(executor, listener); } /** See {@link PeerGroup#addDiscoveredEventListener(Executor, PeerDiscoveredEventListener)} */ public void addDiscoveredEventListener(PeerDiscoveredEventListener listener) { addDiscoveredEventListener(Threading.USER_THREAD, listener); } /** * <p>Adds a listener that will be notified on the given executor when new * peers are discovered.</p> */ public void addDiscoveredEventListener(Executor executor, PeerDiscoveredEventListener listener) { peerDiscoveredEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor)); } /** See {@link Peer#addGetDataEventListener(GetDataEventListener)} */ public void addGetDataEventListener(GetDataEventListener listener) { addGetDataEventListener(Threading.USER_THREAD, listener); } /** See {@link Peer#addGetDataEventListener(Executor, GetDataEventListener)} */ public void addGetDataEventListener(final Executor executor, final GetDataEventListener listener) { peerGetDataEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor)); for (Peer peer : getConnectedPeers()) peer.addGetDataEventListener(executor, listener); for (Peer peer : getPendingPeers()) peer.addGetDataEventListener(executor, listener); } /** See {@link Peer#addOnTransactionBroadcastListener(OnTransactionBroadcastListener)} */ public void addOnTransactionBroadcastListener(OnTransactionBroadcastListener listener) { addOnTransactionBroadcastListener(Threading.USER_THREAD, listener); } /** See {@link Peer#addOnTransactionBroadcastListener(OnTransactionBroadcastListener)} */ public void addOnTransactionBroadcastListener(Executor executor, OnTransactionBroadcastListener listener) { peersTransactionBroadastEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor)); for (Peer peer : getConnectedPeers()) peer.addOnTransactionBroadcastListener(executor, listener); for (Peer peer : getPendingPeers()) peer.addOnTransactionBroadcastListener(executor, listener); } /** See {@link Peer#addPreMessageReceivedEventListener(PreMessageReceivedEventListener)} */ public void addPreMessageReceivedEventListener(PreMessageReceivedEventListener listener) { addPreMessageReceivedEventListener(Threading.USER_THREAD, listener); } /** See {@link Peer#addPreMessageReceivedEventListener(Executor, PreMessageReceivedEventListener)} */ public void addPreMessageReceivedEventListener(Executor executor, PreMessageReceivedEventListener listener) { peersPreMessageReceivedEventListeners.add(new ListenerRegistration<>(Objects.requireNonNull(listener), executor)); for (Peer peer : getConnectedPeers()) peer.addPreMessageReceivedEventListener(executor, listener); for (Peer peer : getPendingPeers()) peer.addPreMessageReceivedEventListener(executor, listener); } public boolean removeBlocksDownloadedEventListener(BlocksDownloadedEventListener listener) { boolean result = ListenerRegistration.removeFromList(listener, peersBlocksDownloadedEventListeners); for (Peer peer : getConnectedPeers()) peer.removeBlocksDownloadedEventListener(listener); for (Peer peer : getPendingPeers()) peer.removeBlocksDownloadedEventListener(listener); return result; } public boolean removeChainDownloadStartedEventListener(ChainDownloadStartedEventListener listener) { boolean result = ListenerRegistration.removeFromList(listener, peersChainDownloadStartedEventListeners); for (Peer peer : getConnectedPeers()) peer.removeChainDownloadStartedEventListener(listener); for (Peer peer : getPendingPeers()) peer.removeChainDownloadStartedEventListener(listener); return result; } /** The given event listener will no longer be called with events. */ public boolean removeConnectedEventListener(PeerConnectedEventListener listener) { boolean result = ListenerRegistration.removeFromList(listener, peerConnectedEventListeners); for (Peer peer : getConnectedPeers()) peer.removeConnectedEventListener(listener); for (Peer peer : getPendingPeers()) peer.removeConnectedEventListener(listener); return result; } /** The given event listener will no longer be called with events. */ public boolean removeDisconnectedEventListener(PeerDisconnectedEventListener listener) { boolean result = ListenerRegistration.removeFromList(listener, peerDisconnectedEventListeners); for (Peer peer : getConnectedPeers()) peer.removeDisconnectedEventListener(listener); for (Peer peer : getPendingPeers()) peer.removeDisconnectedEventListener(listener); return result; } /** The given event listener will no longer be called with events. */ public boolean removeDiscoveredEventListener(PeerDiscoveredEventListener listener) { boolean result = ListenerRegistration.removeFromList(listener, peerDiscoveredEventListeners); return result; } /** The given event listener will no longer be called with events. */ public boolean removeGetDataEventListener(GetDataEventListener listener) { boolean result = ListenerRegistration.removeFromList(listener, peerGetDataEventListeners); for (Peer peer : getConnectedPeers()) peer.removeGetDataEventListener(listener); for (Peer peer : getPendingPeers()) peer.removeGetDataEventListener(listener); return result; } /** The given event listener will no longer be called with events. */ public boolean removeOnTransactionBroadcastListener(OnTransactionBroadcastListener listener) { boolean result = ListenerRegistration.removeFromList(listener, peersTransactionBroadastEventListeners); for (Peer peer : getConnectedPeers()) peer.removeOnTransactionBroadcastListener(listener); for (Peer peer : getPendingPeers()) peer.removeOnTransactionBroadcastListener(listener); return result; } public boolean removePreMessageReceivedEventListener(PreMessageReceivedEventListener listener) { boolean result = ListenerRegistration.removeFromList(listener, peersPreMessageReceivedEventListeners); for (Peer peer : getConnectedPeers()) peer.removePreMessageReceivedEventListener(listener); for (Peer peer : getPendingPeers()) peer.removePreMessageReceivedEventListener(listener); return result; } /** * Returns a newly allocated list containing the currently connected peers. If all you care about is the count, * use numConnectedPeers(). */ public List<Peer> getConnectedPeers() { lock.lock(); try { return new ArrayList<>(peers); } finally { lock.unlock(); } } /** * Returns a list containing Peers that did not complete connection yet. */ public List<Peer> getPendingPeers() { lock.lock(); try { return new ArrayList<>(pendingPeers); } 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. */ public void addAddress(PeerAddress peerAddress) { addAddress(peerAddress, 0); } /** * 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. * @param priority for connecting and being picked as a download peer */ public void addAddress(PeerAddress peerAddress, int priority) { int newMax; lock.lock(); try { if (addInactive(peerAddress, priority)) { newMax = getMaxConnections() + 1; setMaxConnections(newMax); } } finally { lock.unlock(); } } // Adds peerAddress to backoffMap map and inactives queue. // Returns true if it was added, false if it was already there. private boolean addInactive(PeerAddress peerAddress, int priority) { lock.lock(); try { // Deduplicate if (backoffMap.containsKey(peerAddress)) return false; backoffMap.put(peerAddress, new ExponentialBackoff(peerBackoffParams)); if (priority != 0) priorityMap.put(peerAddress, priority); inactives.offer(peerAddress); return true; } finally { lock.unlock(); } } private int getPriority(PeerAddress peerAddress) { Integer priority = priorityMap.get(peerAddress); return priority != null ? priority : 0; } /** * 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 Services#NODE_NETWORK}. */ public void setRequiredServices(long requiredServices) { lock.lock(); try { this.requiredServices = requiredServices; peerDiscoverers.clear(); addPeerDiscovery(MultiplexingDiscovery.forServices(params, requiredServices)); } finally { lock.unlock(); } } /** Convenience method for {@link #addAddress(PeerAddress)}. */ public void addAddress(InetAddress address) { addAddress(PeerAddress.simple(address, params.getPort())); } /** Convenience method for {@link #addAddress(PeerAddress, int)}. */ public void addAddress(InetAddress address, int priority) { addAddress(PeerAddress.simple(address, params.getPort()), priority); } /** * Setting this to {@code true} will add addresses discovered via P2P {@code addr} and {@code addrv2} messages to * the list of potential peers to connect to. This will automatically be set to true if at least one peer discovery * is added via {@link #addPeerDiscovery(PeerDiscovery)}. * * @param discoverPeersViaP2P true if peers should be discovered from the P2P network */ public void setDiscoverPeersViaP2P(boolean discoverPeersViaP2P) { vDiscoverPeersViaP2P = discoverPeersViaP2P; } /** * 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. */ public void addPeerDiscovery(PeerDiscovery peerDiscovery) { lock.lock(); try { if (getMaxConnections() == 0) setMaxConnections(DEFAULT_CONNECTIONS); peerDiscoverers.add(peerDiscovery); } finally { lock.unlock(); } setDiscoverPeersViaP2P(true); } /** Returns number of discovered peers. */ 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; Duration peerDiscoveryTimeout = this.vPeerDiscoveryTimeout; Stopwatch watch = Stopwatch.start(); final List<PeerAddress> addressList = new LinkedList<>(); for (PeerDiscovery peerDiscovery : peerDiscoverers /* COW */) { List<InetSocketAddress> addresses; try { addresses = peerDiscovery.getPeers(requiredServices, peerDiscoveryTimeout); } catch (PeerDiscoveryException e) { log.warn(e.getMessage()); continue; } for (InetSocketAddress address : addresses) addressList.add(PeerAddress.simple(address)); if (addressList.size() >= maxPeersToDiscoverCount) break; } if (!addressList.isEmpty()) { for (PeerAddress address : addressList) { addInactive(address, 0); } final Set<PeerAddress> peersDiscoveredSet = Collections.unmodifiableSet(new HashSet<>(addressList)); for (final ListenerRegistration<PeerDiscoveredEventListener> registration : peerDiscoveredEventListeners /* COW */) { registration.executor.execute(() -> registration.listener.onPeersDiscovered(peersDiscoveredSet)); } } log.info("Peer discovery took {} and returned {} items from {} discoverers", watch, addressList.size(), peerDiscoverers.size()); return addressList.size(); } @VisibleForTesting void waitForJobQueue() { Futures.getUnchecked(executor.submit(Runnables.doNothing())); } private int countConnectedAndPendingPeers() { lock.lock(); try { return peers.size() + pendingPeers.size(); } finally { lock.unlock(); } } private enum LocalhostCheckState { NOT_TRIED, FOUND, FOUND_AND_CONNECTED, NOT_THERE } private LocalhostCheckState localhostCheckState = LocalhostCheckState.NOT_TRIED; private boolean maybeCheckForLocalhostPeer() { checkState(lock.isHeldByCurrentThread()); if (localhostCheckState == LocalhostCheckState.NOT_TRIED) { // Do a fast blocking connect to see if anything is listening. try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), params.getPort()), Math.toIntExact(vConnectTimeout.toMillis())); localhostCheckState = LocalhostCheckState.FOUND; return true; } catch (IOException e) { log.info("Localhost peer not detected."); localhostCheckState = LocalhostCheckState.NOT_THERE; } } return false; } /** * Starts the PeerGroup and begins network activity. * @return A future that completes when first connection activity has been triggered (note: not first connection made). */ public ListenableCompletableFuture<Void> 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. CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { try { log.info("Starting ..."); channels.startAsync(); channels.awaitRunning(); triggerConnections(); setupPinging(); } catch (Throwable e) { log.error("Exception when starting up", e); // The executor swallows exceptions :( } }, executor); return ListenableCompletableFuture.of(future); } /** Does a blocking startup. */ public void start() { startAsync().join(); } public ListenableCompletableFuture<Void> stopAsync() { checkState(vRunning); vRunning = false; CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { try { log.info("Stopping ..."); Stopwatch watch = Stopwatch.start(); // The log output this creates can be useful. setDownloadPeer(null); // Blocking close of all sockets. channels.stopAsync(); channels.awaitTerminated(); for (PeerDiscovery peerDiscovery : peerDiscoverers) { peerDiscovery.shutdown(); } vRunning = false; log.info("Stopped, took {}.", watch); } catch (Throwable e) { log.error("Exception when shutting down", e); // The executor swallows exceptions :( } }, executor); executor.shutdown(); return ListenableCompletableFuture.of(future); } /** Does a blocking stop */ public void stop() { try { Stopwatch watch = Stopwatch.start(); stopAsync(); log.info("Awaiting PeerGroup shutdown ..."); executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); log.info("... took {}", watch); } catch (InterruptedException e) { throw new RuntimeException(e); } } /** * Gracefully drops all connected peers. */ public void dropAllPeers() { lock.lock(); try { for (Peer peer : peers) peer.close(); } finally { lock.unlock(); } } /** * <p>Link the given wallet to this PeerGroup. This is used for three purposes:</p> * * <ol> * <li>So the wallet receives broadcast transactions.</li> * <li>Announcing pending transactions that didn't get into the chain yet to our peers.</li> * <li>Set the fast catchup time using {@link PeerGroup#setFastCatchupTimeSecs(long)}, to optimize chain * download.</li> * </ol> * * <p>Note that this should be done before chain download commences because if you add a wallet with keys earlier * than the current chain head, the relevant parts of the chain won't be redownloaded for you.</p> * * <p>The Wallet will have an event listener registered on it, so to avoid leaks remember to use * {@link PeerGroup#removeWallet(Wallet)} on it if you wish to keep the Wallet but lose the PeerGroup.</p> */ public void addWallet(Wallet wallet) { lock.lock(); try { Objects.requireNonNull(wallet); checkState(!wallets.contains(wallet)); wallets.add(wallet); wallet.setTransactionBroadcaster(this); wallet.addCoinsReceivedEventListener(Threading.SAME_THREAD, walletCoinsReceivedEventListener); wallet.addCoinsSentEventListener(Threading.SAME_THREAD, walletCoinsSentEventListener); wallet.addKeyChainEventListener(Threading.SAME_THREAD, walletKeyEventListener); wallet.addScriptsChangeEventListener(Threading.SAME_THREAD, walletScriptsEventListener); addPeerFilterProvider(wallet); for (Peer peer : peers) { peer.addWallet(wallet); } } finally { lock.unlock(); } } /** * <p>Link the given PeerFilterProvider to this PeerGroup. DO NOT use this for Wallets, use * {@link PeerGroup#addWallet(Wallet)} instead.</p> * * <p>Note that this should be done before chain download commences because if you add a listener with keys earlier * than the current chain head, the relevant parts of the chain won't be redownloaded for you.</p> * * <p>This method invokes {@link PeerGroup#recalculateFastCatchupAndFilter(FilterRecalculateMode)}. * The return value of this method is the {@code ListenableCompletableFuture} returned by that invocation.</p> * * @return a future that completes once each {@code Peer} in this group has had its * {@code BloomFilter} (re)set. */ public ListenableCompletableFuture<BloomFilter> addPeerFilterProvider(PeerFilterProvider provider) { lock.lock(); try { Objects.requireNonNull(provider); checkState(!peerFilterProviders.contains(provider)); // Insert provider at the start. This avoids various concurrency problems that could occur because we need // all providers to be in a consistent, unchanging state whilst the filter is built. Providers can give // this guarantee by taking a lock in their begin method, but if we add to the end of the list here, it // means we establish a lock ordering a > b > c if that's the order the providers were added in. Given that // the main wallet will usually be first, this establishes an ordering wallet > other-provider, which means // other-provider can then not call into the wallet itself. Other providers installed by the API user should // come first so the expected ordering is preserved. This can also manifest itself in providers that use // synchronous RPCs into an actor instead of locking, but the same issue applies. peerFilterProviders.add(0, provider); // Don't bother downloading block bodies before the oldest keys in all our wallets. Make sure we recalculate // if a key is added. Of course, by then we may have downloaded the chain already. Ideally adding keys would // automatically rewind the block chain and redownload the blocks to find transactions relevant to those keys, // all transparently and in the background. But we are a long way from that yet. ListenableCompletableFuture<BloomFilter> future = recalculateFastCatchupAndFilter(FilterRecalculateMode.SEND_IF_CHANGED); updateVersionMessageRelayTxesBeforeFilter(getVersionMessage()); return future; } finally { lock.unlock(); } } /** * Opposite of {@link #addPeerFilterProvider(PeerFilterProvider)}. Again, don't use this for wallets. Does not * trigger recalculation of the filter. */ public void removePeerFilterProvider(PeerFilterProvider provider) { lock.lock(); try { Objects.requireNonNull(provider); checkArgument(peerFilterProviders.remove(provider)); } finally { lock.unlock(); } } /** * Unlinks the given wallet so it no longer receives broadcast transactions or has its transactions announced. */ public void removeWallet(Wallet wallet) { wallets.remove(Objects.requireNonNull(wallet)); peerFilterProviders.remove(wallet); wallet.removeCoinsReceivedEventListener(walletCoinsReceivedEventListener); wallet.removeCoinsSentEventListener(walletCoinsSentEventListener); wallet.removeKeyChainEventListener(walletKeyEventListener); wallet.removeScriptsChangeEventListener(walletScriptsEventListener); wallet.setTransactionBroadcaster(null); for (Peer peer : peers) { peer.removeWallet(wallet); } } public enum FilterRecalculateMode { SEND_IF_CHANGED, FORCE_SEND_FOR_REFRESH, DONT_SEND, } private final Map<FilterRecalculateMode, ListenableCompletableFuture<BloomFilter>> inFlightRecalculations = Maps.newHashMap(); /** * Recalculates the bloom filter given to peers as well as the timestamp after which full blocks are downloaded * (instead of only headers). Note that calls made one after another may return the same future, if the request * wasn't processed yet (i.e. calls are deduplicated). * * @param mode In what situations to send the filter to connected peers. * @return a future that completes once the filter has been calculated (note: this does not mean acknowledged by remote peers). */ public ListenableCompletableFuture<BloomFilter> recalculateFastCatchupAndFilter(final FilterRecalculateMode mode) { final ListenableCompletableFuture<BloomFilter> future = new ListenableCompletableFuture<>(); synchronized (inFlightRecalculations) { if (inFlightRecalculations.get(mode) != null) return inFlightRecalculations.get(mode); inFlightRecalculations.put(mode, future); } Runnable command = new Runnable() { @Override public void run() { try { go(); } catch (Throwable e) { log.error("Exception when trying to recalculate Bloom filter", e); // The executor swallows exceptions :( } } public void go() { checkState(!lock.isHeldByCurrentThread()); // Fully verifying mode doesn't use this optimization (it can't as it needs to see all transactions). if ((chain != null && chain.shouldVerifyTransactions()) || !vBloomFilteringEnabled) return; // We only ever call bloomFilterMerger.calculate on jobQueue, so we cannot be calculating two filters at once. FilterMerger.Result result = bloomFilterMerger.calculate(Collections.unmodifiableList(peerFilterProviders /* COW */)); boolean send; switch (mode) { case SEND_IF_CHANGED: send = result.changed; break; case DONT_SEND: send = false; break; case FORCE_SEND_FOR_REFRESH: send = true; break; default: throw new UnsupportedOperationException(); } if (send) { for (Peer peer : peers /* COW */) { // Only query the mempool if this recalculation request is not in order to lower the observed FP // rate. There's no point querying the mempool when doing this because the FP rate can only go // down, and we will have seen all the relevant txns before: it's pointless to ask for them again. peer.setBloomFilter(result.filter, mode != FilterRecalculateMode.FORCE_SEND_FOR_REFRESH); } // Reset the false positive estimate so that we don't send a flood of filter updates // if the estimate temporarily overshoots our threshold. if (chain != null) chain.resetFalsePositiveEstimate(); } // Do this last so that bloomFilter is already set when it gets called. setFastCatchupTime(result.earliestKeyTime); synchronized (inFlightRecalculations) { inFlightRecalculations.put(mode, null); } future.complete(result.filter); } }; try { executor.execute(command); } catch (RejectedExecutionException e) { // Can happen during shutdown. } return future; } /** * <p>Sets the false positive rate of bloom filters given to peers. The default is {@link #DEFAULT_BLOOM_FILTER_FP_RATE}.</p> * * <p>Be careful regenerating the bloom filter too often, as it decreases anonymity because remote nodes can * compare transactions against both the new and old filters to significantly decrease the false positive rate.</p> * * <p>See the docs for {@link BloomFilter#BloomFilter(int, double, int, BloomFilter.BloomUpdate)} for a brief * explanation of anonymity when using bloom filters.</p> */ public void setBloomFilterFalsePositiveRate(double bloomFilterFPRate) { lock.lock(); try { bloomFilterMerger.setBloomFilterFPRate(bloomFilterFPRate); recalculateFastCatchupAndFilter(FilterRecalculateMode.SEND_IF_CHANGED); } finally { lock.unlock(); } } /** * Returns the number of currently connected peers. To be informed when this count changes, use * {@link PeerConnectedEventListener#onPeerConnected} and {@link PeerDisconnectedEventListener#onPeerDisconnected}. */ public int numConnectedPeers() { return peers.size(); } /** * Connect to a peer by creating a channel to the destination address. This should not be * used normally - let the PeerGroup manage connections through {@link #start()} * * @param address destination IP and port. * @return The newly created Peer object or null if the peer could not be connected. * Use {@link Peer#getConnectionOpenFuture()} if you * want a future which completes when the connection is open. */ @Nullable public Peer connectTo(InetSocketAddress address) { lock.lock(); try { PeerAddress peerAddress = PeerAddress.simple(address); backoffMap.put(peerAddress, new ExponentialBackoff(peerBackoffParams)); return connectTo(peerAddress, true, vConnectTimeout); } finally { lock.unlock(); } } /** * Helper for forcing a connection to localhost. Useful when using regtest mode. Returns the peer object. */ @Nullable public Peer connectToLocalHost() { lock.lock(); try { final PeerAddress localhost = PeerAddress.localhost(params); backoffMap.put(localhost, new ExponentialBackoff(peerBackoffParams)); return connectTo(localhost, true, vConnectTimeout); } finally { lock.unlock(); } } /** * 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. * @param connectTimeout timeout for establishing the connection to peers * @return Peer or null. */ @Nullable @GuardedBy("lock") protected Peer connectTo(PeerAddress address, boolean incrementMaxConnections, Duration connectTimeout) { checkState(lock.isHeldByCurrentThread()); VersionMessage ver = getVersionMessage().duplicate(); ver.bestHeight = chain == null ? 0 : chain.getBestChainHeight(); ver.time = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS); ver.receivingAddr = new InetSocketAddress(address.getAddr(), address.getPort()); 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); CompletableFuture<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(connectTimeout); // 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; } /** You can override this to customise the creation of {@link Peer} objects. */ @GuardedBy("lock") protected Peer createPeer(PeerAddress address, VersionMessage ver) { return new Peer(params, ver, address, chain, requiredServices, downloadTxDependencyDepth); } /** * Sets the timeout between when a connection attempt to a peer begins and when the version message exchange * completes. This does not apply to currently pending peers. * @param connectTimeout timeout for estiablishing the connection to peers */ public void setConnectTimeout(Duration connectTimeout) { this.vConnectTimeout = connectTimeout; } /** @deprecated use {@link #setConnectTimeout(Duration)} */ @Deprecated public void setConnectTimeoutMillis(int connectTimeoutMillis) { setConnectTimeout(Duration.ofMillis(connectTimeoutMillis)); } /** * <p>Start downloading the blockchain.</p> * * <p>If no peers are currently connected, the download will be started once a peer starts. If the peer dies, * the download will resume with another peer.</p> * * @param listener a listener for chain download events, may not be null */ public void startBlockChainDownload(BlockchainDownloadEventListener listener) { lock.lock(); try { if (downloadPeer != null) { if (this.downloadListener != null) { removeDataEventListenerFromPeer(downloadPeer, this.downloadListener); } if (listener != null) { addDataEventListenerToPeer(Threading.USER_THREAD, downloadPeer, listener); } } this.downloadListener = listener; } finally { lock.unlock(); } } /** * Register a data event listener against a single peer (i.e. for blockchain * download). Handling registration/deregistration on peer death/add is * outside the scope of these methods. */ private static void addDataEventListenerToPeer(Executor executor, Peer peer, BlockchainDownloadEventListener downloadListener) { peer.addBlocksDownloadedEventListener(executor, downloadListener); peer.addChainDownloadStartedEventListener(executor, downloadListener); } /** * Remove a registered data event listener against a single peer (i.e. for * blockchain download). Handling registration/deregistration on peer death/add is * outside the scope of these methods. */ private static void removeDataEventListenerFromPeer(Peer peer, BlockchainDownloadEventListener listener) { peer.removeBlocksDownloadedEventListener(listener); peer.removeChainDownloadStartedEventListener(listener); } /** * Download the blockchain from peers. Convenience that uses a {@link DownloadProgressTracker} for you.<p> * * This method waits until the download is complete. "Complete" is defined as downloading * from at least one peer all the blocks that are in that peer's inventory. */ public void downloadBlockChain() { DownloadProgressTracker listener = new DownloadProgressTracker(); startBlockChainDownload(listener); try { listener.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } protected void handleNewPeer(final Peer peer) { int newSize = -1; lock.lock(); try { groupBackoff.trackSuccess(); backoffMap.get(peer.getAddress()).trackSuccess(); // Sets up the newly connected peer so it can do everything it needs to. pendingPeers.remove(peer); peers.add(peer); newSize = peers.size(); log.info("{}: New peer ({} connected, {} pending, {} max)", peer, newSize, pendingPeers.size(), maxConnections); // Give the peer a filter that can be used to probabilistically drop transactions that // aren't relevant to our wallet. We may still receive some false positives, which is // OK because it helps improve wallet privacy. Old nodes will just ignore the message. if (bloomFilterMerger.getLastFilter() != null) peer.setBloomFilter(bloomFilterMerger.getLastFilter()); peer.setDownloadData(false); // TODO: The peer should calculate the fast catchup time from the added wallets here. for (Wallet wallet : wallets) peer.addWallet(wallet); if (downloadPeer == null && newSize > maxConnections / 2) { Peer newDownloadPeer = selectDownloadPeer(peers); if (newDownloadPeer != null) { setDownloadPeer(newDownloadPeer); // Kick off chain download if we aren't already doing it. boolean shouldDownloadChain = downloadListener != null && chain != null; if (shouldDownloadChain) { startBlockChainDownloadFromPeer(downloadPeer); } } else { log.info("Not yet setting download peer because there is no clear candidate."); } } // Make sure the peer knows how to upload transactions that are requested from us. peer.addBlocksDownloadedEventListener(Threading.SAME_THREAD, peerListener); peer.addGetDataEventListener(Threading.SAME_THREAD, peerListener); // Discover other peers. peer.addAddressEventListener(Threading.SAME_THREAD, peerListener); // And set up event listeners for clients. This will allow them to find out about new transactions and blocks. for (ListenerRegistration<BlocksDownloadedEventListener> registration : peersBlocksDownloadedEventListeners) peer.addBlocksDownloadedEventListener(registration.executor, registration.listener); for (ListenerRegistration<ChainDownloadStartedEventListener> registration : peersChainDownloadStartedEventListeners) peer.addChainDownloadStartedEventListener(registration.executor, registration.listener); for (ListenerRegistration<PeerConnectedEventListener> registration : peerConnectedEventListeners) peer.addConnectedEventListener(registration.executor, registration.listener); // We intentionally do not add disconnect listeners to peers for (ListenerRegistration<GetDataEventListener> registration : peerGetDataEventListeners) peer.addGetDataEventListener(registration.executor, registration.listener); for (ListenerRegistration<OnTransactionBroadcastListener> registration : peersTransactionBroadastEventListeners) peer.addOnTransactionBroadcastListener(registration.executor, registration.listener); for (ListenerRegistration<PreMessageReceivedEventListener> registration : peersPreMessageReceivedEventListeners) peer.addPreMessageReceivedEventListener(registration.executor, registration.listener); } finally { lock.unlock(); } final int fNewSize = newSize; for (final ListenerRegistration<PeerConnectedEventListener> registration : peerConnectedEventListeners) { registration.executor.execute(() -> registration.listener.onPeerConnected(peer, fNewSize)); } // Discovery more peers. if (vDiscoverPeersViaP2P) peer.sendMessage(new GetAddrMessage()); } @Nullable private volatile ScheduledFuture<?> vPingTask; @SuppressWarnings("NonAtomicOperationOnVolatileField") private void setupPinging() { if (getPingIntervalMsec() <= 0) return; // Disabled. vPingTask = executor.scheduleAtFixedRate(() -> { try { if (getPingIntervalMsec() <= 0) { ScheduledFuture<?> task = vPingTask; if (task != null) { task.cancel(false); vPingTask = null; } return; // Disabled. } for (Peer peer : getConnectedPeers()) { peer.sendPing(); } } catch (Throwable e) { log.error("Exception in ping loop", e); // The executor swallows exceptions :( } }, getPingIntervalMsec(), getPingIntervalMsec(), TimeUnit.MILLISECONDS); } private void setDownloadPeer(@Nullable Peer peer) { lock.lock(); try { if (downloadPeer == peer) return; if (downloadPeer != null) { log.info("Unsetting download peer: {}", downloadPeer); if (downloadListener != null) { removeDataEventListenerFromPeer(downloadPeer, downloadListener); } downloadPeer.setDownloadData(false); } downloadPeer = peer; if (downloadPeer != null) { log.info("Setting download peer: {}", downloadPeer); if (downloadListener != null) { addDataEventListenerToPeer(Threading.SAME_THREAD, peer, downloadListener); } downloadPeer.setDownloadData(true); if (chain != null) downloadPeer.setFastDownloadParameters(bloomFilterMerger.getLastFilter() != null, fastCatchupTime); } } finally { lock.unlock(); } } /** Use "Context.get().getConfidenceTable()" instead */ @Deprecated @Nullable public TxConfidenceTable getMemoryPool() { return Context.get().getConfidenceTable(); } /** * Tells the {@link PeerGroup} to download only block headers before a certain time and bodies after that. Call this * before starting block chain download. * Do not use a {@code time > NOW - 1} block, as it will break some block download logic. */ public void setFastCatchupTime(Instant fastCatchupTime) { lock.lock(); try { checkState(chain == null || !chain.shouldVerifyTransactions(), () -> "fast catchup is incompatible with fully verifying"); this.fastCatchupTime = fastCatchupTime; if (downloadPeer != null) { downloadPeer.setFastDownloadParameters(bloomFilterMerger.getLastFilter() != null, fastCatchupTime); } } finally { lock.unlock(); } } /** @deprecated use {@link #setFastCatchupTime(Instant)} */ @Deprecated public void setFastCatchupTimeSecs(long fastCatchupTimeSecs) { setFastCatchupTime(Instant.ofEpochSecond(fastCatchupTimeSecs)); } /** * Returns the current fast catchup time. The contents of blocks before this time won't be downloaded as they * cannot contain any interesting transactions. If you use {@link PeerGroup#addWallet(Wallet)} this just returns * the min of the wallets earliest key times. * @return a time in seconds since the epoch */ public Instant fastCatchupTime() { lock.lock(); try { return fastCatchupTime; } finally { lock.unlock(); } } /** @deprecated use {@link #fastCatchupTime()} */ @Deprecated public long getFastCatchupTimeSecs() { return fastCatchupTime().getEpochSecond(); } protected void handlePeerDeath(final Peer peer, @Nullable Throwable exception) { // Peer deaths can occur during startup if a connect attempt after peer discovery aborts immediately. if (!isRunning()) return; int numPeers; int numConnectedPeers = 0; lock.lock(); try { pendingPeers.remove(peer); peers.remove(peer); PeerAddress address = peer.getAddress(); log.info("{}: Peer died ({} connected, {} pending, {} max)", address, peers.size(), pendingPeers.size(), maxConnections); if (peer == downloadPeer) { log.info("Download peer died. Picking a new one."); setDownloadPeer(null); // Pick a new one and possibly tell it to download the chain. final Peer newDownloadPeer = selectDownloadPeer(peers); if (newDownloadPeer != null) { setDownloadPeer(newDownloadPeer); if (downloadListener != null) { startBlockChainDownloadFromPeer(newDownloadPeer); } } } numPeers = peers.size() + pendingPeers.size(); numConnectedPeers = peers.size(); groupBackoff.trackFailure(); if (exception instanceof NoRouteToHostException) { if (address.getAddr() instanceof Inet6Address && !ipv6Unreachable) { ipv6Unreachable = true; log.warn("IPv6 peer connect failed due to routing failure, ignoring IPv6 addresses from now on"); } } else { backoffMap.get(address).trackFailure(); // Put back on inactive list inactives.offer(address); } if (numPeers < getMaxConnections()) { triggerConnections(); } } finally { lock.unlock(); } peer.removeAddressEventListener(peerListener); peer.removeBlocksDownloadedEventListener(peerListener); peer.removeGetDataEventListener(peerListener); for (Wallet wallet : wallets) { peer.removeWallet(wallet); } final int fNumConnectedPeers = numConnectedPeers; for (ListenerRegistration<BlocksDownloadedEventListener> registration: peersBlocksDownloadedEventListeners) peer.removeBlocksDownloadedEventListener(registration.listener); for (ListenerRegistration<ChainDownloadStartedEventListener> registration: peersChainDownloadStartedEventListeners) peer.removeChainDownloadStartedEventListener(registration.listener); for (ListenerRegistration<GetDataEventListener> registration: peerGetDataEventListeners) peer.removeGetDataEventListener(registration.listener); for (ListenerRegistration<PreMessageReceivedEventListener> registration: peersPreMessageReceivedEventListeners) peer.removePreMessageReceivedEventListener(registration.listener); for (ListenerRegistration<OnTransactionBroadcastListener> registration : peersTransactionBroadastEventListeners) peer.removeOnTransactionBroadcastListener(registration.listener); for (final ListenerRegistration<PeerDisconnectedEventListener> registration : peerDisconnectedEventListeners) { registration.executor.execute(() -> registration.listener.onPeerDisconnected(peer, fNumConnectedPeers)); peer.removeDisconnectedEventListener(registration.listener); } } @GuardedBy("lock") private int stallPeriodSeconds = 10; @GuardedBy("lock") private int stallMinSpeedBytesSec = Block.HEADER_SIZE * 10; /** * Configures the stall speed: the speed at which a peer is considered to be serving us the block chain * unacceptably slowly. Once a peer has served us data slower than the given data rate for the given * number of seconds, it is considered stalled and will be disconnected, forcing the chain download to continue * from a different peer. The defaults are chosen conservatively, but if you are running on a platform that is * CPU constrained or on a very slow network e.g. EDGE, the default settings may need adjustment to * avoid false stalls. * * @param periodSecs How many seconds the download speed must be below blocksPerSec, defaults to 10. * @param bytesPerSecond Download speed (only blocks/txns count) must be consistently below this for a stall, defaults to the bandwidth required for 10 block headers per second. */ public void setStallThreshold(int periodSecs, int bytesPerSecond) { lock.lock(); try { stallPeriodSeconds = periodSecs; stallMinSpeedBytesSec = bytesPerSecond; } finally { lock.unlock(); } } private class ChainDownloadSpeedCalculator implements BlocksDownloadedEventListener, Runnable { private int blocksInLastSecond, txnsInLastSecond, origTxnsInLastSecond; private long bytesInLastSecond; // If we take more stalls than this, we assume we're on some kind of terminally slow network and the // stall threshold just isn't set properly. We give up on stall disconnects after that. private int maxStalls = 3; // How many seconds the peer has until we start measuring its speed. private int warmupSeconds = -1; // Used to calculate a moving average. private long[] samples; private int cursor; private boolean syncDone; private final Logger log = LoggerFactory.getLogger(ChainDownloadSpeedCalculator.class); @Override public synchronized void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) { blocksInLastSecond++; bytesInLastSecond += Block.HEADER_SIZE; List<Transaction> blockTransactions = block.getTransactions(); // This whole area of the type hierarchy is a mess. int txCount = (blockTransactions != null ? countAndMeasureSize(blockTransactions) : 0) + (filteredBlock != null ? countAndMeasureSize(filteredBlock.getAssociatedTransactions().values()) : 0); txnsInLastSecond = txnsInLastSecond + txCount; if (filteredBlock != null) origTxnsInLastSecond += filteredBlock.getTransactionCount(); } private int countAndMeasureSize(Collection<Transaction> transactions) { for (Transaction transaction : transactions) bytesInLastSecond += transaction.messageSize(); return transactions.size(); } @Override public void run() { try { calculate(); } catch (Throwable e) { log.error("Error in speed calculator", e); } } private void calculate() { int minSpeedBytesPerSec; int period; lock.lock(); try { minSpeedBytesPerSec = stallMinSpeedBytesSec; period = stallPeriodSeconds; } finally { lock.unlock(); } synchronized (this) { if (samples == null || samples.length != period) { samples = new long[period]; // *2 because otherwise a single low sample could cause an immediate disconnect which is too harsh. Arrays.fill(samples, minSpeedBytesPerSec * 2); warmupSeconds = 15; } int chainHeight = chain != null ? chain.getBestChainHeight() : -1; int mostCommonChainHeight = getMostCommonChainHeight(); if (!syncDone && mostCommonChainHeight > 0 && chainHeight >= mostCommonChainHeight) { log.info("End of sync detected at height {}.", chainHeight); syncDone = true; } if (!syncDone) { // Calculate the moving average. samples[cursor++] = bytesInLastSecond; if (cursor == samples.length) cursor = 0; long sampleSum = 0; for (long sample : samples) sampleSum += sample; final float average = (float) sampleSum / samples.length; String statsString = String.format(Locale.US, "%d blocks/sec, %d tx/sec, %d pre-filtered tx/sec, avg/last %.2f/%.2f kilobytes per sec, chain/common height %d/%d", blocksInLastSecond, txnsInLastSecond, origTxnsInLastSecond, average / 1024.0, bytesInLastSecond / 1024.0, chainHeight, mostCommonChainHeight); String thresholdString = String.format(Locale.US, "(threshold <%.2f KB/sec for %d seconds)", minSpeedBytesPerSec / 1024.0, samples.length); if (maxStalls <= 0) { log.info(statsString + ", stall disabled " + thresholdString); } else if (warmupSeconds > 0) { warmupSeconds--; if (bytesInLastSecond > 0) log.info(statsString + String.format(Locale.US, " (warming up %d more seconds)", warmupSeconds)); } else if (average < minSpeedBytesPerSec) { log.info(statsString + ", STALLED " + thresholdString); maxStalls--; if (maxStalls == 0) { // We could consider starting to drop the Bloom filtering FP rate at this point, because // we tried a bunch of peers and no matter what we don't seem to be able to go any faster. // This implies we're bandwidth bottlenecked and might want to start using bandwidth // more effectively. Of course if there's a MITM that is deliberately throttling us, // this is a good way to make us take away all the FPs from our Bloom filters ... but // as they don't give us a whole lot of privacy either way that's not inherently a big // deal. log.warn("This network seems to be slower than the requested stall threshold - won't do stall disconnects any more."); } else { Peer peer = getDownloadPeer(); log.warn(String.format(Locale.US, "Chain download stalled: received %.2f KB/sec for %d seconds, require average of %.2f KB/sec, disconnecting %s, %d stalls left", average / 1024.0, samples.length, minSpeedBytesPerSec / 1024.0, peer, maxStalls)); peer.close(); // Reset the sample buffer and give the next peer time to get going. samples = null; warmupSeconds = period; } } else { log.info(statsString + ", not stalled " + thresholdString); } } blocksInLastSecond = 0; txnsInLastSecond = 0; origTxnsInLastSecond = 0; bytesInLastSecond = 0; } } } @Nullable private ChainDownloadSpeedCalculator chainDownloadSpeedCalculator; @VisibleForTesting void startBlockChainDownloadFromPeer(Peer peer) { lock.lock(); try { setDownloadPeer(peer); if (chainDownloadSpeedCalculator == null) { // Every second, run the calculator which will log how fast we are downloading the chain. chainDownloadSpeedCalculator = new ChainDownloadSpeedCalculator(); executor.scheduleAtFixedRate(chainDownloadSpeedCalculator, 1, 1, TimeUnit.SECONDS); } peer.addBlocksDownloadedEventListener(Threading.SAME_THREAD, chainDownloadSpeedCalculator); // startBlockChainDownload will setDownloadData(true) on itself automatically. peer.startBlockChainDownload(); } finally { lock.unlock(); } } /** * Returns a future that is triggered when the number of connected peers is equal to the given number of * peers. By using this with {@link PeerGroup#getMaxConnections()} you can wait until the * network is fully online. To block immediately, just call get() on the result. Just calls * {@link #waitForPeersOfVersion(int, long)} with zero as the protocol version. * * @param numPeers How many peers to wait for. * @return a future that will be triggered when the number of connected peers is greater than or equals numPeers */ public ListenableCompletableFuture<List<Peer>> waitForPeers(final int numPeers) { return waitForPeersOfVersion(numPeers, 0); } /** * Returns a future that is triggered when there are at least the requested number of connected peers that support * the given protocol version or higher. To block immediately, just call get() on the result. * * @param numPeers How many peers to wait for. * @param protocolVersion The protocol version the awaited peers must implement (or better). * @return a future that will be triggered when the number of connected peers implementing protocolVersion or higher is greater than or equals numPeers */ public ListenableCompletableFuture<List<Peer>> waitForPeersOfVersion(final int numPeers, final long protocolVersion) { List<Peer> foundPeers = findPeersOfAtLeastVersion(protocolVersion); if (foundPeers.size() >= numPeers) { ListenableCompletableFuture<List<Peer>> f = new ListenableCompletableFuture<>(); f.complete(foundPeers); return f; } final ListenableCompletableFuture<List<Peer>> future = new ListenableCompletableFuture<List<Peer>>(); addConnectedEventListener(new PeerConnectedEventListener() { @Override public void onPeerConnected(Peer peer, int peerCount) { final List<Peer> peers = findPeersOfAtLeastVersion(protocolVersion); if (peers.size() >= numPeers) { future.complete(peers); removeConnectedEventListener(this); } } }); return future; } /** * Returns an array list of peers that implement the given protocol version or better. */ 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 a future that is triggered when there are at least the requested number of connected peers that support * the given protocol version or higher. To block immediately, just call get() on the result. * * @param numPeers How many peers to wait for. * @param mask An integer representing a bit mask that will be ANDed with the peers advertised service masks. * @return a future that will be triggered when the number of connected peers implementing protocolVersion or higher is greater than or equals numPeers */ public ListenableCompletableFuture<List<Peer>> waitForPeersWithServiceMask(final int numPeers, final int mask) { lock.lock(); try { List<Peer> foundPeers = findPeersWithServiceMask(mask); if (foundPeers.size() >= numPeers) { ListenableCompletableFuture<List<Peer>> f = new ListenableCompletableFuture<>(); f.complete(foundPeers); return f; } final ListenableCompletableFuture<List<Peer>> future = new ListenableCompletableFuture<>(); addConnectedEventListener(new PeerConnectedEventListener() { @Override public void onPeerConnected(Peer peer, int peerCount) { final List<Peer> peers = findPeersWithServiceMask(mask); if (peers.size() >= numPeers) { future.complete(peers); removeConnectedEventListener(this); } } }); return future; } finally { lock.unlock(); } } /** * Returns an array list of peers that match the requested service bit mask. */ public List<Peer> findPeersWithServiceMask(int mask) { lock.lock(); try { ArrayList<Peer> results = new ArrayList<>(peers.size()); for (Peer peer : peers) if (peer.getPeerVersionMessage().localServices.has(mask)) results.add(peer); return results; } finally { lock.unlock(); } } /** * Returns the number of connections that are required before transactions will be broadcast. If there aren't * enough, {@link PeerGroup#broadcastTransaction(Transaction)} will wait until the minimum number is reached so * propagation across the network can be observed. If no value has been set using * {@link PeerGroup#setMinBroadcastConnections(int)} a default of 80% of whatever * {@link PeerGroup#getMaxConnections()} returns is used. */ public int getMinBroadcastConnections() { lock.lock(); try { if (minBroadcastConnections == 0) { int max = getMaxConnections(); if (max <= 1) return max; else return (int) Math.round(getMaxConnections() * 0.8); } return minBroadcastConnections; } finally { lock.unlock(); } } /** * See {@link PeerGroup#getMinBroadcastConnections()}. */ public void setMinBroadcastConnections(int value) { lock.lock(); try { minBroadcastConnections = value; } finally { lock.unlock(); } } /** * Calls {@link PeerGroup#broadcastTransaction(Transaction, int, boolean)} with getMinBroadcastConnections() as * the number of connections to wait for before commencing broadcast. Also, if the transaction has no broadcast * confirmations yet the peers will be dropped after the transaction has been sent. */ @Override public TransactionBroadcast broadcastTransaction(final Transaction tx) { return broadcastTransaction(tx, Math.max(1, getMinBroadcastConnections()), true); } /** * <p>Given a transaction, sends it un-announced to one peer and then waits for it to be received back from other * peers. Once all connected peers have announced the transaction, the future available via the * {@link TransactionBroadcast#awaitRelayed()} ()} method will be completed. If anything goes * wrong the exception will be thrown when get() is called, or you can receive it via a callback on the * {@link ListenableCompletableFuture}. This method returns immediately, so if you want it to block just call get() on the * result.</p> * * <p>Optionally, peers will be dropped after they have been used for broadcasting the transaction and they have * no broadcast confirmations yet.</p> * * <p>Note that if the PeerGroup is limited to only one connection (discovery is not activated) then the future * will complete as soon as the transaction was successfully written to that peer.</p> * * <p>The transaction won't be sent until there are at least minConnections active connections available. * A good choice for proportion would be between 0.5 and 0.8 but if you want faster transmission during initial * bringup of the peer group you can lower it.</p> * * <p>The returned {@link TransactionBroadcast} object can be used to get progress feedback, * which is calculated by watching the transaction propagate across the network and be announced by peers.</p> */ public TransactionBroadcast broadcastTransaction(final Transaction tx, final int minConnections, final boolean dropPeersAfterBroadcast) { // If we don't have a record of where this tx came from already, set it to be ourselves so Peer doesn't end up // redownloading it from the network redundantly. if (tx.getConfidence().getSource().equals(TransactionConfidence.Source.UNKNOWN)) { log.info("Transaction source unknown, setting to SELF: {}", tx.getTxId()); tx.getConfidence().setSource(TransactionConfidence.Source.SELF); } final TransactionBroadcast broadcast = new TransactionBroadcast(this, tx); broadcast.setMinConnections(minConnections); broadcast.setDropPeersAfterBroadcast(dropPeersAfterBroadcast && tx.getConfidence().numBroadcastPeers() == 0); // Send the TX to the wallet once we have a successful broadcast. broadcast.awaitRelayed().whenComplete((bcast, throwable) -> { if (bcast != null) { runningBroadcasts.remove(bcast); // OK, now tell the wallet about the transaction. If the wallet created the transaction then // it already knows and will ignore this. If it's a transaction we received from // somebody else via a side channel and are now broadcasting, this will put it into the // wallet now we know it's valid. for (Wallet wallet : wallets) { // Assumption here is there are no dependencies of the created transaction. // // We may end up with two threads trying to do this in parallel - the wallet will // ignore whichever one loses the race. try { wallet.receivePending(bcast.transaction(), null); } catch (VerificationException e) { throw new RuntimeException(e); // Cannot fail to verify a tx we created ourselves. } } } else { // This can happen if we get a reject message from a peer. runningBroadcasts.remove(bcast); } }); // Keep a reference to the TransactionBroadcast object. This is important because otherwise, the entire tree // of objects we just created would become garbage if the user doesn't hold on to the returned future, and // eventually be collected. This in turn could result in the transaction not being committed to the wallet // at all. runningBroadcasts.add(broadcast); broadcast.broadcastOnly(); return broadcast; } /** * Returns the period between pings for an individual peer. Setting this lower means more accurate and timely ping * times are available via {@link Peer#lastPingInterval()} but it increases load on the * remote node. It defaults to {@link PeerGroup#DEFAULT_PING_INTERVAL_MSEC}. */ public long getPingIntervalMsec() { lock.lock(); try { return pingIntervalMsec; } finally { lock.unlock(); } } /** * Sets the period between pings for an individual peer. Setting this lower means more accurate and timely ping * times are available via {@link Peer#lastPingInterval()} but it increases load on the * remote node. It defaults to {@link PeerGroup#DEFAULT_PING_INTERVAL_MSEC}. * Setting the value to be smaller or equals 0 disables pinging entirely, although you can still request one yourself * using {@link Peer#sendPing()}. */ public void setPingIntervalMsec(long pingIntervalMsec) { lock.lock(); try { this.pingIntervalMsec = pingIntervalMsec; ScheduledFuture<?> task = vPingTask; if (task != null) task.cancel(false); setupPinging(); } finally { lock.unlock(); } } /** * If a peer is connected to that claims to speak a protocol version lower than the given version, it will * be disconnected and another one will be tried instead. */ public void setMinRequiredProtocolVersion(int minRequiredProtocolVersion) { this.vMinRequiredProtocolVersion = minRequiredProtocolVersion; } /** The minimum protocol version required: defaults to the version required for Bloom filtering. */ public int getMinRequiredProtocolVersion() { return vMinRequiredProtocolVersion; } /** * Returns our peers most commonly reported chain height. * If the most common heights are tied, or no peers are connected, returns {@code 0}. */ public int getMostCommonChainHeight() { lock.lock(); try { return getMostCommonChainHeight(this.peers); } finally { lock.unlock(); } } /** * Returns most commonly reported chain height from the given list of {@link Peer}s. * If the most common heights are tied, or no peers are connected, returns {@code 0}. */ public static int getMostCommonChainHeight(final List<Peer> peers) { if (peers.isEmpty()) return 0; List<Integer> heights = new ArrayList<>(peers.size()); for (Peer peer : peers) heights.add((int) peer.getBestHeight()); return maxOfMostFreq(heights); } private static class Pair implements Comparable<Pair> { final int item; int count = 0; public Pair(int item) { this.item = item; } // note that in this implementation compareTo() is not consistent with equals() @Override public int compareTo(Pair o) { return -Integer.compare(count, o.count); } } static int maxOfMostFreq(List<Integer> items) { if (items.isEmpty()) return 0; // This would be much easier in a functional language (or in Java 8). items = Ordering.natural().reverse().sortedCopy(items); LinkedList<Pair> pairs = new LinkedList<>(); pairs.add(new Pair(items.get(0))); for (int item : items) { Pair pair = pairs.getLast(); if (pair.item != item) pairs.add((pair = new Pair(item))); pair.count++; } // pairs now contains a uniquified list of the sorted inputs, with counts for how often that item appeared. // Now sort by how frequently they occur, and pick the most frequent. If the first place is tied between two, // don't pick any. Collections.sort(pairs); final Pair firstPair = pairs.get(0); if (pairs.size() == 1) return firstPair.item; final Pair secondPair = pairs.get(1); if (firstPair.count > secondPair.count) return firstPair.item; checkState(firstPair.count == secondPair.count); return 0; } /** * Given a list of Peers, return a Peer to be used as the download peer. If you don't want PeerGroup to manage * download peer statuses for you, just override this and always return null. */ @Nullable protected Peer selectDownloadPeer(List<Peer> peers) { // Characteristics to select for in order of importance: // - Chain height is reasonable (majority of nodes) // - High enough protocol version for the features we want (but we'll settle for less) // - Randomly, to try and spread the load. if (peers.isEmpty()) return null; int mostCommonChainHeight = getMostCommonChainHeight(peers); // Make sure we don't select a peer if there is no consensus about block height. if (mostCommonChainHeight == 0) return null; // Only select peers that announce the minimum protocol and services and that we think is fully synchronized. List<Peer> candidates = new LinkedList<>(); int highestPriority = Integer.MIN_VALUE; final int MINIMUM_VERSION = ProtocolVersion.WITNESS_VERSION.intValue(); for (Peer peer : peers) { final VersionMessage versionMessage = peer.getPeerVersionMessage(); if (versionMessage.clientVersion < MINIMUM_VERSION) continue; if (!versionMessage.services().has(Services.NODE_NETWORK)) continue; if (!versionMessage.services().has(Services.NODE_WITNESS)) continue; final long peerHeight = peer.getBestHeight(); if (peerHeight < mostCommonChainHeight || peerHeight > mostCommonChainHeight + 1) continue; candidates.add(peer); highestPriority = Math.max(highestPriority, getPriority(peer.peerAddress)); } if (candidates.isEmpty()) return null; // If there is a difference in priority, consider only the highest. for (Iterator<Peer> i = candidates.iterator(); i.hasNext(); ) { Peer peer = i.next(); if (getPriority(peer.peerAddress) < highestPriority) i.remove(); } // Random poll. int index = (int) (Math.random() * candidates.size()); return candidates.get(index); } /** * Returns the currently selected download peer. Bear in mind that it may have changed as soon as this method * returns. Can return null if no peer was selected. */ public Peer getDownloadPeer() { lock.lock(); try { return downloadPeer; } finally { lock.unlock(); } } /** * Returns the maximum number of {@link Peer}s to discover. This maximum is checked after * each {@link PeerDiscovery} so this max number can be surpassed. * @return the maximum number of peers to discover */ public int getMaxPeersToDiscoverCount() { return vMaxPeersToDiscoverCount; } /** * Sets the maximum number of {@link Peer}s to discover. This maximum is checked after * each {@link PeerDiscovery} so this max number can be surpassed. * @param maxPeersToDiscoverCount the maximum number of peers to discover */ public void setMaxPeersToDiscoverCount(int maxPeersToDiscoverCount) { this.vMaxPeersToDiscoverCount = maxPeersToDiscoverCount; } /** See {@link #setUseLocalhostPeerWhenPossible(boolean)} */ public boolean getUseLocalhostPeerWhenPossible() { lock.lock(); try { return useLocalhostPeerWhenPossible; } finally { lock.unlock(); } } /** * When true (the default), PeerGroup will attempt to connect to a Bitcoin node running on localhost before * attempting to use the P2P network. If successful, only localhost will be used. This makes for a simple * and easy way for a user to upgrade a bitcoinj based app running in SPV mode to fully validating security. */ public void setUseLocalhostPeerWhenPossible(boolean useLocalhostPeerWhenPossible) { lock.lock(); try { this.useLocalhostPeerWhenPossible = useLocalhostPeerWhenPossible; } finally { lock.unlock(); } } public boolean isRunning() { return vRunning; } /** * Can be used to disable Bloom filtering entirely, even in SPV mode. You are very unlikely to need this, it is * an optimisation for rare cases when full validation is not required but it's still more efficient to download * full blocks than filtered blocks. */ public void setBloomFilteringEnabled(boolean bloomFilteringEnabled) { this.vBloomFilteringEnabled = bloomFilteringEnabled; } /** Returns whether the Bloom filtering protocol optimisation is in use: defaults to true. */ public boolean isBloomFilteringEnabled() { return vBloomFilteringEnabled; } }
117,323
46.212877
183
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/BlockChain.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.store.MemoryBlockStore; import org.bitcoinj.store.SPVBlockStore; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.WalletExtension; import java.io.File; import java.util.ArrayList; import java.util.List; import static org.bitcoinj.base.internal.Preconditions.checkArgument; // TODO: Rename this class to SPVBlockChain at some point. /** * A BlockChain implements the <i>simplified payment verification</i> mode of the Bitcoin protocol. It is the right * choice to use for programs that have limited resources as it won't verify transactions signatures or attempt to store * all of the block chain. Really, this class should be called SPVBlockChain but for backwards compatibility it is not. */ public class BlockChain extends AbstractBlockChain { /** Keeps a map of block hashes to StoredBlocks. */ protected final BlockStore blockStore; /** * <p>Constructs a BlockChain connected to the given wallet and store. To obtain a {@link Wallet} you can construct * one from scratch, or you can deserialize a saved wallet from disk using * {@link Wallet#loadFromFile(File, WalletExtension...)}</p> * * <p>For the store, you should use {@link SPVBlockStore} or you could also try a * {@link MemoryBlockStore} if you want to hold all headers in RAM and don't care about * disk serialization (this is rare).</p> */ public BlockChain(NetworkParameters params, Wallet wallet, BlockStore blockStore) throws BlockStoreException { this(params, new ArrayList<Wallet>(), blockStore); addWallet(wallet); } /** * Constructs a BlockChain that has no wallet at all. This is helpful when you don't actually care about sending * and receiving coins but rather, just want to explore the network data structures. */ public BlockChain(NetworkParameters params, BlockStore blockStore) throws BlockStoreException { this(params, new ArrayList<Wallet>(), blockStore); } /** * Constructs a BlockChain connected to the given list of listeners and a store. */ public BlockChain(NetworkParameters params, List<? extends Wallet> wallets, BlockStore blockStore) throws BlockStoreException { super(params, wallets, blockStore); this.blockStore = blockStore; } @Override protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block blockHeader, TransactionOutputChanges txOutChanges) throws BlockStoreException, VerificationException { StoredBlock newBlock = storedPrev.build(blockHeader); blockStore.put(newBlock); return newBlock; } @Override protected StoredBlock addToBlockStore(StoredBlock storedPrev, Block blockHeader) throws BlockStoreException, VerificationException { StoredBlock newBlock = storedPrev.build(blockHeader); blockStore.put(newBlock); return newBlock; } @Override protected void rollbackBlockStore(int height) throws BlockStoreException { lock.lock(); try { int currentHeight = getBestChainHeight(); checkArgument(height >= 0 && height <= currentHeight, () -> "bad height: " + height); if (height == currentHeight) return; // nothing to do // Look for the block we want to be the new chain head StoredBlock newChainHead = blockStore.getChainHead(); while (newChainHead.getHeight() > height) { newChainHead = newChainHead.getPrev(blockStore); if (newChainHead == null) throw new BlockStoreException("Unreachable height"); } // Modify store directly blockStore.put(newChainHead); this.setChainHead(newChainHead); } finally { lock.unlock(); } } @Override protected boolean shouldVerifyTransactions() { return false; } @Override protected TransactionOutputChanges connectTransactions(int height, Block block) { // Don't have to do anything as this is only called if(shouldVerifyTransactions()) throw new UnsupportedOperationException(); } @Override protected TransactionOutputChanges connectTransactions(StoredBlock newBlock) { // Don't have to do anything as this is only called if(shouldVerifyTransactions()) throw new UnsupportedOperationException(); } @Override protected void disconnectTransactions(StoredBlock block) { // Don't have to do anything as this is only called if(shouldVerifyTransactions()) throw new UnsupportedOperationException(); } @Override protected void doSetChainHead(StoredBlock chainHead) throws BlockStoreException { blockStore.setChainHead(chainHead); } @Override protected void notSettingChainHead() throws BlockStoreException { // We don't use DB transactions here, so we don't need to do anything } @Override protected StoredBlock getStoredBlockInCurrentScope(Sha256Hash hash) throws BlockStoreException { return blockStore.get(hash); } @Override public boolean add(FilteredBlock block) throws VerificationException, PrunedException { boolean success = super.add(block); if (success) { trackFilteredTransactions(block.getTransactionCount()); } return success; } }
6,255
37.146341
131
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/PeerFilterProvider.java
/* * Copyright 2013 Google Inc. * Copyright 2019 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import java.time.Instant; /** * An interface which provides the information required to properly filter data downloaded from Peers. Note that an * implementer is responsible for calling * {@link PeerGroup#recalculateFastCatchupAndFilter(PeerGroup.FilterRecalculateMode)} whenever a change occurs which * effects the data provided via this interface. */ public interface PeerFilterProvider { /** * Returns the earliest time for which full/bloom-filtered blocks must be downloaded. * Blocks with timestamps before this time will only have headers downloaded. {@link Instant#EPOCH} requires that all * blocks be downloaded, and thus this should default to {@link Instant#MAX}. */ Instant earliestKeyCreationTime(); /** @deprecated use {@link #earliestKeyCreationTime()} */ @Deprecated default long getEarliestKeyCreationTime() { Instant earliestKeyCreationTime = earliestKeyCreationTime(); return earliestKeyCreationTime.equals(Instant.MAX) ? Long.MAX_VALUE : earliestKeyCreationTime.getEpochSecond(); } /** * Called on all registered filter providers before {@link #getBloomFilterElementCount()} and * {@link #getBloomFilter(int, double, int)} are called. Once called, the provider should ensure that the items * it will want to insert into the filter don't change. The reason is that all providers will have their element * counts queried, and then a filter big enough for all of them will be specified. So the provider must use * consistent state. There is guaranteed to be a matching call to {@link #endBloomFilterCalculation()} that can * be used to e.g. unlock a lock. */ void beginBloomFilterCalculation(); /** * Gets the number of elements that will be added to a bloom filter returned by * {@link PeerFilterProvider#getBloomFilter(int, double, int)} */ int getBloomFilterElementCount(); /** * Gets a bloom filter that contains all the necessary elements for the listener to receive relevant transactions. * Default value should be an empty bloom filter with the given size, falsePositiveRate, and nTweak. */ BloomFilter getBloomFilter(int size, double falsePositiveRate, int nTweak); /** * See {@link #beginBloomFilterCalculation()}. */ void endBloomFilterCalculation(); }
3,017
42.114286
121
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/AbstractBlockChain.java
/* * Copyright 2012 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.listeners.NewBestBlockListener; import org.bitcoinj.core.listeners.ReorganizeListener; import org.bitcoinj.core.listeners.TransactionReceivedInBlockListener; import org.bitcoinj.script.ScriptException; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.store.SPVBlockStore; import org.bitcoinj.utils.ListenableCompletableFuture; import org.bitcoinj.utils.ListenerRegistration; import org.bitcoinj.utils.Threading; import org.bitcoinj.utils.VersionTally; import org.bitcoinj.wallet.Wallet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.math.BigInteger; import java.nio.ByteBuffer; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.concurrent.locks.ReentrantLock; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>An AbstractBlockChain holds a series of {@link Block} objects, links them together, and knows how to verify that * the chain follows the rules of the {@link NetworkParameters} for this chain.</p> * * <p>It can be connected to a {@link Wallet}, and also {@link TransactionReceivedInBlockListener}s that can receive transactions and * notifications of re-organizations.</p> * * <p>An AbstractBlockChain implementation must be connected to a {@link BlockStore} implementation. The chain object * by itself doesn't store any data, that's delegated to the store. Which store you use is a decision best made by * reading the getting started guide, but briefly, fully validating block chains need fully validating stores. In * the lightweight SPV mode, a {@link SPVBlockStore} is the right choice.</p> * * <p>This class implements an abstract class which makes it simple to create a BlockChain that does/doesn't do full * verification. It verifies headers and is implements most of what is required to implement SPV mode, but * also provides callback hooks which can be used to do full verification.</p> * * <p>There are two subclasses of AbstractBlockChain that are useful: {@link BlockChain}, which is the simplest * class and implements <i>simplified payment verification</i>. This is a lightweight and efficient mode that does * not verify the contents of blocks, just their headers. A {@link FullPrunedBlockChain} paired with a * {@link org.bitcoinj.store.MemoryFullPrunedBlockStore} implements full verification, which is equivalent to * Bitcoin Core. To learn more about the alternative security models, please consult the articles on the * website.</p> * * <b>Theory</b> * * <p>The 'chain' is actually a tree although in normal operation it operates mostly as a list of {@link Block}s. * When multiple new head blocks are found simultaneously, there are multiple stories of the economy competing to become * the one true consensus. This can happen naturally when two miners solve a block within a few seconds of each other, * or it can happen when the chain is under attack.</p> * * <p>A reference to the head block of the best known chain is stored. If you can reach the genesis block by repeatedly * walking through the prevBlock pointers, then we say this is a full chain. If you cannot reach the genesis block * we say it is an orphan chain. Orphan chains can occur when blocks are solved and received during the initial block * chain download, or if we connect to a peer that doesn't send us blocks in order.</p> * * <p>A reorganize occurs when the blocks that make up the best known chain change. Note that simply adding a * new block to the top of the best chain isn't a reorganize, but that a reorganize is always triggered by adding * a new block that connects to some other (non best head) block. By "best" we mean the chain representing the largest * amount of work done.</p> * * <p>Every so often the block chain passes a difficulty transition point. At that time, all the blocks in the last * 2016 blocks are examined and a new difficulty target is calculated from them.</p> */ public abstract class AbstractBlockChain { private static final Logger log = LoggerFactory.getLogger(AbstractBlockChain.class); /** synchronization lock */ protected final ReentrantLock lock = Threading.lock(AbstractBlockChain.class); /** Keeps a map of block hashes to StoredBlocks. */ private final BlockStore blockStore; /** * Tracks the top of the best known chain.<p> * * Following this one down to the genesis block produces the story of the economy from the creation of Bitcoin * until the present day. The chain head can change if a new set of blocks is received that results in a chain of * greater work than the one obtained by following this one down. In that case a reorganize is triggered, * potentially invalidating transactions in our wallet. */ protected StoredBlock chainHead; // TODO: Scrap this and use a proper read/write for all of the block chain objects. // The chainHead field is read/written synchronized with this object rather than BlockChain. However writing is // also guaranteed to happen whilst BlockChain is synchronized (see setChainHead). The goal of this is to let // clients quickly access the chain head even whilst the block chain is downloading and thus the BlockChain is // locked most of the time. private final Object chainHeadLock = new Object(); /** network parameters for this chain */ protected final NetworkParameters params; private final CopyOnWriteArrayList<ListenerRegistration<NewBestBlockListener>> newBestBlockListeners; private final CopyOnWriteArrayList<ListenerRegistration<ReorganizeListener>> reorganizeListeners; private final CopyOnWriteArrayList<ListenerRegistration<TransactionReceivedInBlockListener>> transactionReceivedListeners; // Holds a block header and, optionally, a list of tx hashes or block's transactions static class OrphanBlock { final Block block; final List<Sha256Hash> filteredTxHashes; final Map<Sha256Hash, Transaction> filteredTxn; OrphanBlock(Block block, @Nullable List<Sha256Hash> filteredTxHashes, @Nullable Map<Sha256Hash, Transaction> filteredTxn) { final boolean filtered = filteredTxHashes != null && filteredTxn != null; checkArgument((block.getTransactions() == null && filtered) || (block.getTransactions() != null && !filtered)); this.block = block; this.filteredTxHashes = filteredTxHashes; this.filteredTxn = filteredTxn; } } // Holds blocks that we have received but can't plug into the chain yet, eg because they were created whilst we // were downloading the block chain. private final LinkedHashMap<Sha256Hash, OrphanBlock> orphanBlocks = new LinkedHashMap<>(); /** False positive estimation uses a double exponential moving average. */ public static final double FP_ESTIMATOR_ALPHA = 0.0001; /** False positive estimation uses a double exponential moving average. */ public static final double FP_ESTIMATOR_BETA = 0.01; private double falsePositiveRate; private double falsePositiveTrend; private double previousFalsePositiveRate; private final VersionTally versionTally; /** * Constructs a BlockChain connected to the given list of listeners (wallets) and a store. * @param params network parameters for this chain * @param wallets list of listeners (wallets) * @param blockStore where to store blocks * @throws BlockStoreException if a failure occurs while storing a block */ public AbstractBlockChain(NetworkParameters params, List<? extends Wallet> wallets, BlockStore blockStore) throws BlockStoreException { this.blockStore = blockStore; chainHead = blockStore.getChainHead(); log.info("chain head is at height {}:\n{}", chainHead.getHeight(), chainHead.getHeader()); this.params = params; this.newBestBlockListeners = new CopyOnWriteArrayList<>(); this.reorganizeListeners = new CopyOnWriteArrayList<>(); this.transactionReceivedListeners = new CopyOnWriteArrayList<>(); for (NewBestBlockListener l : wallets) addNewBestBlockListener(Threading.SAME_THREAD, l); for (ReorganizeListener l : wallets) addReorganizeListener(Threading.SAME_THREAD, l); for (TransactionReceivedInBlockListener l : wallets) addTransactionReceivedListener(Threading.SAME_THREAD, l); this.versionTally = new VersionTally(params); this.versionTally.initialize(blockStore, chainHead); } /** * Add a wallet to the BlockChain. Note that the wallet will be unaffected by any blocks received while it * was not part of this BlockChain. This method is useful if the wallet has just been created, and its keys * have never been in use, or if the wallet has been loaded along with the BlockChain. Note that adding multiple * wallets is not well tested! * @param wallet wallet to add */ public final void addWallet(Wallet wallet) { addNewBestBlockListener(Threading.SAME_THREAD, wallet); addReorganizeListener(Threading.SAME_THREAD, wallet); addTransactionReceivedListener(Threading.SAME_THREAD, wallet); int walletHeight = wallet.getLastBlockSeenHeight(); int chainHeight = getBestChainHeight(); if (walletHeight != chainHeight && walletHeight > 0) { log.warn("Wallet/chain height mismatch: {} vs {}", walletHeight, chainHeight); log.warn("Hashes: {} vs {}", wallet.getLastBlockSeenHash(), getChainHead().getHeader().getHash()); // This special case happens when the VM crashes because of a transaction received. It causes the updated // block store to persist, but not the wallet. In order to fix the issue, we roll back the block store to // the wallet height to make it look like as if the block has never been received. if (walletHeight < chainHeight) { try { rollbackBlockStore(walletHeight); log.info("Rolled back block store to height {}.", walletHeight); } catch (BlockStoreException x) { log.warn("Rollback of block store failed, continuing with mismatched heights. This can happen due to a replay."); } } } } /** * Remove a wallet from the chain. * @param wallet wallet to remove */ public void removeWallet(Wallet wallet) { removeNewBestBlockListener(wallet); removeReorganizeListener(wallet); removeTransactionReceivedListener(wallet); } /** * Adds a {@link NewBestBlockListener} listener to the chain. * @param listener listener to add */ public void addNewBestBlockListener(NewBestBlockListener listener) { addNewBestBlockListener(Threading.USER_THREAD, listener); } /** * Adds a {@link NewBestBlockListener} listener to the chain. * @param executor executor to listen on * @param listener listener to add */ public final void addNewBestBlockListener(Executor executor, NewBestBlockListener listener) { newBestBlockListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Adds a generic {@link ReorganizeListener} listener to the chain. * @param listener listener to add */ public void addReorganizeListener(ReorganizeListener listener) { addReorganizeListener(Threading.USER_THREAD, listener); } /** * Adds a generic {@link ReorganizeListener} listener to the chain. * @param executor executor to listen on * @param listener listener to add */ public final void addReorganizeListener(Executor executor, ReorganizeListener listener) { reorganizeListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Adds a generic {@link TransactionReceivedInBlockListener} listener to the chain. * @param listener listener to add */ public void addTransactionReceivedListener(TransactionReceivedInBlockListener listener) { addTransactionReceivedListener(Threading.USER_THREAD, listener); } /** * Adds a generic {@link TransactionReceivedInBlockListener} listener to the chain. * @param executor executor to listen on * @param listener listener to add */ public final void addTransactionReceivedListener(Executor executor, TransactionReceivedInBlockListener listener) { transactionReceivedListeners.add(new ListenerRegistration<>(listener, executor)); } /** * Removes the given {@link NewBestBlockListener} from the chain. * @param listener listener to remove */ public void removeNewBestBlockListener(NewBestBlockListener listener) { ListenerRegistration.removeFromList(listener, newBestBlockListeners); } /** * Removes the given {@link ReorganizeListener} from the chain. * @param listener listener to remove */ public void removeReorganizeListener(ReorganizeListener listener) { ListenerRegistration.removeFromList(listener, reorganizeListeners); } /** * Removes the given {@link TransactionReceivedInBlockListener} from the chain. * @param listener listener to remove */ public void removeTransactionReceivedListener(TransactionReceivedInBlockListener listener) { ListenerRegistration.removeFromList(listener, transactionReceivedListeners); } /** * Returns the {@link BlockStore} the chain was constructed with. You can use this to iterate over the chain. * @return the {@code BlockStore} the chain was constructed with */ public BlockStore getBlockStore() { return blockStore; } /** * Adds/updates the given {@link Block} with the block store. * This version is used when the transactions have not been verified. * @param storedPrev The {@link StoredBlock} which immediately precedes block. * @param block The {@link Block} to add/update. * @return the newly created {@link StoredBlock} * @throws BlockStoreException if a failure occurs while storing a block * @throws VerificationException if the block is invalid */ protected abstract StoredBlock addToBlockStore(StoredBlock storedPrev, Block block) throws BlockStoreException, VerificationException; /** * Adds/updates the given {@link StoredBlock} with the block store. * This version is used when the transactions have already been verified to properly spend txOutputChanges. * @param storedPrev The {@link StoredBlock} which immediately precedes block. * @param header The {@link StoredBlock} to add/update. * @param txOutputChanges The total sum of all changes made by this block to the set of open transaction outputs * (from a call to connectTransactions), if in fully verifying mode (null otherwise). * @return the newly created {@link StoredBlock} * @throws BlockStoreException if a failure occurs while storing a block * @throws VerificationException if the block is invalid */ protected abstract StoredBlock addToBlockStore(StoredBlock storedPrev, Block header, @Nullable TransactionOutputChanges txOutputChanges) throws BlockStoreException, VerificationException; /** * Rollback the block store to a given height. This is currently only supported by {@link BlockChain} instances. * * @param height height to roll back to * @throws BlockStoreException if the operation fails or is unsupported. */ protected abstract void rollbackBlockStore(int height) throws BlockStoreException; /** * Called before setting chain head in memory. * Should write the new head to block store and then commit any database transactions * that were started by disconnectTransactions/connectTransactions. * @param chainHead chain head to set * @throws BlockStoreException if a failure occurs while storing a block */ protected abstract void doSetChainHead(StoredBlock chainHead) throws BlockStoreException; /** * Called if we (possibly) previously called disconnectTransaction/connectTransactions, * but will not be calling preSetChainHead as a block failed verification. * Can be used to abort database transactions that were started by * disconnectTransactions/connectTransactions. * @throws BlockStoreException if a failure occurs while storing a block */ protected abstract void notSettingChainHead() throws BlockStoreException; /** * For a standard BlockChain, this should return blockStore.get(hash), * for a FullPrunedBlockChain blockStore.getOnceUndoableStoredBlock(hash) * @param hash hash of block to fetch * @return block with matching hash * @throws BlockStoreException if a failure occurs while storing a block */ protected abstract StoredBlock getStoredBlockInCurrentScope(Sha256Hash hash) throws BlockStoreException; /** * Processes a received block and tries to add it to the chain. If there's something wrong with the block an * exception is thrown. If the block is OK but cannot be connected to the chain at this time, returns false. * If the block can be connected to the chain, returns true. * Accessing block's transactions in another thread while this method runs may result in undefined behavior. * @param block block to add * @return true if block can be connected, false if block is valid but can't be connected * @throws VerificationException block is invalid or contains invalid transactions * @throws PrunedException a reorg that is too-long for our stored block data has occurred */ public boolean add(Block block) throws VerificationException, PrunedException { try { return add(block, true, null, null); } catch (BlockStoreException e) { // TODO: Figure out a better way to propagate this exception to the user. throw new RuntimeException(e); } catch (VerificationException e) { try { notSettingChainHead(); } catch (BlockStoreException e1) { throw new RuntimeException(e1); } throw new VerificationException("Could not verify block:\n" + block.toString(), e); } } /** * Processes a received block and tries to add it to the chain. If there's something wrong with the block an * exception is thrown. If the block is OK but cannot be connected to the chain at this time, returns false. * If the block can be connected to the chain, returns true. * @param block received block * @return true if block can be connected, false if block is valid but can't be connected * @throws VerificationException if invalid block * @throws PrunedException a reorg that is too-long for our stored block data has occurred */ public boolean add(FilteredBlock block) throws VerificationException, PrunedException { try { // The block has a list of hashes of transactions that matched the Bloom filter, and a list of associated // Transaction objects. There may be fewer Transaction objects than hashes, this is expected. It can happen // in the case where we were already around to witness the initial broadcast, so we downloaded the // transaction and sent it to the wallet before this point (the wallet may have thrown it away if it was // a false positive, as expected in any Bloom filtering scheme). The filteredTxn list here will usually // only be full of data when we are catching up to the head of the chain and thus haven't witnessed any // of the transactions. return add(block.getBlockHeader(), true, block.getTransactionHashes(), block.getAssociatedTransactions()); } catch (BlockStoreException e) { // TODO: Figure out a better way to propagate this exception to the user. throw new RuntimeException(e); } catch (VerificationException e) { try { notSettingChainHead(); } catch (BlockStoreException e1) { throw new RuntimeException(e1); } throw new VerificationException("Could not verify block " + block.getHash().toString() + "\n" + block.toString(), e); } } /** * Whether or not we are maintaining a set of unspent outputs and are verifying all transactions. * Also indicates that all calls to add() should provide a block containing transactions * @return true if we are verifying all transactions */ protected abstract boolean shouldVerifyTransactions(); /** * Connect each transaction in block.transactions, verifying them as we go and removing spent outputs * If an error is encountered in a transaction, no changes should be made to the underlying BlockStore. * and a VerificationException should be thrown. * Only called if(shouldVerifyTransactions()) * @param height block height to attach at * @param block block to connect * @return The full set of all changes made to the set of open transaction outputs. * @throws VerificationException if an attempt was made to spend an already-spent output, or if a transaction incorrectly solved an output script. * @throws BlockStoreException if the block store had an underlying error. */ protected abstract TransactionOutputChanges connectTransactions(int height, Block block) throws VerificationException, BlockStoreException; /** * Load newBlock from BlockStore and connect its transactions, returning changes to the set of unspent transactions. * If an error is encountered in a transaction, no changes should be made to the underlying BlockStore. * Only called if(shouldVerifyTransactions()) * @param newBlock block to load * @throws PrunedException if newBlock does not exist as a {@link StoredUndoableBlock} in the block store. * @throws VerificationException if an attempt was made to spend an already-spent output, or if a transaction incorrectly solved an output script. * @throws BlockStoreException if the block store had an underlying error or newBlock does not exist in the block store at all. * @return The full set of all changes made to the set of open transaction outputs. */ protected abstract TransactionOutputChanges connectTransactions(StoredBlock newBlock) throws VerificationException, BlockStoreException, PrunedException; // filteredTxHashList contains all transactions, filteredTxn just a subset private boolean add(Block block, boolean tryConnecting, @Nullable List<Sha256Hash> filteredTxHashList, @Nullable Map<Sha256Hash, Transaction> filteredTxn) throws BlockStoreException, VerificationException, PrunedException { // TODO: Use read/write locks to ensure that during chain download properties are still low latency. lock.lock(); try { // Quick check for duplicates to avoid an expensive check further down (in findSplit). This can happen a lot // when connecting orphan transactions due to the dumb brute force algorithm we use. if (block.equals(getChainHead().getHeader())) { return true; } if (tryConnecting && orphanBlocks.containsKey(block.getHash())) { return false; } BigInteger target = block.getDifficultyTargetAsInteger(); if (target.signum() <= 0 || target.compareTo(params.maxTarget) > 0) throw new VerificationException("Difficulty target is out of range: " + target.toString()); // If we want to verify transactions (ie we are running with full blocks), verify that block has transactions if (shouldVerifyTransactions() && block.getTransactions() == null) throw new VerificationException("Got a block header while running in full-block mode"); // Check for already-seen block, but only for full pruned mode, where the DB is // more likely able to handle these queries quickly. if (shouldVerifyTransactions() && blockStore.get(block.getHash()) != null) { return true; } final StoredBlock storedPrev; final int height; final EnumSet<Block.VerifyFlag> flags; // Prove the block is internally valid: hash is lower than target, etc. This only checks the block contents // if there is a tx sending or receiving coins using an address in one of our wallets. And those transactions // are only lightly verified: presence in a valid connecting block is taken as proof of validity. See the // article here for more details: https://bitcoinj.github.io/security-model try { Block.verifyHeader(block); storedPrev = getStoredBlockInCurrentScope(block.getPrevBlockHash()); if (storedPrev != null) { height = storedPrev.getHeight() + 1; } else { height = Block.BLOCK_HEIGHT_UNKNOWN; } flags = params.getBlockVerificationFlags(block, versionTally, height); if (shouldVerifyTransactions()) Block.verifyTransactions(params, block, height, flags); } catch (VerificationException e) { log.error("Failed to verify block: ", e); log.error(block.getHashAsString()); throw e; } // Try linking it to a place in the currently known blocks. if (storedPrev == null) { // We can't find the previous block. Probably we are still in the process of downloading the chain and a // block was solved whilst we were doing it. We put it to one side and try to connect it later when we // have more blocks. checkState(tryConnecting, () -> "bug in tryConnectingOrphans"); log.warn("Block does not connect: {} prev {}", block.getHashAsString(), block.getPrevBlockHash()); orphanBlocks.put(block.getHash(), new OrphanBlock(block, filteredTxHashList, filteredTxn)); if (tryConnecting) tryConnectingOrphans(); return false; } else { checkState(lock.isHeldByCurrentThread()); // It connects to somewhere on the chain. Not necessarily the top of the best known chain. params.checkDifficultyTransitions(storedPrev, block, blockStore); connectBlock(block, storedPrev, shouldVerifyTransactions(), filteredTxHashList, filteredTxn); if (tryConnecting) tryConnectingOrphans(); return true; } } finally { lock.unlock(); } } /** * Returns the hashes of the currently stored orphan blocks and then deletes them from this objects storage. * Used by Peer when a filter exhaustion event has occurred and thus any orphan blocks that have been downloaded * might be inaccurate/incomplete. * @return hashes of deleted blocks */ public Set<Sha256Hash> drainOrphanBlocks() { lock.lock(); try { Set<Sha256Hash> hashes = new HashSet<>(orphanBlocks.keySet()); orphanBlocks.clear(); return hashes; } finally { lock.unlock(); } } // expensiveChecks enables checks that require looking at blocks further back in the chain // than the previous one when connecting (eg median timestamp check) // It could be exposed, but for now we just set it to shouldVerifyTransactions() private void connectBlock(final Block block, StoredBlock storedPrev, boolean expensiveChecks, @Nullable final List<Sha256Hash> filteredTxHashList, @Nullable final Map<Sha256Hash, Transaction> filteredTxn) throws BlockStoreException, VerificationException, PrunedException { checkState(lock.isHeldByCurrentThread()); boolean filtered = filteredTxHashList != null && filteredTxn != null; // Check that we aren't connecting a block that fails a checkpoint check if (!params.passesCheckpoint(storedPrev.getHeight() + 1, block.getHash())) throw new VerificationException("Block failed checkpoint lockin at " + (storedPrev.getHeight() + 1)); if (shouldVerifyTransactions()) { for (Transaction tx : block.getTransactions()) if (!tx.isFinal(storedPrev.getHeight() + 1, block.getTimeSeconds())) throw new VerificationException("Block contains non-final transaction"); } StoredBlock head = getChainHead(); if (storedPrev.equals(head)) { if (filtered && filteredTxn.size() > 0) { log.debug("Block {} connects to top of best chain with {} transaction(s) of which we were sent {}", block.getHashAsString(), filteredTxHashList.size(), filteredTxn.size()); for (Sha256Hash hash : filteredTxHashList) log.debug(" matched tx {}", hash); } if (expensiveChecks && block.getTimeSeconds() <= getMedianTimestampOfRecentBlocks(head, blockStore)) throw new VerificationException("Block's timestamp is too early"); // BIP 66 & 65: Enforce block version 3/4 once they are a supermajority of blocks // NOTE: This requires 1,000 blocks since the last checkpoint (on main // net, less on test) in order to be applied. It is also limited to // stopping addition of new v2/3 blocks to the tip of the chain. if (block.getVersion() == Block.BLOCK_VERSION_BIP34 || block.getVersion() == Block.BLOCK_VERSION_BIP66) { final Integer count = versionTally.getCountAtOrAbove(block.getVersion() + 1); if (count != null && count >= params.getMajorityRejectBlockOutdated()) { throw new VerificationException.BlockVersionOutOfDate(block.getVersion()); } } // This block connects to the best known block, it is a normal continuation of the system. TransactionOutputChanges txOutChanges = null; if (shouldVerifyTransactions()) txOutChanges = connectTransactions(storedPrev.getHeight() + 1, block); StoredBlock newStoredBlock = addToBlockStore(storedPrev, block.getTransactions() == null ? block : block.cloneAsHeader(), txOutChanges); versionTally.add(block.getVersion()); setChainHead(newStoredBlock); if (log.isDebugEnabled()) log.debug("Chain is now {} blocks high, running listeners", newStoredBlock.getHeight()); informListenersForNewBlock(block, NewBlockType.BEST_CHAIN, filteredTxHashList, filteredTxn, newStoredBlock); } else { // This block connects to somewhere other than the top of the best known chain. We treat these differently. // // Note that we send the transactions to the wallet FIRST, even if we're about to re-organize this block // to become the new best chain head. This simplifies handling of the re-org in the Wallet class. StoredBlock newBlock = storedPrev.build(block); boolean haveNewBestChain = newBlock.moreWorkThan(head); if (haveNewBestChain) { log.info("Block is causing a re-organize"); } else { StoredBlock splitPoint = findSplit(newBlock, head, blockStore); if (splitPoint != null && splitPoint.equals(newBlock)) { // newStoredBlock is a part of the same chain, there's no fork. This happens when we receive a block // that we already saw and linked into the chain previously, which isn't the chain head. // Re-processing it is confusing for the wallet so just skip. log.warn("Saw duplicated block in best chain at height {}: {}", newBlock.getHeight(), newBlock.getHeader().getHash()); return; } if (splitPoint == null) { // This should absolutely never happen // (lets not write the full block to disk to keep any bugs which allow this to happen // from writing unreasonable amounts of data to disk) throw new VerificationException("Block forks the chain but splitPoint is null"); } else { // We aren't actually spending any transactions (yet) because we are on a fork addToBlockStore(storedPrev, block); int splitPointHeight = splitPoint.getHeight(); String splitPointHash = splitPoint.getHeader().getHashAsString(); log.info("Block forks the chain at height {}/block {}, but it did not cause a reorganize:\n{}", splitPointHeight, splitPointHash, newBlock.getHeader().getHashAsString()); } } // We may not have any transactions if we received only a header, which can happen during fast catchup. // If we do, send them to the wallet but state that they are on a side chain so it knows not to try and // spend them until they become activated. if (block.getTransactions() != null || filtered) { informListenersForNewBlock(block, NewBlockType.SIDE_CHAIN, filteredTxHashList, filteredTxn, newBlock); } if (haveNewBestChain) handleNewBestChain(storedPrev, newBlock, block, expensiveChecks); } } private void informListenersForNewBlock(final Block block, final NewBlockType newBlockType, @Nullable final List<Sha256Hash> filteredTxHashList, @Nullable final Map<Sha256Hash, Transaction> filteredTxn, final StoredBlock newStoredBlock) throws VerificationException { // Notify the listeners of the new block, so the depth and workDone of stored transactions can be updated // (in the case of the listener being a wallet). Wallets need to know how deep each transaction is so // coinbases aren't used before maturity. boolean first = true; Set<Sha256Hash> falsePositives = new HashSet<>(); if (filteredTxHashList != null) falsePositives.addAll(filteredTxHashList); for (final ListenerRegistration<TransactionReceivedInBlockListener> registration : transactionReceivedListeners) { if (registration.executor == Threading.SAME_THREAD) { informListenerForNewTransactions(block, newBlockType, filteredTxHashList, filteredTxn, newStoredBlock, first, registration.listener, falsePositives); } else { // Listener wants to be run on some other thread, so marshal it across here. final boolean notFirst = !first; registration.executor.execute(() -> { try { // We can't do false-positive handling when executing on another thread Set<Sha256Hash> ignoredFalsePositives = new HashSet<>(); informListenerForNewTransactions(block, newBlockType, filteredTxHashList, filteredTxn, newStoredBlock, notFirst, registration.listener, ignoredFalsePositives); } catch (VerificationException e) { log.error("Block chain listener threw exception: ", e); // Don't attempt to relay this back to the original peer thread if this was an async // listener invocation. // TODO: Make exception reporting a global feature and use it here. } }); } first = false; } for (final ListenerRegistration<NewBestBlockListener> registration : newBestBlockListeners) { if (registration.executor == Threading.SAME_THREAD) { if (newBlockType == NewBlockType.BEST_CHAIN) registration.listener.notifyNewBestBlock(newStoredBlock); } else { // Listener wants to be run on some other thread, so marshal it across here. registration.executor.execute(() -> { try { if (newBlockType == NewBlockType.BEST_CHAIN) registration.listener.notifyNewBestBlock(newStoredBlock); } catch (VerificationException e) { log.error("Block chain listener threw exception: ", e); // Don't attempt to relay this back to the original peer thread if this was an async // listener invocation. // TODO: Make exception reporting a global feature and use it here. } }); } first = false; } trackFalsePositives(falsePositives.size()); } private static void informListenerForNewTransactions(Block block, NewBlockType newBlockType, @Nullable List<Sha256Hash> filteredTxHashList, @Nullable Map<Sha256Hash, Transaction> filteredTxn, StoredBlock newStoredBlock, boolean first, TransactionReceivedInBlockListener listener, Set<Sha256Hash> falsePositives) throws VerificationException { if (block.getTransactions() != null) { // If this is not the first wallet, ask for the transactions to be duplicated before being given // to the wallet when relevant. This ensures that if we have two connected wallets and a tx that // is relevant to both of them, they don't end up accidentally sharing the same object (which can // result in temporary in-memory corruption during re-orgs). See bug 257. We only duplicate in // the case of multiple wallets to avoid an unnecessary efficiency hit in the common case. sendTransactionsToListener(newStoredBlock, newBlockType, listener, 0, block.getTransactions(), !first, falsePositives); } else if (filteredTxHashList != null) { Objects.requireNonNull(filteredTxn); // We must send transactions to listeners in the order they appeared in the block - thus we iterate over the // set of hashes and call sendTransactionsToListener with individual txn when they have not already been // seen in loose broadcasts - otherwise notifyTransactionIsInBlock on the hash. int relativityOffset = 0; for (Sha256Hash hash : filteredTxHashList) { Transaction tx = filteredTxn.get(hash); if (tx != null) { sendTransactionsToListener(newStoredBlock, newBlockType, listener, relativityOffset, Collections.singletonList(tx), !first, falsePositives); } else { if (listener.notifyTransactionIsInBlock(hash, newStoredBlock, newBlockType, relativityOffset)) { falsePositives.remove(hash); } } relativityOffset++; } } } /** * Gets the median timestamp of the last 11 blocks */ private static long getMedianTimestampOfRecentBlocks(StoredBlock storedBlock, BlockStore store) throws BlockStoreException { long[] timestamps = new long[11]; int unused = 9; timestamps[10] = storedBlock.getHeader().getTimeSeconds(); while (unused >= 0 && (storedBlock = storedBlock.getPrev(store)) != null) timestamps[unused--] = storedBlock.getHeader().getTimeSeconds(); Arrays.sort(timestamps, unused+1, 11); return timestamps[unused + (11-unused)/2]; } /** * Disconnect each transaction in the block (after reading it from the block store) * Only called if(shouldVerifyTransactions()) * @param block block to disconnect * @throws PrunedException if block does not exist as a {@link StoredUndoableBlock} in the block store. * @throws BlockStoreException if the block store had an underlying error or block does not exist in the block store at all. */ protected abstract void disconnectTransactions(StoredBlock block) throws PrunedException, BlockStoreException; /** * Called as part of connecting a block when the new block results in a different chain having higher total work. * * if (shouldVerifyTransactions) * Either newChainHead needs to be in the block store as a FullStoredBlock, or (block != null && block.transactions != null) */ private void handleNewBestChain(StoredBlock storedPrev, StoredBlock newChainHead, Block block, boolean expensiveChecks) throws BlockStoreException, VerificationException, PrunedException { checkState(lock.isHeldByCurrentThread()); // This chain has overtaken the one we currently believe is best. Reorganize is required. // // Firstly, calculate the block at which the chain diverged. We only need to examine the // chain from beyond this block to find differences. StoredBlock head = getChainHead(); final StoredBlock splitPoint = findSplit(newChainHead, head, blockStore); log.info("Re-organize after split at height {}", splitPoint.getHeight()); log.info("Old chain head: {}", head.getHeader().getHashAsString()); log.info("New chain head: {}", newChainHead.getHeader().getHashAsString()); log.info("Split at block: {}", splitPoint.getHeader().getHashAsString()); // Then build a list of all blocks in the old part of the chain and the new part. final LinkedList<StoredBlock> oldBlocks = getPartialChain(head, splitPoint, blockStore); final LinkedList<StoredBlock> newBlocks = getPartialChain(newChainHead, splitPoint, blockStore); // Disconnect each transaction in the previous best chain that is no longer in the new best chain StoredBlock storedNewHead = splitPoint; if (shouldVerifyTransactions()) { for (StoredBlock oldBlock : oldBlocks) { try { disconnectTransactions(oldBlock); } catch (PrunedException e) { // We threw away the data we need to re-org this deep! We need to go back to a peer with full // block contents and ask them for the relevant data then rebuild the indexs. Or we could just // give up and ask the human operator to help get us unstuck (eg, rescan from the genesis block). // TODO: Retry adding this block when we get a block with hash e.getHash() throw e; } } StoredBlock cursor; // Walk in ascending chronological order. for (Iterator<StoredBlock> it = newBlocks.descendingIterator(); it.hasNext();) { cursor = it.next(); Block cursorBlock = cursor.getHeader(); if (expensiveChecks && cursorBlock.getTimeSeconds() <= getMedianTimestampOfRecentBlocks(cursor.getPrev(blockStore), blockStore)) throw new VerificationException("Block's timestamp is too early during reorg"); TransactionOutputChanges txOutChanges; if (cursor != newChainHead || block == null) txOutChanges = connectTransactions(cursor); else txOutChanges = connectTransactions(newChainHead.getHeight(), block); storedNewHead = addToBlockStore(storedNewHead, cursorBlock.cloneAsHeader(), txOutChanges); } } else { // (Finally) write block to block store storedNewHead = addToBlockStore(storedPrev, newChainHead.getHeader()); } // Now inform the listeners. This is necessary so the set of currently active transactions (that we can spend) // can be updated to take into account the re-organize. We might also have received new coins we didn't have // before and our previous spends might have been undone. for (final ListenerRegistration<ReorganizeListener> registration : reorganizeListeners) { if (registration.executor == Threading.SAME_THREAD) { // Short circuit the executor so we can propagate any exceptions. // TODO: Do we really need to do this or should it be irrelevant? registration.listener.reorganize(splitPoint, oldBlocks, newBlocks); } else { registration.executor.execute(() -> { try { registration.listener.reorganize(splitPoint, oldBlocks, newBlocks); } catch (VerificationException e) { log.error("Block chain listener threw exception during reorg", e); } }); } } // Update the pointer to the best known block. setChainHead(storedNewHead); } /** * Returns the set of contiguous blocks between 'higher' and 'lower'. Higher is included, lower is not. */ private static LinkedList<StoredBlock> getPartialChain(StoredBlock higher, StoredBlock lower, BlockStore store) throws BlockStoreException { checkArgument(higher.getHeight() > lower.getHeight(), () -> "higher and lower are reversed"); LinkedList<StoredBlock> results = new LinkedList<>(); StoredBlock cursor = higher; do { results.add(cursor); cursor = Objects.requireNonNull(cursor.getPrev(store), "Ran off the end of the chain"); } while (!cursor.equals(lower)); return results; } /** * Locates the point in the chain at which newStoredBlock and chainHead diverge. Returns null if no split point was * found (ie they are not part of the same chain). Returns newChainHead or chainHead if they don't actually diverge * but are part of the same chain. */ private static StoredBlock findSplit(StoredBlock newChainHead, StoredBlock oldChainHead, BlockStore store) throws BlockStoreException { StoredBlock currentChainCursor = oldChainHead; StoredBlock newChainCursor = newChainHead; // Loop until we find the block both chains have in common. Example: // // A -> B -> C -> D // \--> E -> F -> G // // findSplit will return block B. oldChainHead = D and newChainHead = G. while (!currentChainCursor.equals(newChainCursor)) { if (currentChainCursor.getHeight() > newChainCursor.getHeight()) { currentChainCursor = currentChainCursor.getPrev(store); Objects.requireNonNull(currentChainCursor, "Attempt to follow an orphan chain"); } else { newChainCursor = newChainCursor.getPrev(store); Objects.requireNonNull(newChainCursor, "Attempt to follow an orphan chain"); } } return currentChainCursor; } /** * @return the height of the best known chain, convenience for {@code getChainHead().getHeight()}. */ public final int getBestChainHeight() { return getChainHead().getHeight(); } /** * Indicates whether new Block was on the best chain or not */ public enum NewBlockType { /** New block is on the best chain */ BEST_CHAIN, /** New block is on a side chain */ SIDE_CHAIN } private static void sendTransactionsToListener(StoredBlock block, NewBlockType blockType, TransactionReceivedInBlockListener listener, int relativityOffset, List<Transaction> transactions, boolean clone, Set<Sha256Hash> falsePositives) throws VerificationException { for (Transaction tx : transactions) { try { falsePositives.remove(tx.getTxId()); if (clone) tx = Transaction.read(ByteBuffer.wrap(tx.serialize())); listener.receiveFromBlock(tx, block, blockType, relativityOffset++); } catch (ScriptException e) { // We don't want scripts we don't understand to break the block chain so just note that this tx was // not scanned here and continue. log.warn("Failed to parse a script: " + e.toString()); } catch (ProtocolException e) { // Failed to duplicate tx, should never happen. throw new RuntimeException(e); } } } /** * @param chainHead chain head to set * @throws BlockStoreException if a failure occurs while storing a block */ protected void setChainHead(StoredBlock chainHead) throws BlockStoreException { doSetChainHead(chainHead); synchronized (chainHeadLock) { this.chainHead = chainHead; } } /** * For each block in orphanBlocks, see if we can now fit it on top of the chain and if so, do so. */ private void tryConnectingOrphans() throws VerificationException, BlockStoreException, PrunedException { checkState(lock.isHeldByCurrentThread()); // For each block in our orphan list, try and fit it onto the head of the chain. If we succeed remove it // from the list and keep going. If we changed the head of the list at the end of the round try again until // we can't fit anything else on the top. // // This algorithm is kind of crappy, we should do a topo-sort then just connect them in order, but for small // numbers of orphan blocks it does OK. int blocksConnectedThisRound; do { blocksConnectedThisRound = 0; Iterator<OrphanBlock> iter = orphanBlocks.values().iterator(); while (iter.hasNext()) { OrphanBlock orphanBlock = iter.next(); // Look up the blocks previous. StoredBlock prev = getStoredBlockInCurrentScope(orphanBlock.block.getPrevBlockHash()); if (prev == null) { // This is still an unconnected/orphan block. if (log.isDebugEnabled()) log.debug("Orphan block {} is not connectable right now", orphanBlock.block.getHash()); continue; } // Otherwise we can connect it now. // False here ensures we don't recurse infinitely downwards when connecting huge chains. log.info("Connected orphan {}", orphanBlock.block.getHash()); add(orphanBlock.block, false, orphanBlock.filteredTxHashes, orphanBlock.filteredTxn); iter.remove(); blocksConnectedThisRound++; } if (blocksConnectedThisRound > 0) { log.info("Connected {} orphan blocks.", blocksConnectedThisRound); } } while (blocksConnectedThisRound > 0); } /** * Returns the block at the head of the current best chain. This is the block which represents the greatest * amount of cumulative work done. * @return block at the head of the current best chain */ public StoredBlock getChainHead() { synchronized (chainHeadLock) { return chainHead; } } /** * An orphan block is one that does not connect to the chain anywhere (ie we can't find its parent, therefore * it's an orphan). Typically, this occurs when we are downloading the chain and didn't reach the head yet, and/or * if a block is solved whilst we are downloading. It's possible that we see a small amount of orphan blocks which * chain together, this method tries walking backwards through the known orphan blocks to find the bottom-most. * * @param from hash of block to walk backwards from * @return from or one of froms parents, or null if "from" does not identify an orphan block */ @Nullable public Block getOrphanRoot(Sha256Hash from) { lock.lock(); try { OrphanBlock cursor = orphanBlocks.get(from); if (cursor == null) return null; OrphanBlock tmp; while ((tmp = orphanBlocks.get(cursor.block.getPrevBlockHash())) != null) { cursor = tmp; } return cursor.block; } finally { lock.unlock(); } } /** * Returns true if the given block is currently in the orphan blocks list. * @param block block to check * @return true if block is an orphan */ public boolean isOrphan(Sha256Hash block) { lock.lock(); try { return orphanBlocks.containsKey(block); } finally { lock.unlock(); } } /** * Returns an estimate of when the given block will be reached, assuming a perfect 10 minute average for each * block. This is useful for turning transaction lock times into human-readable times. Note that a height in * the past will still be estimated, even though the time of solving is actually known (we won't scan backwards * through the chain to obtain the right answer). * @param height block time to estimate * @return estimated time block will be mined */ public Instant estimateBlockTimeInstant(int height) { synchronized (chainHeadLock) { long offset = height - chainHead.getHeight(); Instant headTime = chainHead.getHeader().time(); return headTime.plus(10 * offset, ChronoUnit.MINUTES); } } /** @deprecated use {@link #estimateBlockTimeInstant(int)} */ @Deprecated public Date estimateBlockTime(int height) { return Date.from(estimateBlockTimeInstant(height)); } /** * Returns a future that completes when the block chain has reached the given height. Yields the * {@link StoredBlock} of the block that reaches that height first. The future completes on a peer thread. * @param height desired height * @return future that will complete when height is reached */ public ListenableCompletableFuture<StoredBlock> getHeightFuture(final int height) { final ListenableCompletableFuture<StoredBlock> result = new ListenableCompletableFuture<>(); addNewBestBlockListener(Threading.SAME_THREAD, new NewBestBlockListener() { @Override public void notifyNewBestBlock(StoredBlock block) throws VerificationException { if (block.getHeight() >= height) { removeNewBestBlockListener(this); result.complete(block); } } }); return result; } /** * The false positive rate is the average over all blockchain transactions of: * * - 1.0 if the transaction was false-positive (was irrelevant to all listeners) * - 0.0 if the transaction was relevant or filtered out * * @return the false positive rate */ public double getFalsePositiveRate() { return falsePositiveRate; } /** * We completed handling of a filtered block. Update false-positive estimate based * on the total number of transactions in the original block. * * count includes filtered transactions, transactions that were passed in and were relevant * and transactions that were false positives (i.e. includes all transactions in the block). * @param count total number of transactions in original block */ protected void trackFilteredTransactions(int count) { // Track non-false-positives in batch. Each non-false-positive counts as // 0.0 towards the estimate. // // This is slightly off because we are applying false positive tracking before non-FP tracking, // which counts FP as if they came at the beginning of the block. Assuming uniform FP // spread in a block, this will somewhat underestimate the FP rate (5% for 1000 tx block). double alphaDecay = Math.pow(1 - FP_ESTIMATOR_ALPHA, count); // new_rate = alpha_decay * new_rate falsePositiveRate = alphaDecay * falsePositiveRate; double betaDecay = Math.pow(1 - FP_ESTIMATOR_BETA, count); // trend = beta * (new_rate - old_rate) + beta_decay * trend falsePositiveTrend = FP_ESTIMATOR_BETA * count * (falsePositiveRate - previousFalsePositiveRate) + betaDecay * falsePositiveTrend; // new_rate += alpha_decay * trend falsePositiveRate += alphaDecay * falsePositiveTrend; // Stash new_rate in old_rate previousFalsePositiveRate = falsePositiveRate; } /* Irrelevant transactions were received. Update false-positive estimate. */ void trackFalsePositives(int count) { // Track false positives in batch by adding alpha to the false positive estimate once per count. // Each false positive counts as 1.0 towards the estimate. falsePositiveRate += FP_ESTIMATOR_ALPHA * count; if (count > 0 && log.isDebugEnabled()) log.debug("{} false positives, current rate = {} trend = {}", count, falsePositiveRate, falsePositiveTrend); } /** Resets estimates of false positives. Used when the filter is sent to the peer. */ public void resetFalsePositiveEstimate() { falsePositiveRate = 0; falsePositiveTrend = 0; previousFalsePositiveRate = 0; } /** * @return version tally (not thread safe!) */ protected VersionTally getVersionTally() { return versionTally; } }
60,690
51.820714
161
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/BaseMessage.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; /** * A Message is a data structure that can be serialized/deserialized using the Bitcoin serialization format. * Specific types of messages that are used both in the blockchain, and on the wire, are derived from this * class. * <p> * Instances of this class are not safe for use by multiple threads. */ public abstract class BaseMessage implements Message { private static final Logger log = LoggerFactory.getLogger(BaseMessage.class); // These methods handle the serialization/deserialization using the custom Bitcoin protocol. /** * <p>Serialize this message to a byte array that conforms to the bitcoin wire protocol.</p> * * @return serialized data in Bitcoin protocol format */ @Override public final byte[] serialize() { // No cached array available so serialize parts by stream. ByteArrayOutputStream stream = new ByteArrayOutputStream(100); // initial size just a guess try { bitcoinSerializeToStream(stream); } catch (IOException e) { // Cannot happen, we are serializing to a memory stream. } return stream.toByteArray(); } /** * Serializes this message to the provided stream. If you just want the raw bytes use bitcoinSerialize(). */ protected abstract void bitcoinSerializeToStream(OutputStream stream) throws IOException; /** * Return the size of the serialized message. Note that if the message was deserialized from a payload, this * size can differ from the size of the original payload. * @return size of this object when serialized (in bytes) */ @Override public int messageSize() { return serialize().length; } }
2,517
34.971429
112
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/SendAddrV2Message.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; /** * <p>Represents the {@code sendaddrv2} P2P protocol message, which indicates that a node can understand and prefers * to receive {@code addrv2} messages instead of {@code addr} messages.</p> * * <p>See <a href="https://github.com/bitcoin/bips/blob/master/bip-0155.mediawiki">BIP155</a> for details.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class SendAddrV2Message extends EmptyMessage { public SendAddrV2Message() { super(); } }
1,147
34.875
116
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/ProtocolVersion.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; /** * Define important versions of the Bitcoin Protocol */ public enum ProtocolVersion { MINIMUM(70000), @Deprecated PONG(60001), BLOOM_FILTER(70001), // BIP37 BLOOM_FILTER_BIP111(70011), // BIP111 WITNESS_VERSION(70012), FEEFILTER(70013), // BIP133 CURRENT(70013); private final int bitcoinProtocol; ProtocolVersion(final int bitcoinProtocol) { this.bitcoinProtocol = bitcoinProtocol; } /** * @return protocol version as an integer value */ public int intValue() { return bitcoinProtocol; } /** * @deprecated Use {@link #intValue()} */ @Deprecated public int getBitcoinProtocolVersion() { return intValue(); } }
1,375
25.461538
75
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/TransactionOutPoint.java
/* * Copyright 2011 Google Inc. * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptError; import org.bitcoinj.script.ScriptException; import org.bitcoinj.script.ScriptPattern; import org.bitcoinj.wallet.KeyBag; import org.bitcoinj.wallet.RedeemData; import javax.annotation.Nullable; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.Objects; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>This message is a reference or pointer to an output of a different transaction.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class TransactionOutPoint { public static final int BYTES = 36; /** Special outpoint that normally marks a coinbase input. It's also used as a test dummy. */ public static final TransactionOutPoint UNCONNECTED = new TransactionOutPoint(ByteUtils.MAX_UNSIGNED_INTEGER, Sha256Hash.ZERO_HASH); /** Hash of the transaction to which we refer. */ private final Sha256Hash hash; /** Which output of that transaction we are talking about. */ private final long index; // This is not part of bitcoin serialization. It points to the connected transaction. final Transaction fromTx; // The connected output. final TransactionOutput connectedOutput; /** * Deserialize this transaction outpoint from a given payload. * * @param payload payload to deserialize from * @return read transaction outpoint * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static TransactionOutPoint read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { Sha256Hash hash = Sha256Hash.read(payload); long index = ByteUtils.readUint32(payload); return new TransactionOutPoint(index, hash); } public TransactionOutPoint(long index, Transaction fromTx) { this(fromTx.getTxId(), index, fromTx, null); } public TransactionOutPoint(long index, Sha256Hash hash) { this(hash, index, null, null); } public TransactionOutPoint(TransactionOutput connectedOutput) { this(connectedOutput.getParentTransactionHash(), connectedOutput.getIndex(), null, connectedOutput); } private TransactionOutPoint(Sha256Hash hash, long index, @Nullable Transaction fromTx, @Nullable TransactionOutput connectedOutput) { this.hash = Objects.requireNonNull(hash); checkArgument(index >= 0 && index <= ByteUtils.MAX_UNSIGNED_INTEGER, () -> "index out of range: " + index); this.index = index; this.fromTx = fromTx; this.connectedOutput = connectedOutput; } /** * Write this transaction outpoint into the given buffer. * * @param buf buffer to write into * @return the buffer * @throws BufferOverflowException if the outpoint doesn't fit the remaining buffer */ public ByteBuffer write(ByteBuffer buf) throws BufferOverflowException { buf.put(hash.serialize()); ByteUtils.writeInt32LE(index, buf); return buf; } /** * Allocates a byte array and writes this transaction outpoint into it. * * @return byte array containing the transaction outpoint */ public byte[] serialize() { return write(ByteBuffer.allocate(BYTES)).array(); } /** @deprecated use {@link #serialize()} */ @Deprecated public byte[] bitcoinSerialize() { return serialize(); } /** @deprecated use {@link #BYTES} */ @Deprecated public int getMessageSize() { return BYTES; } /** * 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. */ @Nullable public TransactionOutput getConnectedOutput() { if (fromTx != null) { return fromTx.getOutput(index); } else if (connectedOutput != null) { return connectedOutput; } return null; } /** * Returns the pubkey script from the connected output. * @throws java.lang.NullPointerException if there is no connected output. */ public byte[] getConnectedPubKeyScript() { byte[] result = Objects.requireNonNull(getConnectedOutput()).getScriptBytes(); checkState(result.length > 0); return result; } /** * Returns the ECKey identified in the connected output, for either P2PKH, P2WPKH or P2PK scripts. * For P2SH scripts you can use {@link #getConnectedRedeemData(KeyBag)} and then get the * key from RedeemData. * If the script form cannot be understood, throws ScriptException. * * @return an ECKey or null if the connected key cannot be found in the wallet. */ @Nullable public ECKey getConnectedKey(KeyBag keyBag) throws ScriptException { TransactionOutput connectedOutput = getConnectedOutput(); Objects.requireNonNull(connectedOutput, "Input is not connected so cannot retrieve key"); Script connectedScript = connectedOutput.getScriptPubKey(); if (ScriptPattern.isP2PKH(connectedScript)) { byte[] addressBytes = ScriptPattern.extractHashFromP2PKH(connectedScript); return keyBag.findKeyFromPubKeyHash(addressBytes, ScriptType.P2PKH); } else if (ScriptPattern.isP2WPKH(connectedScript)) { byte[] addressBytes = ScriptPattern.extractHashFromP2WH(connectedScript); return keyBag.findKeyFromPubKeyHash(addressBytes, ScriptType.P2WPKH); } else if (ScriptPattern.isP2PK(connectedScript)) { byte[] pubkeyBytes = ScriptPattern.extractKeyFromP2PK(connectedScript); return keyBag.findKeyFromPubKey(pubkeyBytes); } 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. */ @Nullable public RedeemData getConnectedRedeemData(KeyBag keyBag) throws ScriptException { TransactionOutput connectedOutput = getConnectedOutput(); Objects.requireNonNull(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, ScriptType.P2PKH), connectedScript); } else if (ScriptPattern.isP2WPKH(connectedScript)) { byte[] addressBytes = ScriptPattern.extractHashFromP2WH(connectedScript); return RedeemData.of(keyBag.findKeyFromPubKeyHash(addressBytes, 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 a copy of this outpoint, but with the connectedOutput removed. * @return outpoint with removed connectedOutput */ public TransactionOutPoint disconnectOutput() { return new TransactionOutPoint(hash, index, fromTx, null); } /** * Returns a copy of this outpoint, but with the provided transaction as fromTx. * @param transaction transaction to set as fromTx * @return outpoint with fromTx set */ public TransactionOutPoint connectTransaction(Transaction transaction) { return new TransactionOutPoint(hash, index, Objects.requireNonNull(transaction), connectedOutput); } /** * Returns a copy of this outpoint, but with fromTx removed. * @return outpoint with removed fromTx */ public TransactionOutPoint disconnectTransaction() { return new TransactionOutPoint(hash, index, null, connectedOutput); } @Override public String toString() { return hash + ":" + index; } /** * Returns the hash of the transaction this outpoint references/spends/is connected to. */ public Sha256Hash hash() { return hash; } /** * @return the index of this outpoint */ public long index() { return index; } /** * @deprecated Use {@link #hash()} */ @Deprecated public Sha256Hash getHash() { return hash(); } /** * @deprecated Use {@link #index()} */ @Deprecated public long getIndex() { return index(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TransactionOutPoint other = (TransactionOutPoint) o; return index == other.index && hash.equals(other.hash); } @Override public int hashCode() { return Objects.hash(index, hash); } }
10,828
36.863636
152
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/Block.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.annotations.VisibleForTesting; import org.bitcoinj.base.Address; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.Buffers; import org.bitcoinj.base.internal.Stopwatch; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.base.internal.InternalUtils; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.params.BitcoinNetworkParams; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.script.ScriptOpCodes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import static org.bitcoinj.base.Coin.FIFTY_COINS; import static org.bitcoinj.base.Sha256Hash.hashTwice; import static org.bitcoinj.base.internal.Preconditions.check; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>A block is a group of transactions, and is one of the fundamental data structures of the Bitcoin system. * It records a set of {@link Transaction}s together with some data that links it into a place in the global block * chain, and proves that a difficult calculation was done over its contents. See * <a href="http://www.bitcoin.org/bitcoin.pdf">the Bitcoin technical paper</a> for * more detail on blocks.</p> * * <p>To get a block, you can either build one from the raw bytes you can get from another implementation, or request one * specifically using {@link Peer#getBlock(Sha256Hash)}, or grab one from a downloaded {@link BlockChain}.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class Block extends BaseMessage { /** * Flags used to control which elements of block validation are done on * received blocks. */ public enum VerifyFlag { /** Check that block height is in coinbase transaction (BIP 34). */ HEIGHT_IN_COINBASE } private static final Logger log = LoggerFactory.getLogger(Block.class); /** How many bytes are required to represent a block header WITHOUT the trailing 00 length byte. */ public static final int HEADER_SIZE = 80; static final Duration ALLOWED_TIME_DRIFT = Duration.ofHours(2); // Same value as Bitcoin Core. /** * A constant shared by the entire network: how large in bytes a block is allowed to be. One day we may have to * upgrade everyone to change this, so Bitcoin can continue to grow. For now it exists as an anti-DoS measure to * avoid somebody creating a titanically huge but valid block and forcing everyone to download/store it forever. */ public static final int MAX_BLOCK_SIZE = 1_000_000; /** * A "sigop" is a signature verification operation. Because they're expensive we also impose a separate limit on * the number in a block to prevent somebody mining a huge block that has way more sigops than normal, so is very * expensive/slow to verify. */ public static final int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE / 50; /** Standard maximum value for difficultyTarget (nBits) (Bitcoin MainNet and TestNet) */ public static final long STANDARD_MAX_DIFFICULTY_TARGET = 0x1d00ffffL; /** A value for difficultyTarget (nBits) that allows (slightly less than) half of all possible hash solutions. Used in unit testing. */ public static final long EASIEST_DIFFICULTY_TARGET = 0x207fFFFFL; /** Value to use if the block height is unknown */ public static final int BLOCK_HEIGHT_UNKNOWN = -1; /** Height of the first block */ public static final int BLOCK_HEIGHT_GENESIS = 0; public static final long BLOCK_VERSION_GENESIS = 1; /** Block version introduced in BIP 34: Height in coinbase */ public static final long BLOCK_VERSION_BIP34 = 2; /** Block version introduced in BIP 66: Strict DER signatures */ public static final long BLOCK_VERSION_BIP66 = 3; /** Block version introduced in BIP 65: OP_CHECKLOCKTIMEVERIFY */ public static final long BLOCK_VERSION_BIP65 = 4; // Fields defined as part of the protocol format. private long version; private Sha256Hash prevBlockHash; private Sha256Hash merkleRoot, witnessRoot; private Instant time; private long difficultyTarget; // "nBits" private long nonce; // If null, it means this object holds only the headers. @VisibleForTesting @Nullable List<Transaction> transactions; /** Stores the hash of the block. If null, getHash() will recalculate it. */ private Sha256Hash hash; /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static Block read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { // header payload.mark(); long version = ByteUtils.readUint32(payload); Sha256Hash prevBlockHash = Sha256Hash.read(payload); Sha256Hash merkleRoot = Sha256Hash.read(payload); Instant time = Instant.ofEpochSecond(ByteUtils.readUint32(payload)); long difficultyTarget = ByteUtils.readUint32(payload); long nonce = ByteUtils.readUint32(payload); payload.reset(); // read again from the mark for the hash Sha256Hash hash = Sha256Hash.wrapReversed(Sha256Hash.hashTwice(Buffers.readBytes(payload, HEADER_SIZE))); // transactions List<Transaction> transactions = payload.hasRemaining() ? // otherwise this message is just a header readTransactions(payload) : null; Block block = new Block(version, prevBlockHash, merkleRoot, time, difficultyTarget, nonce, transactions); block.hash = hash; return block; } /** * Parse transactions from the block. */ private static List<Transaction> readTransactions(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { VarInt numTransactionsVarInt = VarInt.read(payload); check(numTransactionsVarInt.fitsInt(), BufferUnderflowException::new); int numTransactions = numTransactionsVarInt.intValue(); List<Transaction> transactions = new ArrayList<>(Math.min(numTransactions, Utils.MAX_INITIAL_ARRAY_LENGTH)); for (int i = 0; i < numTransactions; i++) { Transaction tx = Transaction.read(payload); // Label the transaction as coming from the P2P network, so code that cares where we first saw it knows. tx.getConfidence().setSource(TransactionConfidence.Source.NETWORK); transactions.add(tx); } return transactions; } /** Special case constructor, used for the genesis node, cloneAsHeader and unit tests. */ Block(long setVersion) { // Set up a few basic things. We are not complete after this though. version = setVersion; difficultyTarget = 0x1d07fff8L; time = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS); // convert to Bitcoin time prevBlockHash = Sha256Hash.ZERO_HASH; } /** * Construct a block initialized with all the given fields. * @param version This should usually be set to 1 or 2, depending on if the height is in the coinbase input. * @param prevBlockHash Reference to previous block in the chain or {@link Sha256Hash#ZERO_HASH} if genesis. * @param merkleRoot The root of the merkle tree formed by the transactions. * @param time time when the block was mined. * @param difficultyTarget Number which this block hashes lower than. * @param nonce Arbitrary number to make the block hash lower than the target. * @param transactions List of transactions including the coinbase. */ public Block(long version, Sha256Hash prevBlockHash, Sha256Hash merkleRoot, Instant time, long difficultyTarget, long nonce, List<Transaction> transactions) { super(); this.version = version; this.prevBlockHash = prevBlockHash; this.merkleRoot = merkleRoot; this.time = time; this.difficultyTarget = difficultyTarget; this.nonce = nonce; if (transactions != null) transactions = new LinkedList<>(transactions); this.transactions = transactions; } /** * Construct a block initialized with all the given fields. * @param version This should usually be set to 1 or 2, depending on if the height is in the coinbase input. * @param prevBlockHash Reference to previous block in the chain or {@link Sha256Hash#ZERO_HASH} if genesis. * @param merkleRoot The root of the merkle tree formed by the transactions. * @param time UNIX time seconds when the block was mined. * @param difficultyTarget Number which this block hashes lower than. * @param nonce Arbitrary number to make the block hash lower than the target. * @param transactions List of transactions including the coinbase. * @deprecated use {@link #Block(long, Sha256Hash, Sha256Hash, Instant, long, long, List)} */ @Deprecated public Block(long version, Sha256Hash prevBlockHash, Sha256Hash merkleRoot, long time, long difficultyTarget, long nonce, List<Transaction> transactions) { this(version, prevBlockHash, merkleRoot, Instant.ofEpochSecond(time), difficultyTarget, nonce, transactions); } public static Block createGenesis() { Block genesisBlock = new Block(BLOCK_VERSION_GENESIS); Transaction tx = Transaction.coinbase(genesisTxInputScriptBytes); tx.addOutput(new TransactionOutput(tx, FIFTY_COINS, genesisTxScriptPubKeyBytes)); genesisBlock.addTransaction(tx); return genesisBlock; } // A script containing the difficulty bits and the following message: // // "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks" private static final byte[] genesisTxInputScriptBytes = ByteUtils.parseHex ("04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73"); private static final byte[] genesisTxScriptPubKeyBytes; static { ByteArrayOutputStream scriptPubKeyBytes = new ByteArrayOutputStream(); try { Script.writeBytes(scriptPubKeyBytes, ByteUtils.parseHex ("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f")); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } scriptPubKeyBytes.write(ScriptOpCodes.OP_CHECKSIG); genesisTxScriptPubKeyBytes = scriptPubKeyBytes.toByteArray(); } @Override public int messageSize() { int size = HEADER_SIZE; List<Transaction> transactions = getTransactions(); if (transactions != null) { size += VarInt.sizeOf(transactions.size()); for (Transaction tx : transactions) { size += tx.messageSize(); } } return size; } // default for testing void writeHeader(OutputStream stream) throws IOException { ByteUtils.writeInt32LE(version, stream); stream.write(prevBlockHash.serialize()); stream.write(getMerkleRoot().serialize()); ByteUtils.writeInt32LE(time.getEpochSecond(), stream); ByteUtils.writeInt32LE(difficultyTarget, stream); ByteUtils.writeInt32LE(nonce, stream); } private void writeTransactions(OutputStream stream) throws IOException { // check for no transaction conditions first // must be a more efficient way to do this but I'm tired atm. if (transactions == null) { return; } stream.write(VarInt.of(transactions.size()).serialize()); for (Transaction tx : transactions) { tx.bitcoinSerializeToStream(stream); } } @Override protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { writeHeader(stream); writeTransactions(stream); } protected void unCache() { // Since we have alternate uncache methods to use internally this will only ever be called by a child // transaction so we only need to invalidate that part of the cache. unCacheTransactions(); } private void unCacheHeader() { hash = null; } private void unCacheTransactions() { // Current implementation has to uncache headers as well as any change to a tx will alter the merkle root. In // future we can go more granular and cache merkle root separately so rest of the header does not need to be // rewritten. unCacheHeader(); // Clear merkleRoot last as it may end up being parsed during unCacheHeader(). merkleRoot = null; } /** * Calculates the block hash by serializing the block and hashing the * resulting bytes. */ private Sha256Hash calculateHash() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(HEADER_SIZE); writeHeader(bos); return Sha256Hash.wrapReversed(Sha256Hash.hashTwice(bos.toByteArray())); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } /** * Returns the hash of the block (which for a valid, solved block should be below the target) in the form seen on * the block explorer. If you call this on block 1 in the mainnet chain * you will get "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048". */ public String getHashAsString() { return getHash().toString(); } /** * Returns the hash of the block (which for a valid, solved block should be * below the target). Big endian. */ public Sha256Hash getHash() { if (hash == null) hash = calculateHash(); return hash; } /** * The number that is one greater than the largest representable SHA-256 * hash. */ private static BigInteger LARGEST_HASH = BigInteger.ONE.shiftLeft(256); /** * Returns the work represented by this block.<p> * * Work is defined as the number of tries needed to solve a block in the * average case. Consider a difficulty target that covers 5% of all possible * hash values. Then the work of the block will be 20. As the target gets * lower, the amount of work goes up. */ public BigInteger getWork() throws VerificationException { BigInteger target = getDifficultyTargetAsInteger(); return LARGEST_HASH.divide(target.add(BigInteger.ONE)); } /** * Returns a copy of the block, but without any transactions. * @return new, header-only {@code Block} */ public Block cloneAsHeader() { Block block = new Block(version); block.difficultyTarget = difficultyTarget; block.time = time; block.nonce = nonce; block.prevBlockHash = prevBlockHash; block.merkleRoot = getMerkleRoot(); block.hash = getHash(); block.transactions = null; return block; } /** * Returns a multi-line string containing a description of the contents of * the block. Use for debugging purposes only. */ @Override public String toString() { StringBuilder s = new StringBuilder(); s.append(" block: \n"); s.append(" hash: ").append(getHashAsString()).append('\n'); s.append(" version: ").append(version); String bips = InternalUtils.commaJoin(isBIP34() ? "BIP34" : null, isBIP66() ? "BIP66" : null, isBIP65() ? "BIP65" : null); if (!bips.isEmpty()) s.append(" (").append(bips).append(')'); s.append('\n'); s.append(" previous block: ").append(getPrevBlockHash()).append("\n"); s.append(" time: ").append(time).append(" (").append(TimeUtils.dateTimeFormat(time)).append(")\n"); s.append(" difficulty target (nBits): ").append(difficultyTarget).append("\n"); s.append(" nonce: ").append(nonce).append("\n"); if (transactions != null && transactions.size() > 0) { s.append(" merkle root: ").append(getMerkleRoot()).append("\n"); s.append(" witness root: ").append(getWitnessRoot()).append("\n"); s.append(" with ").append(transactions.size()).append(" transaction(s):\n"); for (Transaction tx : transactions) { s.append(tx).append('\n'); } } return s.toString(); } /** * <p>Finds a value of nonce that makes the blocks hash lower than the difficulty target. This is called mining, but * solve() is far too slow to do real mining with. It exists only for unit testing purposes. * * <p>This can loop forever if a solution cannot be found solely by incrementing nonce. It doesn't change * extraNonce.</p> */ @VisibleForTesting public void solve() { Duration warningThreshold = Duration.ofSeconds(5); Stopwatch watch = Stopwatch.start(); while (true) { try { // Is our proof of work valid yet? if (checkProofOfWork(false)) return; // No, so increment the nonce and try again. setNonce(getNonce() + 1); if (watch.isRunning() && watch.elapsed().compareTo(warningThreshold) > 0) { watch.stop(); log.warn("trying to solve block for longer than {} seconds", warningThreshold.getSeconds()); } } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen. } } } /** * Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash. Inside a block the * target is represented using a compact form. * * @return difficulty target as 256-bit value */ public BigInteger getDifficultyTargetAsInteger() { return ByteUtils.decodeCompactBits(difficultyTarget); } /** Returns true if the hash of the block is OK (lower than difficulty target). */ protected boolean checkProofOfWork(boolean throwException) throws VerificationException { // shortcut for unit-testing if (Context.get().isRelaxProofOfWork()) return true; // This part is key - it is what proves the block was as difficult to make as it claims // to be. Note however that in the context of this function, the block can claim to be // as difficult as it wants to be .... if somebody was able to take control of our network // connection and fork us onto a different chain, they could send us valid blocks with // ridiculously easy difficulty and this function would accept them. // // To prevent this attack from being possible, elsewhere we check that the difficultyTarget // field is of the right value. This requires us to have the preceding blocks. BigInteger target = getDifficultyTargetAsInteger(); BigInteger h = getHash().toBigInteger(); if (h.compareTo(target) > 0) { // Proof of work check failed! if (throwException) throw new VerificationException("Hash is higher than target: " + getHashAsString() + " vs " + target.toString(16)); else return false; } return true; } private void checkTimestamp() throws VerificationException { final Instant allowedTime = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS).plus(ALLOWED_TIME_DRIFT); if (time.isAfter(allowedTime)) throw new VerificationException(String.format(Locale.US, "Block too far in future: %s (%d) vs allowed %s (%d)", TimeUtils.dateTimeFormat(time), time.toEpochMilli(), TimeUtils.dateTimeFormat(allowedTime), allowedTime.toEpochMilli())); } private void checkSigOps() throws VerificationException { // Check there aren't too many signature verifications in the block. This is an anti-DoS measure, see the // comments for MAX_BLOCK_SIGOPS. int sigOps = 0; for (Transaction tx : transactions) { sigOps += tx.getSigOpCount(); } if (sigOps > MAX_BLOCK_SIGOPS) throw new VerificationException("Block had too many Signature Operations"); } private void checkMerkleRoot() throws VerificationException { Sha256Hash calculatedRoot = calculateMerkleRoot(); if (!calculatedRoot.equals(merkleRoot)) { log.error("Merkle tree did not verify"); throw new VerificationException("Merkle hashes do not match: " + calculatedRoot + " vs " + merkleRoot); } } @VisibleForTesting void checkWitnessRoot() throws VerificationException { Transaction coinbase = transactions.get(0); checkState(coinbase.isCoinBase()); Sha256Hash witnessCommitment = coinbase.findWitnessCommitment(); if (witnessCommitment != null) { byte[] witnessReserved = null; TransactionWitness witness = coinbase.getInput(0).getWitness(); if (witness.getPushCount() != 1) throw new VerificationException("Coinbase witness reserved invalid: push count"); witnessReserved = witness.getPush(0); if (witnessReserved.length != 32) throw new VerificationException("Coinbase witness reserved invalid: length"); Sha256Hash witnessRootHash = Sha256Hash.twiceOf(getWitnessRoot().serialize(), witnessReserved); if (!witnessRootHash.equals(witnessCommitment)) throw new VerificationException("Witness merkle root invalid. Expected " + witnessCommitment.toString() + " but got " + witnessRootHash.toString()); } else { for (Transaction tx : transactions) { if (tx.hasWitnesses()) throw new VerificationException("Transaction witness found but no witness commitment present"); } } } private Sha256Hash calculateMerkleRoot() { List<Sha256Hash> tree = buildMerkleTree(false); return tree.get(tree.size() - 1); } private Sha256Hash calculateWitnessRoot() { List<Sha256Hash> tree = buildMerkleTree(true); return tree.get(tree.size() - 1); } private List<Sha256Hash> buildMerkleTree(boolean useWTxId) { // The Merkle root is based on a tree of hashes calculated from the transactions: // // root // / \ // A B // / \ / \ // t1 t2 t3 t4 // // The tree is represented as a list: t1,t2,t3,t4,A,B,root where each // entry is a hash. // // The hashing algorithm is double SHA-256. The leaves are a hash of the serialized contents of the transaction. // The interior nodes are hashes of the concatenation of the two child hashes. // // This structure allows the creation of proof that a transaction was included into a block without having to // provide the full block contents. Instead, you can provide only a Merkle branch. For example to prove tx2 was // in a block you can just provide tx2, the hash(tx1) and B. Now the other party has everything they need to // derive the root, which can be checked against the block header. These proofs aren't used right now but // will be helpful later when we want to download partial block contents. // // Note that if the number of transactions is not even the last tx is repeated to make it so (see // tx3 above). A tree with 5 transactions would look like this: // // root // / \ // 1 5 // / \ / \ // 2 3 4 4 // / \ / \ / \ // t1 t2 t3 t4 t5 t5 ArrayList<Sha256Hash> tree = new ArrayList<>(transactions.size()); // Start by adding all the hashes of the transactions as leaves of the tree. for (Transaction tx : transactions) { final Sha256Hash hash; if (useWTxId && tx.isCoinBase()) hash = Sha256Hash.ZERO_HASH; else hash = useWTxId ? tx.getWTxId() : tx.getTxId(); tree.add(hash); } int levelOffset = 0; // Offset in the list where the currently processed level starts. // Step through each level, stopping when we reach the root (levelSize == 1). for (int levelSize = transactions.size(); levelSize > 1; levelSize = (levelSize + 1) / 2) { // For each pair of nodes on that level: for (int left = 0; left < levelSize; left += 2) { // The right hand node can be the same as the left hand, in the case where we don't have enough // transactions. int right = Math.min(left + 1, levelSize - 1); Sha256Hash leftHash = tree.get(levelOffset + left); Sha256Hash rightHash = tree.get(levelOffset + right); tree.add(Sha256Hash.wrapReversed(hashTwice( leftHash.serialize(), rightHash.serialize()))); } // Move to the next level. levelOffset += levelSize; } return tree; } /** * Verify the transactions on a block. * * @param height block height, if known, or -1 otherwise. If provided, used * to validate the coinbase input script of v2 and above blocks. * @throws VerificationException if there was an error verifying the block. */ private void checkTransactions(final int height, final EnumSet<VerifyFlag> flags) throws VerificationException { // The first transaction in a block must always be a coinbase transaction. if (!transactions.get(0).isCoinBase()) throw new VerificationException("First tx is not coinbase"); if (flags.contains(Block.VerifyFlag.HEIGHT_IN_COINBASE) && height >= BLOCK_HEIGHT_GENESIS) { transactions.get(0).checkCoinBaseHeight(height); } // The rest must not be. for (int i = 1; i < transactions.size(); i++) { if (transactions.get(i).isCoinBase()) throw new VerificationException("TX " + i + " is coinbase when it should not be."); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return getHash().equals(((Block)o).getHash()); } @Override public int hashCode() { return getHash().hashCode(); } /** * Returns the merkle root in big endian form, calculating it from transactions if necessary. */ public Sha256Hash getMerkleRoot() { if (merkleRoot == null) { //TODO check if this is really necessary. unCacheHeader(); merkleRoot = calculateMerkleRoot(); } return merkleRoot; } /** Exists only for unit testing. */ @VisibleForTesting void setMerkleRoot(Sha256Hash value) { unCacheHeader(); merkleRoot = value; hash = null; } /** * Returns the witness root in big endian form, calculating it from transactions if necessary. */ public Sha256Hash getWitnessRoot() { if (witnessRoot == null) witnessRoot = calculateWitnessRoot(); return witnessRoot; } /** Adds a transaction to this block. The nonce and merkle root are invalid after this. */ public void addTransaction(Transaction t) { addTransaction(t, true); } /** Adds a transaction to this block, with or without checking the sanity of doing so */ void addTransaction(Transaction t, boolean runSanityChecks) { unCacheTransactions(); if (transactions == null) { transactions = new ArrayList<>(); } if (runSanityChecks && transactions.size() == 0 && !t.isCoinBase()) throw new RuntimeException("Attempted to add a non-coinbase transaction as the first transaction: " + t); else if (runSanityChecks && transactions.size() > 0 && t.isCoinBase()) throw new RuntimeException("Attempted to add a coinbase transaction when there already is one: " + t); transactions.add(t); // Force a recalculation next time the values are needed. merkleRoot = null; hash = null; } /** Returns the version of the block data structure as defined by the Bitcoin protocol. */ public long getVersion() { return version; } /** * Returns the hash of the previous block in the chain, as defined by the block header. */ public Sha256Hash getPrevBlockHash() { return prevBlockHash; } @VisibleForTesting void setPrevBlockHash(Sha256Hash prevBlockHash) { unCacheHeader(); this.prevBlockHash = prevBlockHash; this.hash = null; } /** * Returns the time at which the block was solved and broadcast, according to the clock of the solving node. */ public Instant time() { return time; } /** * Returns the time at which the block was solved and broadcast, according to the clock of the solving node. This * is measured in seconds since the UNIX epoch (midnight Jan 1st 1970). * @deprecated use {@link #time()} */ @Deprecated public long getTimeSeconds() { return time.getEpochSecond(); } /** * Returns the time at which the block was solved and broadcast, according to the clock of the solving node. * @deprecated use {@link #time()} */ @Deprecated public Date getTime() { return Date.from(time()); } @VisibleForTesting public void setTime(Instant time) { unCacheHeader(); this.time = time.truncatedTo(ChronoUnit.SECONDS); // convert to Bitcoin time this.hash = null; } /** * Returns the difficulty of the proof of work that this block should meet encoded <b>in compact form</b>. The {@link * BlockChain} verifies that this is not too easy by looking at the length of the chain when the block is added. * To find the actual value the hash should be compared against, use * {@link Block#getDifficultyTargetAsInteger()}. Note that this is <b>not</b> the same as * the difficulty value reported by the Bitcoin "getdifficulty" RPC that you may see on various block explorers. * That number is the result of applying a formula to the underlying difficulty to normalize the minimum to 1. * Calculating the difficulty that way is currently unsupported. */ public long getDifficultyTarget() { return difficultyTarget; } /** Sets the difficulty target in compact form. */ @VisibleForTesting public void setDifficultyTarget(long compactForm) { unCacheHeader(); this.difficultyTarget = compactForm; this.hash = null; } /** * Returns the nonce, an arbitrary value that exists only to make the hash of the block header fall below the * difficulty target. */ public long getNonce() { return nonce; } /** Sets the nonce and clears any cached data. */ @VisibleForTesting public void setNonce(long nonce) { unCacheHeader(); this.nonce = nonce; this.hash = null; } /** Returns an unmodifiable list of transactions held in this block, or null if this object represents just a header. */ @Nullable public List<Transaction> getTransactions() { return transactions == null ? null : Collections.unmodifiableList(transactions); } // /////////////////////////////////////////////////////////////////////////////////////////////// // Unit testing related methods. // Used to make transactions unique. private static int txCounter; /** Adds a coinbase transaction to the block. This exists for unit tests. * * @param height block height, if known, or -1 otherwise. */ @VisibleForTesting void addCoinbaseTransaction(byte[] pubKeyTo, Coin value, final int height) { unCacheTransactions(); transactions = new ArrayList<>(); Transaction coinbase = new Transaction(); final ScriptBuilder inputBuilder = new ScriptBuilder(); if (height >= Block.BLOCK_HEIGHT_GENESIS) { inputBuilder.number(height); } inputBuilder.data(new byte[]{(byte) txCounter, (byte) (txCounter++ >> 8)}); // A real coinbase transaction has some stuff in the scriptSig like the extraNonce and difficulty. The // transactions are distinguished by every TX output going to a different key. // // Here we will do things a bit differently so a new address isn't needed every time. We'll put a simple // counter in the scriptSig so every transaction has a different hash. coinbase.addInput(TransactionInput.coinbaseInput(coinbase, inputBuilder.build().program())); coinbase.addOutput(new TransactionOutput(coinbase, value, ScriptBuilder.createP2PKOutputScript(ECKey.fromPublicOnly(pubKeyTo)).program())); transactions.add(coinbase); } private static final byte[] EMPTY_BYTES = new byte[32]; // It's pretty weak to have this around at runtime: fix later. private static final byte[] pubkeyForTesting = new ECKey().getPubKey(); /** * Returns a solved block that builds on top of this one. This exists for unit tests. * * @param to if not null, 50 coins are sent to the address * @param version version of the block to create * @param time time of the block to create * @param height block height if known, or -1 otherwise * @return created block */ @VisibleForTesting public Block createNextBlock(@Nullable Address to, long version, Instant time, int height) { return createNextBlock(to, version, null, time, pubkeyForTesting, FIFTY_COINS, height); } /** * Returns a solved block that builds on top of this one. This exists for unit tests. * In this variant you can specify a public key (pubkey) for use in generating coinbase blocks. * * @param to if not null, 50 coins are sent to the address * @param version version of the block to create * @param prevOut previous output to spend by the "50 coins transaction" * @param time time of the block to create * @param pubKey for the coinbase * @param coinbaseValue for the coinbase * @param height block height if known, or -1 otherwise * @return created block */ @VisibleForTesting Block createNextBlock(@Nullable Address to, long version, @Nullable TransactionOutPoint prevOut, Instant time, byte[] pubKey, Coin coinbaseValue, int height) { Block b = new Block(version); b.setDifficultyTarget(difficultyTarget); b.addCoinbaseTransaction(pubKey, coinbaseValue, height); if (to != null) { // Add a transaction paying 50 coins to the "to" address. Transaction t = new Transaction(); t.addOutput(new TransactionOutput(t, FIFTY_COINS, to)); // The input does not really need to be a valid signature, as long as it has the right general form. TransactionInput input; if (prevOut == null) { prevOut = new TransactionOutPoint(0, nextTestOutPointHash()); } input = new TransactionInput(t, Script.createInputScript(EMPTY_BYTES, EMPTY_BYTES), prevOut); t.addInput(input); b.addTransaction(t); } b.setPrevBlockHash(getHash()); // Don't let timestamp go backwards Instant bitcoinTime = time.truncatedTo(ChronoUnit.SECONDS); if (time().compareTo(bitcoinTime) >= 0) b.setTime(time().plusSeconds(1)); else b.setTime(bitcoinTime); b.solve(); try { Block.verifyHeader(b); } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen. } if (b.getVersion() != version) { throw new RuntimeException(); } return b; } // Importantly the outpoint hash cannot be zero as that's how we detect a coinbase transaction in isolation // but it must be unique to avoid 'different' transactions looking the same. private Sha256Hash nextTestOutPointHash() { byte[] counter = new byte[32]; counter[0] = (byte) txCounter; counter[1] = (byte) (txCounter++ >> 8); return Sha256Hash.wrap(counter); } /** * This method is intended for test use only. * * @param to if not null, 50 coins are sent to the address * @param prevOut previous output to spend by the "50 coins transaction" * @return created block */ @VisibleForTesting public Block createNextBlock(@Nullable Address to, TransactionOutPoint prevOut) { return createNextBlock(to, BLOCK_VERSION_GENESIS, prevOut, time().plusSeconds(5), pubkeyForTesting, FIFTY_COINS, BLOCK_HEIGHT_UNKNOWN); } /** * This method is intended for test use only. * * @param to if not null, 50 coins are sent to the address * @param coinbaseValue for the coinbase * @return created block */ @VisibleForTesting public Block createNextBlock(@Nullable Address to, Coin coinbaseValue) { return createNextBlock(to, BLOCK_VERSION_GENESIS, null, time().plusSeconds(5), pubkeyForTesting, coinbaseValue, BLOCK_HEIGHT_UNKNOWN); } /** * This method is intended for test use only. * * @param to if not null, 50 coins are sent to the address * @return created block */ @VisibleForTesting public Block createNextBlock(@Nullable Address to) { return createNextBlock(to, FIFTY_COINS); } /** * This method is intended for test use only. * * @param version version of the block to create * @param pubKey for the coinbase * @param coinbaseValue for the coinbase * @param height block height if known, or -1 otherwise * @return created block */ @VisibleForTesting public Block createNextBlockWithCoinbase(long version, byte[] pubKey, Coin coinbaseValue, int height) { return createNextBlock(null, version, (TransactionOutPoint) null, TimeUtils.currentTime(), pubKey, coinbaseValue, height); } /** * Create a block sending 50BTC as a coinbase transaction to the public key specified. * This method is intended for test use only. * * @param version version of the block to create * @param pubKey for the coinbase * @param height block height if known, or -1 otherwise * @return created block */ @VisibleForTesting Block createNextBlockWithCoinbase(long version, byte[] pubKey, int height) { return createNextBlock(null, version, (TransactionOutPoint) null, TimeUtils.currentTime(), pubKey, FIFTY_COINS, height); } /** * Return whether this block contains any transactions. * * @return true if the block contains transactions, false otherwise (is * purely a header). */ public boolean hasTransactions() { return (this.transactions != null) && !this.transactions.isEmpty(); } /** * Returns whether this block conforms to * <a href="https://github.com/bitcoin/bips/blob/master/bip-0034.mediawiki">BIP34: Height in Coinbase</a>. */ public boolean isBIP34() { return version >= BLOCK_VERSION_BIP34; } /** * Returns whether this block conforms to * <a href="https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki">BIP66: Strict DER signatures</a>. */ public boolean isBIP66() { return version >= BLOCK_VERSION_BIP66; } /** * Returns whether this block conforms to * <a href="https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki">BIP65: OP_CHECKLOCKTIMEVERIFY</a>. */ public boolean isBIP65() { return version >= BLOCK_VERSION_BIP65; } /** * Verifies both the header and that the transactions hash to the merkle root. * * @param params parameters for the verification rules * @param block block to verify * @param height block height, if known, or -1 otherwise. * @param flags flags to indicate which tests should be applied (i.e. * whether to test for height in the coinbase transaction). * @throws VerificationException if at least one of the rules is violated */ public static void verify(NetworkParameters params, Block block, int height, EnumSet<VerifyFlag> flags) throws VerificationException { verifyHeader(block); verifyTransactions(params, block, height, flags); } /** * Checks the block data to ensure it follows the rules laid out in the network parameters. Specifically, * throws an exception if the proof of work is invalid, or if the timestamp is too far from what it should be. * This is <b>not</b> everything that is required for a block to be valid, only what is checkable independent * of the chain and without a transaction index. * * @param block block to verify * @throws VerificationException if at least one of the rules is violated */ public static void verifyHeader(Block block) throws VerificationException { // Prove that this block is OK. It might seem that we can just ignore most of these checks given that the // network is also verifying the blocks, but we cannot as it'd open us to a variety of obscure attacks. // // Firstly we need to ensure this block does in fact represent real work done. If the difficulty is high // enough, it's probably been done by the network. block.checkProofOfWork(true); block.checkTimestamp(); } /** * Checks the block contents * * @param params parameters for the verification rules * @param block block to verify * @param height block height, if known, or -1 otherwise. If valid, used * to validate the coinbase input script of v2 and above blocks. * @param flags flags to indicate which tests should be applied (i.e. * whether to test for height in the coinbase transaction). * @throws VerificationException if at least one of the rules is violated */ public static void verifyTransactions(NetworkParameters params, Block block, int height, EnumSet<VerifyFlag> flags) throws VerificationException { // Now we need to check that the body of the block actually matches the headers. The network won't generate // an invalid block, but if we didn't validate this then an untrusted man-in-the-middle could obtain the next // valid block from the network and simply replace the transactions in it with their own fictional // transactions that reference spent or non-existent inputs. if (block.transactions.isEmpty()) throw new VerificationException("Block had no transactions"); if (block.messageSize() > MAX_BLOCK_SIZE) throw new VerificationException("Block larger than MAX_BLOCK_SIZE"); block.checkTransactions(height, flags); block.checkMerkleRoot(); block.checkSigOps(); for (Transaction tx : block.transactions) Transaction.verify(params.network(), tx); } }
45,633
41.76851
175
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/CheckpointManager.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.hash.HashCode; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import com.google.common.io.BaseEncoding; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.store.FullPrunedBlockStore; import org.bitcoinj.store.SPVBlockStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.security.DigestInputStream; import java.security.MessageDigest; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>Vends hard-coded {@link StoredBlock}s for blocks throughout the chain. Checkpoints serve two purposes:</p> * <ol> * <li>They act as a safety mechanism against huge re-orgs that could rewrite large chunks of history, thus * constraining the block chain to be a consensus mechanism only for recent parts of the timeline.</li> * <li>They allow synchronization to the head of the chain for new wallets/users much faster than syncing all * headers from the genesis block.</li> * </ol> * * <p>Checkpoints are used by the SPV {@link BlockChain} to initialize fresh * {@link SPVBlockStore}s. They are not used by fully validating mode, which instead has a * different concept of checkpoints that are used to hard-code the validity of blocks that violate BIP30 (duplicate * coinbase transactions). Those "checkpoints" can be found in NetworkParameters.</p> * * <p>The file format consists of the string "CHECKPOINTS 1", followed by a uint32 containing the number of signatures * to read. The value may not be larger than 256 (so it could have been a byte but isn't for historical reasons). * If the number of signatures is larger than zero, each 65 byte ECDSA secp256k1 signature then follows. The signatures * sign the hash of all bytes that follow the last signature.</p> * * <p>After the signatures come an int32 containing the number of checkpoints in the file. Then each checkpoint follows * one after the other. A checkpoint is 12 bytes for the total work done field, 4 bytes for the height, 80 bytes * for the block header and then 1 zero byte at the end (i.e. number of transactions in the block: always zero).</p> */ public class CheckpointManager { private static final Logger log = LoggerFactory.getLogger(CheckpointManager.class); private static final String BINARY_MAGIC = "CHECKPOINTS 1"; private static final String TEXTUAL_MAGIC = "TXT CHECKPOINTS 1"; private static final int MAX_SIGNATURES = 256; // Map of block header time (in seconds) to data. protected final TreeMap<Instant, StoredBlock> checkpoints = new TreeMap<>(); protected final NetworkParameters params; protected final Sha256Hash dataHash; public static final BaseEncoding BASE64 = BaseEncoding.base64().omitPadding(); /** Loads the default checkpoints bundled with bitcoinj */ public CheckpointManager(NetworkParameters params) throws IOException { this(params, null); } /** Loads the checkpoints from the given stream */ public CheckpointManager(NetworkParameters params, @Nullable InputStream inputStream) throws IOException { this.params = Objects.requireNonNull(params); if (inputStream == null) inputStream = openStream(params); Objects.requireNonNull(inputStream); inputStream = new BufferedInputStream(inputStream); inputStream.mark(1); int first = inputStream.read(); inputStream.reset(); if (first == BINARY_MAGIC.charAt(0)) dataHash = readBinary(inputStream); else if (first == TEXTUAL_MAGIC.charAt(0)) dataHash = readTextual(inputStream); else throw new IOException("Unsupported format."); } /** Returns a checkpoints stream pointing to inside the bitcoinj JAR */ public static InputStream openStream(NetworkParameters params) { return CheckpointManager.class.getResourceAsStream("/" + params.getId() + ".checkpoints.txt"); } private Sha256Hash readBinary(InputStream inputStream) throws IOException { DataInputStream dis = null; try { MessageDigest digest = Sha256Hash.newDigest(); DigestInputStream digestInputStream = new DigestInputStream(inputStream, digest); dis = new DataInputStream(digestInputStream); digestInputStream.on(false); byte[] header = new byte[BINARY_MAGIC.length()]; dis.readFully(header); if (!Arrays.equals(header, BINARY_MAGIC.getBytes(StandardCharsets.US_ASCII))) throw new IOException("Header bytes did not match expected version"); int numSignatures = dis.readInt(); checkState(numSignatures >= 0 && numSignatures < MAX_SIGNATURES, () -> "numSignatures out of range: " + numSignatures); for (int i = 0; i < numSignatures; i++) { byte[] sig = new byte[65]; dis.readFully(sig); // TODO: Do something with the signature here. } digestInputStream.on(true); int numCheckpoints = dis.readInt(); checkState(numCheckpoints > 0); final int size = StoredBlock.COMPACT_SERIALIZED_SIZE; ByteBuffer buffer = ByteBuffer.allocate(size); for (int i = 0; i < numCheckpoints; i++) { if (dis.read(buffer.array(), 0, size) < size) throw new IOException("Incomplete read whilst loading checkpoints."); StoredBlock block = StoredBlock.deserializeCompact(buffer); ((Buffer) buffer).position(0); checkpoints.put(block.getHeader().time(), block); } Sha256Hash dataHash = Sha256Hash.wrap(digest.digest()); log.info("Read {} checkpoints up to time {}, hash is {}", checkpoints.size(), TimeUtils.dateTimeFormat(checkpoints.lastEntry().getKey()), dataHash); return dataHash; } catch (ProtocolException e) { throw new IOException(e); } finally { if (dis != null) dis.close(); inputStream.close(); } } private Sha256Hash readTextual(InputStream inputStream) throws IOException { Hasher hasher = Hashing.sha256().newHasher(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.US_ASCII))) { String magic = reader.readLine(); if (!TEXTUAL_MAGIC.equals(magic)) throw new IOException("unexpected magic: " + magic); int numSigs = Integer.parseInt(reader.readLine()); for (int i = 0; i < numSigs; i++) reader.readLine(); // Skip sigs for now. int numCheckpoints = Integer.parseInt(reader.readLine()); checkState(numCheckpoints > 0); // Hash numCheckpoints in a way compatible to the binary format. hasher.putBytes(ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(numCheckpoints).array()); final int size = StoredBlock.COMPACT_SERIALIZED_SIZE; ByteBuffer buffer = ByteBuffer.allocate(size); for (int i = 0; i < numCheckpoints; i++) { byte[] bytes = BASE64.decode(reader.readLine()); hasher.putBytes(bytes); ((Buffer) buffer).position(0); buffer.put(bytes); ((Buffer) buffer).position(0); StoredBlock block = StoredBlock.deserializeCompact(buffer); checkpoints.put(block.getHeader().time(), block); } HashCode hash = hasher.hash(); log.info("Read {} checkpoints up to time {}, hash is {}", checkpoints.size(), TimeUtils.dateTimeFormat(checkpoints.lastEntry().getKey()), hash); return Sha256Hash.wrap(hash.asBytes()); } } /** * Returns a {@link StoredBlock} representing the last checkpoint before the given time, for example, normally * you would want to know the checkpoint before the earliest wallet birthday. */ public StoredBlock getCheckpointBefore(Instant time) { try { checkArgument(time.isAfter(params.getGenesisBlock().time())); // This is thread safe because the map never changes after creation. Map.Entry<Instant, StoredBlock> entry = checkpoints.floorEntry(time); if (entry != null) return entry.getValue(); Block genesis = params.getGenesisBlock().cloneAsHeader(); return new StoredBlock(genesis, genesis.getWork(), 0); } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen. } } /** @deprecated use {@link #getCheckpointBefore(Instant)} */ @Deprecated public StoredBlock getCheckpointBefore(long timeSecs) { return getCheckpointBefore(Instant.ofEpochSecond(timeSecs)); } /** Returns the number of checkpoints that were loaded. */ public int numCheckpoints() { return checkpoints.size(); } /** Returns a hash of the concatenated checkpoint data. */ public Sha256Hash getDataHash() { return dataHash; } /** * <p>Convenience method that creates a CheckpointManager, loads the given data, gets the checkpoint for the given * time, then inserts it into the store and sets that to be the chain head. Useful when you have just created * a new store from scratch and want to use configure it all in one go.</p> * * <p>Note that time is adjusted backwards by a week to account for possible clock drift in the block headers.</p> */ public static void checkpoint(NetworkParameters params, InputStream checkpoints, BlockStore store, Instant time) throws IOException, BlockStoreException { Objects.requireNonNull(params); Objects.requireNonNull(store); checkArgument(!(store instanceof FullPrunedBlockStore), () -> "you cannot use checkpointing with a full store"); time = time.minus(7, ChronoUnit.DAYS); log.info("Attempting to initialize a new block store with a checkpoint for time {} ({})", time.getEpochSecond(), TimeUtils.dateTimeFormat(time)); BufferedInputStream stream = new BufferedInputStream(checkpoints); CheckpointManager manager = new CheckpointManager(params, stream); StoredBlock checkpoint = manager.getCheckpointBefore(time); store.put(checkpoint); store.setChainHead(checkpoint); } /** @deprecated use {@link #checkpoint(NetworkParameters, InputStream, BlockStore, Instant)} */ @Deprecated public static void checkpoint(NetworkParameters params, InputStream checkpoints, BlockStore store, long timeSecs) throws IOException, BlockStoreException { checkpoint(params, checkpoints, store, Instant.ofEpochSecond(timeSecs)); } }
12,324
46.041985
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/LockTime.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.internal.TimeUtils; import java.time.Instant; import java.util.Objects; /** * Wrapper for transaction lock time, specified either as a block height {@link HeightLock} or as a timestamp * {@link TimeLock} (in seconds since epoch). Both are encoded into the same long "raw value", as used in the Bitcoin protocol. * The lock time is said to be "not set" if its raw value is zero (and the zero value will be represented by a {@link HeightLock} * with value zero.) * <p> * Instances of this class are immutable and should be treated as Java * <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/doc-files/ValueBased.html#Value-basedClasses">value-based</a>. */ public abstract /* sealed */ class LockTime { /** * A {@code LockTime} instance that contains a block height. * Can also be zero to represent no-lock. */ public static final class HeightLock extends LockTime { private HeightLock(long value) { super(value); } /** * @return block height as an int */ public int blockHeight() { return Math.toIntExact(value); } } /** * A {@code LockTime} instance that contains a timestamp. */ public static final class TimeLock extends LockTime { private TimeLock(long value) { super(value); } /** * @return timestamp in java.time format */ public Instant timestamp() { return Instant.ofEpochSecond(value); } } /** * Wrap a raw value (as used in the Bitcoin protocol) into a lock time. * @param rawValue raw value to be wrapped * @return wrapped value */ public static LockTime of(long rawValue) { if (rawValue < 0) throw new IllegalArgumentException("illegal negative lock time: " + rawValue); return rawValue < LockTime.THRESHOLD ? new HeightLock(rawValue) : new TimeLock(rawValue); } /** * Wrap a block height into a lock time. * @param blockHeight block height to be wrapped * @return wrapped block height */ public static HeightLock ofBlockHeight(int blockHeight) { if (blockHeight < 0) throw new IllegalArgumentException("illegal negative block height: " + blockHeight); if (blockHeight >= THRESHOLD) throw new IllegalArgumentException("block height too high: " + blockHeight); return new HeightLock(blockHeight); } /** * Wrap a timestamp into a lock time. * @param time timestamp to be wrapped * @return wrapped timestamp */ public static TimeLock ofTimestamp(Instant time) { long secs = time.getEpochSecond(); if (secs < THRESHOLD) throw new IllegalArgumentException("timestamp too low: " + secs); return new TimeLock(secs); } /** * Construct an unset lock time. * @return unset lock time */ public static LockTime unset() { return LockTime.ofBlockHeight(0); } /** * Raw values below this threshold specify a block height, otherwise a timestamp in seconds since epoch. * Consider using {@code lockTime instance of HeightLock} or {@code lockTime instance of TimeLock} before using this constant. */ public static final long THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC protected final long value; private LockTime(long rawValue) { this.value = rawValue; } /** * Gets the raw value as used in the Bitcoin protocol * @return raw value */ public long rawValue() { return value; } /** * The lock time is considered to be set only if its raw value is greater than zero. * In other words, it is set if it is either a non-zero block height or a timestamp. * @return true if lock time is set */ public boolean isSet() { return value > 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return this.value == ((LockTime) o).value; } @Override public int hashCode() { return Objects.hash(value); } @Override public String toString() { return this instanceof HeightLock ? "block " + ((HeightLock) this).blockHeight() : TimeUtils.dateTimeFormat(((TimeLock) this).timestamp()); } }
5,193
31.061728
145
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/TransactionInput.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.Buffers; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.base.internal.InternalUtils; import org.bitcoinj.script.Script; import org.bitcoinj.script.ScriptException; import org.bitcoinj.wallet.DefaultRiskAnalysis; import org.bitcoinj.wallet.KeyBag; import org.bitcoinj.wallet.RedeemData; import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Map; import java.util.Objects; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * <p>A transfer of coins from one address to another creates a transaction in which the outputs * can be claimed by the recipient in the input of another transaction. You can imagine a * transaction as being a module which is wired up to others, the inputs of one have to be wired * to the outputs of another. The exceptions are coinbase transactions, which create new coins.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class TransactionInput { /** Magic sequence number that indicates there is no sequence number. */ public static final long NO_SEQUENCE = 0xFFFFFFFFL; /** * BIP68: If this flag set, sequence is NOT interpreted as a relative lock-time. */ public static final long SEQUENCE_LOCKTIME_DISABLE_FLAG = 1L << 31; /** * BIP68: If sequence encodes a relative lock-time and this flag is set, the relative lock-time has units of 512 * seconds, otherwise it specifies blocks with a granularity of 1. */ public static final long SEQUENCE_LOCKTIME_TYPE_FLAG = 1L << 22; /** * BIP68: If sequence encodes a relative lock-time, this mask is applied to extract that lock-time from the sequence * field. */ public static final long SEQUENCE_LOCKTIME_MASK = 0x0000ffff; private static final byte[] EMPTY_ARRAY = new byte[0]; // Magic outpoint index that indicates the input is in fact unconnected. private static final long UNCONNECTED = 0xFFFFFFFFL; @Nullable protected Transaction parent; // Allows for altering transactions after they were broadcast. Values below NO_SEQUENCE-1 mean it can be altered. private long sequence; // Data needed to connect to the output of the transaction we're gathering coins from. private TransactionOutPoint outpoint; // The "script bytes" might not actually be a script. In coinbase transactions where new coins are minted there // is no input transaction, so instead the scriptBytes contains some extra stuff (like a rollover nonce) that we // don't care about much. The bytes are turned into a Script object (cached below) on demand via a getter. private byte[] scriptBytes; // The Script object obtained from parsing scriptBytes. Only filled in on demand and if the transaction is not // coinbase. private WeakReference<Script> scriptSig; /** Value of the output connected to the input, if known. This field does not participate in equals()/hashCode(). */ @Nullable private Coin value; private TransactionWitness witness; /** * Creates an input that connects to nothing - used only in creation of coinbase transactions. * * @param parentTransaction parent transaction * @param scriptBytes arbitrary bytes in the script */ public static TransactionInput coinbaseInput(Transaction parentTransaction, byte[] scriptBytes) { Objects.requireNonNull(parentTransaction); checkArgument(scriptBytes.length >= 2 && scriptBytes.length <= 100, () -> "script must be between 2 and 100 bytes: " + scriptBytes.length); return new TransactionInput(parentTransaction, scriptBytes, TransactionOutPoint.UNCONNECTED); } /** * Deserialize this transaction input from a given payload. * * @param payload payload to deserialize from * @param parentTransaction parent transaction of the input * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static TransactionInput read(ByteBuffer payload, Transaction parentTransaction) throws BufferUnderflowException, ProtocolException { Objects.requireNonNull(parentTransaction); TransactionOutPoint outpoint = TransactionOutPoint.read(payload); byte[] scriptBytes = Buffers.readLengthPrefixedBytes(payload); long sequence = ByteUtils.readUint32(payload); return new TransactionInput(parentTransaction, scriptBytes, outpoint, sequence, null); } public TransactionInput(@Nullable Transaction parentTransaction, byte[] scriptBytes, TransactionOutPoint outpoint) { this(parentTransaction, scriptBytes, outpoint, NO_SEQUENCE, null); } public TransactionInput(@Nullable Transaction parentTransaction, byte[] scriptBytes, TransactionOutPoint outpoint, @Nullable Coin value) { this(parentTransaction, scriptBytes, outpoint, NO_SEQUENCE, value); } private TransactionInput(@Nullable Transaction parentTransaction, byte[] scriptBytes, TransactionOutPoint outpoint, long sequence, @Nullable Coin value) { checkArgument(value == null || value.signum() >= 0, () -> "value out of range: " + value); this.scriptBytes = scriptBytes; this.outpoint = outpoint; this.sequence = sequence; this.value = value; setParent(parentTransaction); } /** * Creates an UNSIGNED input that links to the given output */ TransactionInput(Transaction parentTransaction, TransactionOutput output) { super(); long outputIndex = output.getIndex(); if(output.getParentTransaction() != null ) { outpoint = new TransactionOutPoint(outputIndex, output.getParentTransaction()); } else { outpoint = new TransactionOutPoint(output); } scriptBytes = EMPTY_ARRAY; sequence = NO_SEQUENCE; setParent(parentTransaction); this.value = output.getValue(); } /** * Gets the index of this input in the parent transaction, or throws if this input is freestanding. Iterates * over the parents list to discover this. */ public int getIndex() { final int myIndex = getParentTransaction().getInputs().indexOf(this); if (myIndex < 0) throw new IllegalStateException("Input linked to wrong parent transaction?"); return myIndex; } /** * Write this transaction input into the given buffer. * * @param buf buffer to write into * @return the buffer * @throws BufferOverflowException if the input doesn't fit the remaining buffer */ public ByteBuffer write(ByteBuffer buf) throws BufferOverflowException { buf.put(outpoint.serialize()); Buffers.writeLengthPrefixedBytes(buf, scriptBytes); ByteUtils.writeInt32LE(sequence, buf); return buf; } /** * Allocates a byte array and writes this transaction input into it. * * @return byte array containing the transaction input */ public byte[] serialize() { return write(ByteBuffer.allocate(getMessageSize())).array(); } /** @deprecated use {@link #serialize()} */ @Deprecated public byte[] bitcoinSerialize() { return serialize(); } /** * Return the size of the serialized message. Note that if the message was deserialized from a payload, this * size can differ from the size of the original payload. * * @return size of the serialized message in bytes */ public int getMessageSize() { int size = TransactionOutPoint.BYTES; size += VarInt.sizeOf(scriptBytes.length) + scriptBytes.length; size += 4; // sequence return size; } /** * Coinbase transactions have special inputs with hashes of zero. If this is such an input, returns true. */ public boolean isCoinBase() { return outpoint.hash().equals(Sha256Hash.ZERO_HASH) && (outpoint.index() & 0xFFFFFFFFL) == 0xFFFFFFFFL; // -1 but all is serialized to the wire as unsigned int. } /** * Returns the script that is fed to the referenced output (scriptPubKey) script in order to satisfy it: usually * contains signatures and maybe keys, but can contain arbitrary data if the output script accepts it. */ public Script getScriptSig() throws ScriptException { // Transactions that generate new coins don't actually have a script. Instead this // parameter is overloaded to be something totally different. Script script = scriptSig == null ? null : scriptSig.get(); if (script == null) { script = Script.parse(scriptBytes); scriptSig = new WeakReference<>(script); } return script; } /** Set the given program as the scriptSig that is supposed to satisfy the connected output script. */ public void setScriptSig(Script scriptSig) { this.scriptSig = new WeakReference<>(Objects.requireNonNull(scriptSig)); // TODO: This should all be cleaned up so we have a consistent internal representation. setScriptBytes(scriptSig.program()); } /** * Sequence numbers allow participants in a multi-party transaction signing protocol to create new versions of the * transaction independently of each other. Newer versions of a transaction can replace an existing version that's * in nodes memory pools if the existing version is time locked. See the Contracts page on the Bitcoin wiki for * examples of how you can use this feature to build contract protocols. */ public long getSequenceNumber() { return sequence; } /** * Sequence numbers allow participants in a multi-party transaction signing protocol to create new versions of the * transaction independently of each other. Newer versions of a transaction can replace an existing version that's * in nodes memory pools if the existing version is time locked. See the Contracts page on the Bitcoin wiki for * examples of how you can use this feature to build contract protocols. */ public void setSequenceNumber(long sequence) { checkArgument(sequence >= 0 && sequence <= ByteUtils.MAX_UNSIGNED_INTEGER, () -> "sequence out of range: " + sequence); this.sequence = sequence; } /** * @return The previous output transaction reference, as an OutPoint structure. This contains the * data needed to connect to the output of the transaction we're gathering coins from. */ public TransactionOutPoint getOutpoint() { return outpoint; } /** * The "script bytes" might not actually be a script. In coinbase transactions where new coins are minted there * is no input transaction, so instead the scriptBytes contains some extra stuff (like a rollover nonce) that we * don't care about much. The bytes are turned into a Script object (cached below) on demand via a getter. * @return the scriptBytes */ public byte[] getScriptBytes() { return scriptBytes; } /** Clear input scripts, e.g. in preparation for signing. */ public void clearScriptBytes() { setScriptBytes(TransactionInput.EMPTY_ARRAY); } /** * @param scriptBytes the scriptBytes to set */ void setScriptBytes(byte[] scriptBytes) { this.scriptSig = null; this.scriptBytes = scriptBytes; } /** * @return The Transaction that owns this input. */ public Transaction getParentTransaction() { return parent; } /** * @return Value of the output connected to this input, if known. Null if unknown. */ @Nullable public Coin getValue() { return value; } /** * Get the transaction witness of this input. * * @return the witness of the input */ public TransactionWitness getWitness() { return witness != null ? witness : TransactionWitness.EMPTY; } /** * Set the transaction witness of an input. */ public void setWitness(TransactionWitness witness) { this.witness = witness; } /** * Determine if the transaction has witnesses. * * @return true if the transaction has witnesses */ public boolean hasWitness() { return witness != null && witness.getPushCount() != 0; } public enum ConnectionResult { NO_SUCH_TX, ALREADY_SPENT, SUCCESS } // TODO: Clean all this up once TransactionOutPoint disappears. /** * Locates the referenced output from the given pool of transactions. * * @return The TransactionOutput or null if the transactions map doesn't contain the referenced tx. */ @Nullable TransactionOutput getConnectedOutput(Map<Sha256Hash, Transaction> transactions) { Transaction tx = transactions.get(outpoint.hash()); if (tx == null) return null; return tx.getOutput(outpoint); } /** * Alias for getOutpoint().getConnectedRedeemData(keyBag) * @see TransactionOutPoint#getConnectedRedeemData(KeyBag) */ @Nullable public RedeemData getConnectedRedeemData(KeyBag keyBag) throws ScriptException { return getOutpoint().getConnectedRedeemData(keyBag); } public enum ConnectMode { DISCONNECT_ON_CONFLICT, ABORT_ON_CONFLICT } /** * 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. */ public ConnectionResult connect(Map<Sha256Hash, Transaction> transactions, ConnectMode mode) { Transaction tx = transactions.get(outpoint.hash()); if (tx == null) { return TransactionInput.ConnectionResult.NO_SUCH_TX; } return connect(tx, mode); } /** * 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. */ public ConnectionResult connect(Transaction transaction, ConnectMode mode) { if (!transaction.getTxId().equals(outpoint.hash())) return ConnectionResult.NO_SUCH_TX; TransactionOutput out = transaction.getOutput(outpoint); 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 = outpoint.connectTransaction(out.getParentTransaction()); return TransactionInput.ConnectionResult.ALREADY_SPENT; } } connect(out); return TransactionInput.ConnectionResult.SUCCESS; } /** Internal use only: connects this TransactionInput to the given output (updates pointers and spent flags) */ public void connect(TransactionOutput out) { outpoint = outpoint.connectTransaction(out.getParentTransaction()); out.markAsSpent(this); value = out.getValue(); } /** * 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. */ public boolean disconnect() { TransactionOutput connectedOutput; if (outpoint.fromTx != null) { // The outpoint is connected using a "standard" wallet, disconnect it. connectedOutput = outpoint.fromTx.getOutput(outpoint); outpoint = outpoint.disconnectTransaction(); } else if (outpoint.connectedOutput != null) { // The outpoint is connected using a UTXO based wallet, disconnect it. connectedOutput = outpoint.connectedOutput; outpoint = outpoint.disconnectOutput(); } 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; } } /** * @return true if this transaction's sequence number is set (ie it may be a part of a time-locked transaction) */ public boolean hasSequence() { return sequence != NO_SEQUENCE; } /** * Returns whether this input will cause a transaction to opt into the * <a href="https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki">full replace-by-fee </a> semantics. */ public boolean isOptInFullRBF() { return sequence < NO_SEQUENCE - 1; } /** * Returns whether this input, if it belongs to a version 2 (or higher) transaction, has * <a href="https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki">relative lock-time</a> enabled. */ public boolean hasRelativeLockTime() { return (sequence & SEQUENCE_LOCKTIME_DISABLE_FLAG) == 0; } /** * 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. */ public void verify() throws VerificationException { final Transaction fromTx = getOutpoint().fromTx; Objects.requireNonNull(fromTx, "Not connected"); final TransactionOutput output = fromTx.getOutput(outpoint); verify(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. * * @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. */ public void verify(TransactionOutput output) throws VerificationException { if (output.parent != null) { if (!getOutpoint().hash().equals(output.getParentTransaction().getTxId())) throw new VerificationException("This input does not refer to the tx containing the output."); if (getOutpoint().index() != 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); } /** * Returns the connected output, assuming the input was connected with * {@link TransactionInput#connect(TransactionOutput)} or variants at some point. If it wasn't connected, then * this method returns null. */ @Nullable public TransactionOutput getConnectedOutput() { return getOutpoint().getConnectedOutput(); } /** * Returns the connected transaction, assuming the input was connected with * {@link TransactionInput#connect(TransactionOutput)} or variants at some point. If it wasn't connected, then * this method returns null. */ @Nullable public Transaction getConnectedTransaction() { return getOutpoint().fromTx; } /** * <p>Returns either RuleViolation.NONE if the input is standard, or which rule makes it non-standard if so. * The "IsStandard" rules control whether the default Bitcoin Core client blocks relay of a tx / refuses to mine it, * however, non-standard transactions can still be included in blocks and will be accepted as valid if so.</p> * * <p>This method simply calls {@code DefaultRiskAnalysis.isInputStandard(this)}.</p> */ public DefaultRiskAnalysis.RuleViolation isStandard() { return DefaultRiskAnalysis.isInputStandard(this); } protected final void setParent(@Nullable Transaction parent) { this.parent = parent; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TransactionInput other = (TransactionInput) o; return sequence == other.sequence && parent != null && parent.equals(other.parent) && outpoint.equals(other.outpoint) && Arrays.equals(scriptBytes, other.scriptBytes); } @Override public int hashCode() { return Objects.hash(sequence, outpoint, Arrays.hashCode(scriptBytes)); } /** * Returns a human-readable debug string. */ @Override public String toString() { StringBuilder s = new StringBuilder("TxIn"); if (isCoinBase()) { s.append(": COINBASE"); } else { s.append(" for [").append(outpoint).append("]: "); try { s.append(getScriptSig()); String flags = InternalUtils.commaJoin(hasWitness() ? "witness" : null, hasSequence() ? "sequence: " + Long.toHexString(sequence) : null, isOptInFullRBF() ? "opts into full RBF" : null); if (!flags.isEmpty()) s.append(" (").append(flags).append(')'); } catch (ScriptException e) { s.append(" [exception: ").append(e.getMessage()).append("]"); } } return s.toString(); } }
23,821
40.072414
143
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/MemoryPoolMessage.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; /** * <p>The "mempool" message asks a remote peer to announce all transactions in its memory pool, possibly restricted by * any Bloom filter set on the connection. The list of transaction hashes comes back in an inv message. Note that * this is different to the {@link TxConfidenceTable} object which doesn't try to keep track of all pending transactions, * it's just a holding area for transactions that a part of the app may find interesting. The mempool message has * no fields.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class MemoryPoolMessage extends EmptyMessage { }
1,272
41.433333
121
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/PeerAddress.java
/* * Copyright 2011 Google Inc. * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.io.BaseEncoding; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.Buffers; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.crypto.internal.CryptoUtils; import org.bitcoinj.base.internal.ByteUtils; import javax.annotation.Nullable; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; import static org.bitcoinj.base.internal.Preconditions.checkArgument; /** * A PeerAddress holds an IP address and port number representing the network location of * a peer in the Bitcoin P2P network. It exists primarily for serialization purposes. * <p> * Instances of this class are not safe for use by multiple threads. */ public class PeerAddress { @Nullable private final InetAddress addr; // Used for IPV4, IPV6, null otherwise @Nullable private final String hostname; // Used for (.onion addresses) TORV2, TORV3, null otherwise private final int port; private final Services services; private final Instant time; private static final BaseEncoding BASE32 = BaseEncoding.base32().omitPadding().lowerCase(); private static final byte[] ONIONCAT_PREFIX = ByteUtils.parseHex("fd87d87eeb43"); // BIP-155 reserved network IDs, see: https://github.com/bitcoin/bips/blob/master/bip-0155.mediawiki private enum NetworkId { IPV4(1), IPV6(2), TORV2(3), TORV3(4), I2P(5), CJDNS(6); final int value; NetworkId(int value) { this.value = value; } static Optional<NetworkId> of(int value) { return Stream.of(values()) .filter(id -> id.value == value) .findFirst(); } } /** * Constructs a simple peer address from the given IP address and port, but without services. The time is set to * current time. * * @param addr ip address of peer * @param port port the peer is listening on * @return simple peer address */ public static PeerAddress simple(InetAddress addr, int port) { return new PeerAddress( Objects.requireNonNull(addr), null, port, Services.none(), TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS)); } /** * Constructs a simple peer address from the given socket address, but without services. The time is set to * current time. * * @param addr ip address and port of peer * @return simple peer address */ public static PeerAddress simple(InetSocketAddress addr) { return new PeerAddress( addr.getAddress(), null, addr.getPort(), Services.none(), TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS)); } /** * Constructs a peer address from the given IP address, port, services and time. Such addresses are used for * `addr` and `addrv2` messages of types IPv4 and IPv6. * * @param addr ip address of the peer * @param port port the peer is listening on * @param services node services the peer is providing * @param time last-seen time of the peer */ public static PeerAddress inet(InetAddress addr, int port, Services services, Instant time) { return new PeerAddress( Objects.requireNonNull(addr), null, port, Objects.requireNonNull(services), Objects.requireNonNull(time)); } /** * Constructs a peer address from the given IP address, port, services and time. Such addresses are used for * `addr` and `addrv2` messages of types IPv4 and IPv6. * * @param addr ip address and port of the peer * @param services node services the peer is providing * @param time last-seen time of the peer */ public static PeerAddress inet(InetSocketAddress addr, Services services, Instant time) { return new PeerAddress( addr.getAddress(), null, addr.getPort(), Objects.requireNonNull(services), Objects.requireNonNull(time)); } /** * Deserialize this peer address from a given payload, using a given protocol variant. The variant can be * 1 ({@link AddressV1Message}) or 2 ({@link AddressV2Message}). * * @param payload payload to deserialize from * @param protocolVariant variant of protocol to use for parsing * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static PeerAddress read(ByteBuffer payload, int protocolVariant) throws BufferUnderflowException, ProtocolException { if (protocolVariant < 0 || protocolVariant > 2) throw new IllegalStateException("invalid protocolVariant: " + protocolVariant); Instant time = Instant.ofEpochSecond(ByteUtils.readUint32(payload)); Services services; InetAddress addr = null; String hostname = null; if (protocolVariant == 2) { services = Services.of(VarInt.read(payload).longValue()); int networkId = payload.get(); byte[] addrBytes = Buffers.readLengthPrefixedBytes(payload); int addrLen = addrBytes.length; Optional<NetworkId> id = NetworkId.of(networkId); if (id.isPresent()) { switch(id.get()) { case IPV4: if (addrLen != 4) throw new ProtocolException("invalid length of IPv4 address: " + addrLen); addr = getByAddress(addrBytes); hostname = null; break; case IPV6: if (addrLen != 16) throw new ProtocolException("invalid length of IPv6 address: " + addrLen); addr = getByAddress(addrBytes); hostname = null; break; case TORV2: if (addrLen != 10) throw new ProtocolException("invalid length of TORv2 address: " + addrLen); hostname = BASE32.encode(addrBytes) + ".onion"; addr = null; break; case TORV3: if (addrLen != 32) throw new ProtocolException("invalid length of TORv3 address: " + addrLen); byte torVersion = 0x03; byte[] onionAddress = new byte[35]; System.arraycopy(addrBytes, 0, onionAddress, 0, 32); System.arraycopy(CryptoUtils.onionChecksum(addrBytes, torVersion), 0, onionAddress, 32, 2); onionAddress[34] = torVersion; hostname = BASE32.encode(onionAddress) + ".onion"; addr = null; break; case I2P: case CJDNS: // ignore unimplemented network IDs for now addr = null; hostname = null; break; } } else { // ignore unknown network IDs addr = null; hostname = null; } } else { services = Services.read(payload); byte[] addrBytes = Buffers.readBytes(payload, 16); if (Arrays.equals(ONIONCAT_PREFIX, Arrays.copyOf(addrBytes, 6))) { byte[] onionAddress = Arrays.copyOfRange(addrBytes, 6, 16); hostname = BASE32.encode(onionAddress) + ".onion"; } else { addr = getByAddress(addrBytes); hostname = null; } } int port = ByteUtils.readUint16BE(payload); return new PeerAddress(addr, hostname, port, services, time); } private PeerAddress(InetAddress addr, String hostname, int port, Services services, Instant time) { this.addr = addr; this.hostname = hostname; this.port = port; this.services = services; this.time = time; } public static PeerAddress localhost(NetworkParameters params) { return PeerAddress.simple(InetAddress.getLoopbackAddress(), params.getPort()); } /** * Write this peer address into the given buffer, using a given protocol variant. The variant can be * 1 ({@link AddressV1Message}) or 2 ({@link AddressV2Message}).. * * @param buf buffer to write into * @param protocolVariant variant of protocol used * @return the buffer * @throws BufferOverflowException if the peer addressdoesn't fit the remaining buffer */ public ByteBuffer write(ByteBuffer buf, int protocolVariant) throws BufferOverflowException { if (protocolVariant < 1 || protocolVariant > 2) throw new IllegalStateException("invalid protocolVariant: " + protocolVariant); ByteUtils.writeInt32LE(time.getEpochSecond(), buf); if (protocolVariant == 2) { VarInt.of(services.bits()).write(buf); if (addr != null) { if (addr instanceof Inet4Address) { buf.put((byte) 0x01); VarInt.of(4).write(buf); buf.put(addr.getAddress()); } else if (addr instanceof Inet6Address) { buf.put((byte) 0x02); VarInt.of(16).write(buf); buf.put(addr.getAddress()); } else { throw new IllegalStateException(); } } else if (addr == null && hostname != null && hostname.toLowerCase(Locale.ROOT).endsWith(".onion")) { byte[] onionAddress = BASE32.decode(hostname.substring(0, hostname.length() - 6)); if (onionAddress.length == 10) { // TORv2 buf.put((byte) 0x03); VarInt.of(10).write(buf); buf.put(onionAddress); } else if (onionAddress.length == 32 + 2 + 1) { // TORv3 buf.put((byte) 0x04); VarInt.of(32).write(buf); byte[] pubkey = Arrays.copyOfRange(onionAddress, 0, 32); byte[] checksum = Arrays.copyOfRange(onionAddress, 32, 34); byte torVersion = onionAddress[34]; if (torVersion != 0x03) throw new IllegalStateException("version"); if (!Arrays.equals(checksum, CryptoUtils.onionChecksum(pubkey, torVersion))) throw new IllegalStateException("checksum"); buf.put(pubkey); } else { throw new IllegalStateException(); } } else { throw new IllegalStateException(); } } else { services.write(buf); if (addr != null) { // Java does not provide any utility to map an IPv4 address into IPv6 space, so we have to do it by // hand. byte[] ipBytes = addr.getAddress(); buf.put(mapIntoIPv6(ipBytes)); } else if (hostname != null && hostname.toLowerCase(Locale.ROOT).endsWith(".onion")) { byte[] onionAddress = BASE32.decode(hostname.substring(0, hostname.length() - 6)); if (onionAddress.length == 10) { // TORv2 buf.put(ONIONCAT_PREFIX); buf.put(onionAddress); } else { throw new IllegalStateException(); } } else { throw new IllegalStateException(); } } // And write out the port. Unlike the rest of the protocol, address and port is in big endian byte order. ByteUtils.writeInt16BE(port, buf); return buf; } /** * Allocates a byte array and writes this peer address into it, using a given protocol variant. The variant can be * 1 ({@link AddressV1Message}) or 2 ({@link AddressV2Message}). * * @param protocolVariant variant of protocol used * @return byte array containing the peer address */ public byte[] serialize(int protocolVariant) { return write(ByteBuffer.allocate(getMessageSize(protocolVariant)), protocolVariant).array(); } /** * Return the size of the serialized message, using a given protocol variant. The variant can be * 1 ({@link AddressV1Message}) or 2 ({@link AddressV2Message}).. Note that if the message was deserialized from * a payload, this size can differ from the size of the original payload. * * @param protocolVariant variant of protocol used * @return size of the serialized message in bytes */ public int getMessageSize(int protocolVariant) { if (protocolVariant < 1 || protocolVariant > 2) throw new IllegalStateException("invalid protocolVariant: " + protocolVariant); int size = 0; size += 4; // time if (protocolVariant == 2) { size += VarInt.sizeOf(services.bits()); size += 1; // network id if (addr != null) { if (addr instanceof Inet4Address) { size += VarInt.sizeOf(4) + 4; } else if (addr instanceof Inet6Address) { size += VarInt.sizeOf(16) + 16; } else { throw new IllegalStateException(); } } else if (addr == null && hostname != null && hostname.toLowerCase(Locale.ROOT).endsWith(".onion")) { byte[] onionAddress = BASE32.decode(hostname.substring(0, hostname.length() - 6)); if (onionAddress.length == 10) { // TORv2 size += VarInt.sizeOf(10) + 10; } else if (onionAddress.length == 32 + 2 + 1) { // TORv3 size += VarInt.sizeOf(32) + 32; } else { throw new IllegalStateException(); } } else { throw new IllegalStateException(); } } else { size += Services.BYTES; size += 16; // ip } size += 2; // port return size; } public static InetAddress getByAddress(byte[] addrBytes) { try { return InetAddress.getByAddress(addrBytes); } catch (UnknownHostException e) { throw new RuntimeException(e); // Cannot happen. } } /** * Map given IPv4 address into IPv6 space. * * @param ip IPv4 to map into IPv6 space * @return mapped IP */ public static byte[] mapIntoIPv6(byte[] ip) { checkArgument(ip.length == 4 || ip.length == 16, () -> "need IPv4 or IPv6"); if (ip.length == 16) return ip; // nothing to do byte[] ipv6 = new byte[16]; System.arraycopy(ip, 0, ipv6, 12, 4); ipv6[10] = (byte) 0xFF; ipv6[11] = (byte) 0xFF; return ipv6; } public String getHostname() { return hostname; } public InetAddress getAddr() { return addr; } public InetSocketAddress getSocketAddress() { return new InetSocketAddress(getAddr(), getPort()); } public int getPort() { return port; } public Services getServices() { return services; } /** * Gets the time that the node was last seen as connected to the network. * @return time that the node was last seen */ public Instant time() { return time; } /** @deprecated use {@link #time()} */ @Deprecated public long getTime() { return time.getEpochSecond(); } @Override public String toString() { if (hostname != null) { return "[" + hostname + "]:" + port; } else if (addr != null) { return "[" + addr.getHostAddress() + "]:" + port; } else { return "[ PeerAddress of unsupported type ]:" + port; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PeerAddress other = (PeerAddress) o; // time is deliberately not included in equals return Objects.equals(addr, other.addr) && Objects.equals(hostname, other.hostname) && port == other.port && Objects.equals(services, other.services); } @Override public int hashCode() { // time is deliberately not included in hashcode return Objects.hash(addr, hostname, port, services); } public InetSocketAddress toSocketAddress() { // Reconstruct the InetSocketAddress properly if (hostname != null) { return InetSocketAddress.createUnresolved(hostname, port); } else { // A null addr will create a wildcard InetSocketAddress return new InetSocketAddress(addr, port); } } }
18,615
37.783333
128
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/Transaction.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.base.MoreObjects; import com.google.common.math.IntMath; import org.bitcoinj.base.Address; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Network; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.Buffers; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.LockTime.HeightLock; import org.bitcoinj.core.LockTime.TimeLock; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.core.TransactionConfidence.ConfidenceType; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.script.Script; import org.bitcoinj.base.ScriptType; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.script.ScriptError; import org.bitcoinj.script.ScriptException; import org.bitcoinj.script.ScriptOpCodes; import org.bitcoinj.script.ScriptPattern; import org.bitcoinj.signers.TransactionSigner; import org.bitcoinj.utils.ExchangeRate; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.WalletTransaction.Pool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.math.BigInteger; import java.math.RoundingMode; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.TreeMap; import static org.bitcoinj.base.internal.Preconditions.check; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; import static org.bitcoinj.core.ProtocolVersion.WITNESS_VERSION; import static org.bitcoinj.base.internal.ByteUtils.writeInt32LE; import static org.bitcoinj.base.internal.ByteUtils.writeInt64LE; /** * <p>A transaction represents the movement of coins from some addresses to some other addresses. It can also represent * the minting of new coins. A Transaction object corresponds to the equivalent in the Bitcoin C++ implementation.</p> * * <p>Transactions are the fundamental atoms of Bitcoin and have many powerful features. Read * <a href="https://bitcoinj.github.io/working-with-transactions">"Working with transactions"</a> in the * documentation to learn more about how to use this class.</p> * * <p>All Bitcoin transactions are at risk of being reversed, though the risk is much less than with traditional payment * systems. Transactions have <i>confidence levels</i>, which help you decide whether to trust a transaction or not. * Whether to trust a transaction is something that needs to be decided on a case by case basis - a rule that makes * sense for selling MP3s might not make sense for selling cars, or accepting payments from a family member. If you * are building a wallet, how to present confidence to your users is something to consider carefully.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class Transaction extends BaseMessage { private static final Comparator<Transaction> SORT_TX_BY_ID = Comparator.comparing(Transaction::getTxId); /** * A comparator that can be used to sort transactions by their updateTime field. The ordering goes from most recent * into the past. Transactions with an unknown update time will go to the end. */ public static final Comparator<Transaction> SORT_TX_BY_UPDATE_TIME = Comparator.comparing( Transaction::sortableUpdateTime, Comparator.reverseOrder()) .thenComparing(SORT_TX_BY_ID); // helps the above comparator by handling transactions with unknown update time private static Instant sortableUpdateTime(Transaction tx) { return tx.updateTime().orElse(Instant.EPOCH); } /** * A comparator that can be used to sort transactions by their chain height. Unconfirmed transactions will go to * the end. */ public static final Comparator<Transaction> SORT_TX_BY_HEIGHT = Comparator.comparing( Transaction::sortableBlockHeight, Comparator.reverseOrder()) .thenComparing(SORT_TX_BY_ID); // helps the above comparator by handling unconfirmed transactions private static int sortableBlockHeight(Transaction tx) { TransactionConfidence confidence = tx.getConfidence(); return confidence.getConfidenceType() == ConfidenceType.BUILDING ? confidence.getAppearedAtChainHeight() : Block.BLOCK_HEIGHT_UNKNOWN; } private static final Logger log = LoggerFactory.getLogger(Transaction.class); /** * When this bit is set in protocolVersion, do not include witness. The actual value is the same as in Bitcoin Core * for consistency. */ public static final int SERIALIZE_TRANSACTION_NO_WITNESS = 0x40000000; /** * @deprecated use {@link LockTime#THRESHOLD} or * {@code lockTime instanceof HeightLock} or * {@code lockTime instanceof TimeLock} **/ @Deprecated public static final int LOCKTIME_THRESHOLD = (int) LockTime.THRESHOLD; /** How many bytes a transaction can be before it won't be relayed anymore. Currently 100kb. */ public static final int MAX_STANDARD_TX_SIZE = 100000; /** * If feePerKb is lower than this, Bitcoin Core will treat it as if there were no fee. */ public static final Coin REFERENCE_DEFAULT_MIN_TX_FEE = Coin.valueOf(1000); // 0.01 mBTC /** * If using this feePerKb, transactions will get confirmed within the next couple of blocks. * This should be adjusted from time to time. Last adjustment: February 2017. */ public static final Coin DEFAULT_TX_FEE = Coin.valueOf(100000); // 1 mBTC private final int protocolVersion; // These are bitcoin serialized. private long version; private List<TransactionInput> inputs; private List<TransactionOutput> outputs; private volatile LockTime vLockTime; // This is either the time the transaction was broadcast as measured from the local clock, or the time from the // block in which it was included. Note that this can be changed by re-orgs so the wallet may update this field. // Old serialized transactions don't have this field, thus null is valid. It is used for returning an ordered // list of transactions from a wallet, which is helpful for presenting to users. @Nullable private Instant updateTime = null; // Data about how confirmed this tx is. Serialized, may be null. @Nullable private TransactionConfidence confidence; // Records a map of which blocks the transaction has appeared in (keys) to an index within that block (values). // The "index" is not a real index, instead the values are only meaningful relative to each other. For example, // consider two transactions that appear in the same block, t1 and t2, where t2 spends an output of t1. Both // will have the same block hash as a key in their appearsInHashes, but the counter would be 1 and 2 respectively // regardless of where they actually appeared in the block. // // If this transaction is not stored in the wallet, appearsInHashes is null. private Map<Sha256Hash, Integer> appearsInHashes; /** * This enum describes the underlying reason the transaction was created. It's useful for rendering wallet GUIs * more appropriately. */ public enum Purpose { /** Used when the purpose of a transaction is genuinely unknown. */ UNKNOWN, /** Transaction created to satisfy a user payment request. */ USER_PAYMENT, /** Transaction automatically created and broadcast in order to reallocate money from old to new keys. */ KEY_ROTATION, /** Transaction that uses up pledges to an assurance contract */ ASSURANCE_CONTRACT_CLAIM, /** Transaction that makes a pledge to an assurance contract. */ ASSURANCE_CONTRACT_PLEDGE, /** Send-to-self transaction that exists just to create an output of the right size we can pledge. */ ASSURANCE_CONTRACT_STUB, /** Raise fee, e.g. child-pays-for-parent. */ RAISE_FEE, // In future: de/refragmentation, privacy boosting/mixing, etc. // When adding a value, it also needs to be added to wallet.proto, WalletProtobufSerialize.makeTxProto() // and WalletProtobufSerializer.readTransaction()! } private Purpose purpose = Purpose.UNKNOWN; /** * This field can be used by applications to record the exchange rate that was valid when the transaction happened. * It's optional. */ @Nullable private ExchangeRate exchangeRate; /** * This field can be used to record the memo of the payment request that initiated the transaction. It's optional. */ @Nullable private String memo; /** * Constructs an incomplete coinbase transaction with a minimal input script and no outputs. * * @return coinbase transaction */ public static Transaction coinbase() { Transaction tx = new Transaction(); tx.addInput(TransactionInput.coinbaseInput(tx, new byte[2])); // 2 is minimum return tx; } /** * Constructs an incomplete coinbase transaction with given bytes for the input script and no outputs. * * @param inputScriptBytes arbitrary bytes for the coinbase input * @return coinbase transaction */ public static Transaction coinbase(byte[] inputScriptBytes) { Transaction tx = new Transaction(); tx.addInput(TransactionInput.coinbaseInput(tx, inputScriptBytes)); return tx; } /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static Transaction read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { return Transaction.read(payload, ProtocolVersion.CURRENT.intValue()); } /** * Deserialize this message from a given payload, according to * <a href="https://github.com/bitcoin/bips/blob/master/bip-0144.mediawiki">BIP144</a> or the * <a href="https://en.bitcoin.it/wiki/Protocol_documentation#tx">classic format</a>, depending on if the * transaction is segwit or not. * * @param payload payload to deserialize from * @param protocolVersion protocol version to use for deserialization * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static Transaction read(ByteBuffer payload, int protocolVersion) throws BufferUnderflowException, ProtocolException { Transaction tx = new Transaction(protocolVersion); boolean allowWitness = allowWitness(protocolVersion); // version tx.version = ByteUtils.readUint32(payload); byte flags = 0; // Try to parse the inputs. In case the dummy is there, this will be read as an empty array list. tx.readInputs(payload); if (tx.inputs.size() == 0 && allowWitness) { // We read a dummy or an empty input flags = payload.get(); if (flags != 0) { tx.readInputs(payload); tx.readOutputs(payload); } else { tx.outputs = new ArrayList<>(0); } } else { // We read non-empty inputs. Assume normal outputs follows. tx.readOutputs(payload); } if (((flags & 1) != 0) && allowWitness) { // The witness flag is present, and we support witnesses. flags ^= 1; // script_witnesses tx.readWitnesses(payload); if (!tx.hasWitnesses()) { // It's illegal to encode witnesses when all witness stacks are empty. throw new ProtocolException("Superfluous witness record"); } } if (flags != 0) { // Unknown flag in the serialization throw new ProtocolException("Unknown transaction optional data"); } // lock_time tx.vLockTime = LockTime.of(ByteUtils.readUint32(payload)); return tx; } private Transaction(int protocolVersion) { this.protocolVersion = protocolVersion; } public Transaction() { this.protocolVersion = ProtocolVersion.CURRENT.intValue(); version = 1; inputs = new ArrayList<>(); outputs = new ArrayList<>(); // We don't initialize appearsIn deliberately as it's only useful for transactions stored in the wallet. vLockTime = LockTime.unset(); } /** * Returns the transaction id as you see them in block explorers. It is used as a reference by transaction inputs * via outpoints. */ public Sha256Hash getTxId() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { bitcoinSerializeToStream(baos, false); } catch (IOException e) { throw new RuntimeException(e); // cannot happen } return Sha256Hash.wrapReversed(Sha256Hash.hashTwice(baos.toByteArray())); } /** * Returns if tx witnesses are allowed based on the protocol version */ private static boolean allowWitness(int protocolVersion) { return (protocolVersion & SERIALIZE_TRANSACTION_NO_WITNESS) == 0 && protocolVersion >= WITNESS_VERSION.intValue(); } /** * Returns the witness transaction id (aka witness id) as per BIP144. For transactions without witness, this is the * same as {@link #getTxId()}. */ public Sha256Hash getWTxId() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { bitcoinSerializeToStream(baos, hasWitnesses()); } catch (IOException e) { throw new RuntimeException(e); // cannot happen } return Sha256Hash.wrapReversed(Sha256Hash.hashTwice(baos.toByteArray())); } /** Gets the transaction weight as defined in BIP141. */ public int getWeight() { if (!hasWitnesses()) return this.messageSize() * 4; try (final ByteArrayOutputStream stream = new ByteArrayOutputStream(255)) { // just a guess at an average tx length bitcoinSerializeToStream(stream, false); final int baseSize = stream.size(); stream.reset(); bitcoinSerializeToStream(stream, true); final int totalSize = stream.size(); return baseSize * 3 + totalSize; } catch (IOException e) { throw new RuntimeException(e); // cannot happen } } /** Gets the virtual transaction size as defined in BIP141. */ public int getVsize() { if (!hasWitnesses()) return this.messageSize(); return IntMath.divide(getWeight(), 4, RoundingMode.CEILING); // round up } /** * Gets the sum of all transaction inputs, regardless of who owns them. * <p> * <b>Warning:</b> Inputs with {@code null} {@link TransactionInput#getValue()} are silently skipped. Before completing * or signing a transaction you should verify that there are no inputs with {@code null} values. * @return The sum of all inputs with non-null values. */ public Coin getInputSum() { return inputs.stream() .map(TransactionInput::getValue) .filter(Objects::nonNull) .reduce(Coin.ZERO, Coin::add); } /** * Calculates the sum of the outputs that are sending coins to a key in the wallet. */ public Coin getValueSentToMe(TransactionBag transactionBag) { // This is tested in WalletTest. Coin v = Coin.ZERO; for (TransactionOutput o : outputs) { if (!o.isMineOrWatched(transactionBag)) continue; v = v.add(o.getValue()); } return v; } /** * Returns a map of block [hashes] which contain the transaction mapped to relativity counters, or null if this * transaction doesn't have that data because it's not stored in the wallet or because it has never appeared in a * block. */ @Nullable public Map<Sha256Hash, Integer> getAppearsInHashes() { return appearsInHashes != null ? Collections.unmodifiableMap(new HashMap<>(appearsInHashes)) : null; } /** * Convenience wrapper around getConfidence().getConfidenceType() * @return true if this transaction hasn't been seen in any block yet. */ public boolean isPending() { return getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.PENDING; } /** * <p>Puts the given block in the internal set of blocks in which this transaction appears. This is * used by the wallet to ensure transactions that appear on side chains are recorded properly even though the * block stores do not save the transaction data at all.</p> * * <p>If there is a re-org this will be called once for each block that was previously seen, to update which block * is the best chain. The best chain block is guaranteed to be called last. So this must be idempotent.</p> * * <p>Sets updatedAt to be the earliest valid block time where this tx was seen.</p> * * @param block The {@link StoredBlock} in which the transaction has appeared. * @param bestChain whether to set the updatedAt timestamp from the block header (only if not already set) * @param relativityOffset A number that disambiguates the order of transactions within a block. */ public void setBlockAppearance(StoredBlock block, boolean bestChain, int relativityOffset) { Instant blockTime = block.getHeader().time(); if (bestChain && (updateTime == null || updateTime.equals(Instant.EPOCH) || updateTime.isAfter(blockTime))) { updateTime = blockTime; } addBlockAppearance(block.getHeader().getHash(), relativityOffset); if (bestChain) { TransactionConfidence transactionConfidence = getConfidence(); // This sets type to BUILDING and depth to one. transactionConfidence.setAppearedAtChainHeight(block.getHeight()); } } public void addBlockAppearance(final Sha256Hash blockHash, int relativityOffset) { if (appearsInHashes == null) { // TODO: This could be a lot more memory efficient as we'll typically only store one element. appearsInHashes = new TreeMap<>(); } appearsInHashes.put(blockHash, relativityOffset); } /** * Calculates the sum of the inputs that are spending coins with keys in the wallet. This requires the * transactions sending coins to those keys to be in the wallet. This method will not attempt to download the * blocks containing the input transactions if the key is in the wallet but the transactions are not. * * @return sum of the inputs that are spending coins with keys in the wallet */ public Coin getValueSentFromMe(TransactionBag wallet) throws ScriptException { // This is tested in WalletTest. Coin v = Coin.ZERO; for (TransactionInput input : inputs) { // This input is taking value from a transaction in our wallet. To discover the value, // we must find the connected transaction. TransactionOutput connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.UNSPENT)); if (connected == null) connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.SPENT)); if (connected == null) connected = input.getConnectedOutput(wallet.getTransactionPool(Pool.PENDING)); if (connected == null) continue; // The connected output may be the change to the sender of a previous input sent to this wallet. In this // case we ignore it. if (!connected.isMineOrWatched(wallet)) continue; v = v.add(connected.getValue()); } return v; } /** * Gets the sum of the outputs of the transaction. If the outputs are less than the inputs, it does not count the fee. * @return the sum of the outputs regardless of who owns them. */ public Coin getOutputSum() { return outputs.stream() .map(TransactionOutput::getValue) .reduce(Coin.ZERO, Coin::add); } /** * Returns the difference of {@link Transaction#getValueSentToMe(TransactionBag)} and {@link Transaction#getValueSentFromMe(TransactionBag)}. */ public Coin getValue(TransactionBag wallet) throws ScriptException { return getValueSentToMe(wallet).subtract(getValueSentFromMe(wallet)); } /** * The transaction fee is the difference of the value of all inputs and the value of all outputs. Currently, the fee * can only be determined for transactions created by us. * * @return fee, or null if it cannot be determined */ public Coin getFee() { Coin fee = Coin.ZERO; if (inputs.isEmpty() || outputs.isEmpty()) // Incomplete transaction return null; for (TransactionInput input : inputs) { if (input.getValue() == null) return null; fee = fee.add(input.getValue()); } for (TransactionOutput output : outputs) { fee = fee.subtract(output.getValue()); } return fee; } /** * Returns true if any of the outputs is marked as spent. */ public boolean isAnyOutputSpent() { for (TransactionOutput output : outputs) { if (!output.isAvailableForSpending()) return true; } return false; } /** * Returns false if this transaction has at least one output that is owned by the given wallet and unspent, true * otherwise. */ public boolean isEveryOwnedOutputSpent(TransactionBag transactionBag) { for (TransactionOutput output : outputs) { if (output.isAvailableForSpending() && output.isMineOrWatched(transactionBag)) return false; } return true; } /** * Returns the earliest time at which the transaction was seen (broadcast or included into the chain), * or empty if that information isn't available. */ public Optional<Instant> updateTime() { return Optional.ofNullable(updateTime); } /** @deprecated use {@link #updateTime()} */ @Deprecated public Date getUpdateTime() { return Date.from(updateTime().orElse(Instant.EPOCH)); } /** * Sets the update time of this transaction. * @param updateTime update time */ public void setUpdateTime(Instant updateTime) { this.updateTime = Objects.requireNonNull(updateTime); } /** * Clears the update time of this transaction. */ public void clearUpdateTime() { this.updateTime = null; } /** @deprecated use {@link #setUpdateTime(Instant)} or {@link #clearUpdateTime()} */ @Deprecated public void setUpdateTime(Date updateTime) { if (updateTime != null && updateTime.getTime() > 0) setUpdateTime(updateTime.toInstant()); else clearUpdateTime(); } /** * These constants are a part of a scriptSig signature on the inputs. They define the details of how a * transaction can be redeemed, specifically, they control how the hash of the transaction is calculated. */ public enum SigHash { ALL(1), NONE(2), SINGLE(3), ANYONECANPAY(0x80), // Caution: Using this type in isolation is non-standard. Treated similar to ANYONECANPAY_ALL. ANYONECANPAY_ALL(0x81), ANYONECANPAY_NONE(0x82), ANYONECANPAY_SINGLE(0x83), UNSET(0); // Caution: Using this type in isolation is non-standard. Treated similar to ALL. public final int value; /** * @param value */ SigHash(final int value) { this.value = value; } /** * @return the value as a byte */ public byte byteValue() { return (byte) this.value; } } /** * @deprecated Instead use SigHash.ANYONECANPAY.value or SigHash.ANYONECANPAY.byteValue() as appropriate. */ public static final byte SIGHASH_ANYONECANPAY_VALUE = (byte) 0x80; private void readInputs(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { VarInt numInputsVarInt = VarInt.read(payload); check(numInputsVarInt.fitsInt(), BufferUnderflowException::new); int numInputs = numInputsVarInt.intValue(); inputs = new ArrayList<>(Math.min((int) numInputs, Utils.MAX_INITIAL_ARRAY_LENGTH)); for (long i = 0; i < numInputs; i++) { inputs.add(TransactionInput.read(payload, this)); } } private void readOutputs(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { VarInt numOutputsVarInt = VarInt.read(payload); check(numOutputsVarInt.fitsInt(), BufferUnderflowException::new); int numOutputs = numOutputsVarInt.intValue(); outputs = new ArrayList<>(Math.min((int) numOutputs, Utils.MAX_INITIAL_ARRAY_LENGTH)); for (long i = 0; i < numOutputs; i++) { outputs.add(TransactionOutput.read(payload, this)); } } private void readWitnesses(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { for (TransactionInput input : inputs) { input.setWitness(TransactionWitness.read(payload)); } } /** @return true of the transaction has any witnesses in any of its inputs */ public boolean hasWitnesses() { return inputs.stream().anyMatch(TransactionInput::hasWitness); } /** * The priority (coin age) calculation doesn't use the regular message size, but rather one adjusted downwards * for the number of inputs. The goal is to incentivise cleaning up the UTXO set with free transactions, if one * can do so. */ public int getMessageSizeForPriorityCalc() { int size = this.messageSize(); for (TransactionInput input : inputs) { // 41: min size of an input // 110: enough to cover a compressed pubkey p2sh redemption (somewhat arbitrary). int benefit = 41 + Math.min(110, input.getScriptSig().program().length); if (size > benefit) size -= benefit; } return size; } /** * A coinbase transaction is one that creates a new coin. They are the first transaction in each block and their * value is determined by a formula that all implementations of Bitcoin share. In 2011 the value of a coinbase * transaction is 50 coins, but in future it will be less. A coinbase transaction is defined not only by its * position in a block but by the data in the inputs. */ public boolean isCoinBase() { return inputs.size() == 1 && inputs.get(0).isCoinBase(); } @Override public String toString() { MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this); helper.addValue(toString(null, null)); return helper.toString(); } /** * A human-readable version of the transaction useful for debugging. The format is not guaranteed to be stable. * @param chain if provided, will be used to estimate lock times (if set) * @param network if provided, network for output scripts converted to addresses */ public String toString(@Nullable AbstractBlockChain chain, @Nullable Network network) { return toString(chain, network, ""); } /** * A human-readable version of the transaction useful for debugging. The format is not guaranteed to be stable. * @param chain if provided, will be used to estimate lock times (if set) * @param network if provided, network for output scripts converted to addresses * @param indent characters that will be prepended to each line of the output */ public String toString(@Nullable AbstractBlockChain chain, @Nullable Network network, CharSequence indent) { Objects.requireNonNull(indent); StringBuilder s = new StringBuilder(); Sha256Hash txId = getTxId(), wTxId = getWTxId(); s.append(indent).append(txId); if (!wTxId.equals(txId)) s.append(", wtxid ").append(wTxId); s.append('\n'); int weight = getWeight(); int size = this.messageSize(); int vsize = getVsize(); s.append(indent).append("weight: ").append(weight).append(" wu, "); if (size != vsize) s.append(vsize).append(" virtual bytes, "); s.append(size).append(" bytes\n"); updateTime().ifPresent( time -> s.append(indent).append("updated: ").append(TimeUtils.dateTimeFormat(time)).append('\n')); if (version != 1) s.append(indent).append("version ").append(version).append('\n'); if (isTimeLocked()) { s.append(indent).append("time locked until "); LockTime locktime = lockTime(); s.append(locktime); if (locktime instanceof HeightLock) { if (chain != null) { s.append(" (estimated to be reached at ") .append(TimeUtils.dateTimeFormat(chain.estimateBlockTimeInstant(((HeightLock) locktime).blockHeight()))) .append(')'); } } s.append('\n'); } if (hasRelativeLockTime()) { s.append(indent).append("has relative lock time\n"); } if (isOptInFullRBF()) { s.append(indent).append("opts into full replace-by-fee\n"); } if (purpose != null) s.append(indent).append("purpose: ").append(purpose).append('\n'); if (isCoinBase()) { s.append(indent).append("coinbase\n"); } else if (!inputs.isEmpty()) { int i = 0; for (TransactionInput in : inputs) { s.append(indent).append(" "); s.append("in "); try { s.append(in.getScriptSig()); final Coin value = in.getValue(); if (value != null) s.append(" ").append(value.toFriendlyString()); s.append('\n'); if (in.hasWitness()) { s.append(indent).append(" witness:"); s.append(in.getWitness()); s.append('\n'); } final TransactionOutPoint outpoint = in.getOutpoint(); final TransactionOutput connectedOutput = outpoint.getConnectedOutput(); s.append(indent).append(" "); if (connectedOutput != null) { Script scriptPubKey = connectedOutput.getScriptPubKey(); ScriptType scriptType = scriptPubKey.getScriptType(); if (scriptType != null) { s.append(scriptType); if (network != null) s.append(" addr:").append(scriptPubKey.getToAddress(network)); } else { s.append("unknown script type"); } } else { s.append("unconnected"); } s.append(" outpoint:").append(outpoint).append('\n'); if (in.hasSequence()) { s.append(indent).append(" sequence:").append(Long.toHexString(in.getSequenceNumber())); if (in.isOptInFullRBF()) s.append(", opts into full RBF"); if (version >= 2 && in.hasRelativeLockTime()) s.append(", has RLT"); s.append('\n'); } } catch (Exception e) { s.append("[exception: ").append(e.getMessage()).append("]\n"); } i++; } } else { s.append(indent).append(" "); s.append("INCOMPLETE: No inputs!\n"); } for (TransactionOutput out : outputs) { s.append(indent).append(" "); s.append("out "); try { Script scriptPubKey = out.getScriptPubKey(); s.append(scriptPubKey.chunks().size() > 0 ? scriptPubKey.toString() : "<no scriptPubKey>"); s.append(" "); s.append(out.getValue().toFriendlyString()); s.append('\n'); s.append(indent).append(" "); ScriptType scriptType = scriptPubKey.getScriptType(); if (scriptType != null) { s.append(scriptType); if (network != null) s.append(" addr:").append(scriptPubKey.getToAddress(network)); } else { s.append("unknown script type"); } if (!out.isAvailableForSpending()) { s.append(" spent"); final TransactionInput spentBy = out.getSpentBy(); if (spentBy != null) { s.append(" by:"); s.append(spentBy.getParentTransaction().getTxId()).append(':') .append(spentBy.getIndex()); } } s.append('\n'); } catch (Exception e) { s.append("[exception: ").append(e.getMessage()).append("]\n"); } } final Coin fee = getFee(); if (fee != null) { s.append(indent).append(" fee "); s.append(fee.multiply(1000).divide(weight).toFriendlyString()).append("/wu, "); if (size != vsize) s.append(fee.multiply(1000).divide(vsize).toFriendlyString()).append("/vkB, "); s.append(fee.multiply(1000).divide(size).toFriendlyString()).append("/kB "); s.append(fee.toFriendlyString()).append('\n'); } return s.toString(); } /** * Removes all the inputs from this transaction. * Note that this also invalidates the length attribute */ public void clearInputs() { for (TransactionInput input : inputs) { input.setParent(null); } inputs.clear(); } /** * Adds an input to this transaction that imports value from the given output. Note that this input is <i>not</i> * complete and after every input is added with {@link #addInput(TransactionInput)} and every output is added with * {@link #addOutput(TransactionOutput)}, a {@link TransactionSigner} must be used to finalize the transaction and finish the inputs * off. Otherwise it won't be accepted by the network. * @return the newly created input. */ public TransactionInput addInput(TransactionOutput from) { return addInput(new TransactionInput(this, from)); } /** * Adds an input directly, with no checking that it's valid. * @return the new input. */ public TransactionInput addInput(TransactionInput input) { input.setParent(this); inputs.add(input); return input; } /** * Creates and adds an input to this transaction, with no checking that it's valid. * @return the newly created input. */ public TransactionInput addInput(Sha256Hash spendTxHash, long outputIndex, Script script) { return addInput(new TransactionInput(this, script.program(), new TransactionOutPoint(outputIndex, spendTxHash))); } /** * Adds a new and fully signed input for the given parameters. Note that this method is <b>not</b> thread safe * and requires external synchronization. Please refer to general documentation on Bitcoin scripting and contracts * to understand the values of sigHash and anyoneCanPay: otherwise you can use the other form of this method * that sets them to typical defaults. * * @param prevOut A reference to the output being spent * @param scriptPubKey The scriptPubKey of the output * @param amount The amount of the output (which is part of the signature hash for segwit) * @param sigKey The signing key * @param sigHash enum specifying how the transaction hash is calculated * @param anyoneCanPay anyone-can-pay hashing * @return The newly created input * @throws ScriptException if the scriptPubKey is something we don't know how to sign. */ public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, Coin amount, ECKey sigKey, SigHash sigHash, boolean anyoneCanPay) throws ScriptException { // Verify the API user didn't try to do operations out of order. checkState(!outputs.isEmpty(), () -> "attempting to sign tx without outputs"); if (amount == null || amount.value <= 0) { log.warn("Illegal amount value. Amount is required for SegWit transactions."); } TransactionInput input = new TransactionInput(this, new byte[] {}, prevOut, amount); addInput(input); int inputIndex = inputs.size() - 1; if (ScriptPattern.isP2PK(scriptPubKey)) { TransactionSignature signature = calculateSignature(inputIndex, sigKey, scriptPubKey, sigHash, anyoneCanPay); input.setScriptSig(ScriptBuilder.createInputScript(signature)); input.setWitness(null); } else if (ScriptPattern.isP2PKH(scriptPubKey)) { TransactionSignature signature = calculateSignature(inputIndex, sigKey, scriptPubKey, sigHash, anyoneCanPay); input.setScriptSig(ScriptBuilder.createInputScript(signature, sigKey)); input.setWitness(null); } else if (ScriptPattern.isP2WPKH(scriptPubKey)) { Script scriptCode = ScriptBuilder.createP2PKHOutputScript(sigKey); TransactionSignature signature = calculateWitnessSignature(inputIndex, sigKey, scriptCode, input.getValue(), sigHash, anyoneCanPay); input.setScriptSig(ScriptBuilder.createEmpty()); input.setWitness(TransactionWitness.redeemP2WPKH(signature, sigKey)); } else { throw new ScriptException(ScriptError.SCRIPT_ERR_UNKNOWN_ERROR, "Don't know how to sign for this kind of scriptPubKey: " + scriptPubKey); } return input; } /** * @param prevOut A reference to the output being spent * @param scriptPubKey The scriptPubKey of the output * @param sigKey The signing key * @param sigHash enum specifying how the transaction hash is calculated * @param anyoneCanPay anyone-can-pay hashing * @return The newly created input * @throws ScriptException if the scriptPubKey is something we don't know how to sign. * @deprecated Use {@link Transaction#addSignedInput(TransactionOutPoint, Script, Coin, ECKey, SigHash, boolean)} */ @Deprecated public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey, SigHash sigHash, boolean anyoneCanPay) throws ScriptException { return addSignedInput(prevOut, scriptPubKey, null, sigKey, sigHash, anyoneCanPay); } /** * Adds a new and fully signed input for the given parameters. Note that this method is <b>not</b> thread safe * and requires external synchronization. * Defaults to {@link SigHash#ALL} and "false" for the anyoneCanPay flag. This is normally what you want. * @param prevOut A reference to the output being spent * @param scriptPubKey The scriptPubKey of the output * @param amount The amount of the output (which is part of the signature hash for segwit) * @param sigKey The signing key * @return The newly created input * @throws ScriptException if the scriptPubKey is something we don't know how to sign. */ public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, Coin amount, ECKey sigKey) throws ScriptException { return addSignedInput(prevOut, scriptPubKey, amount, sigKey, SigHash.ALL, false); } /** * @param prevOut A reference to the output being spent * @param scriptPubKey The scriptPubKey of the output * @param sigKey The signing key * @return The newly created input * @throws ScriptException if the scriptPubKey is something we don't know how to sign. * @deprecated Use {@link Transaction#addSignedInput(TransactionOutPoint, Script, Coin, ECKey)} */ @Deprecated public TransactionInput addSignedInput(TransactionOutPoint prevOut, Script scriptPubKey, ECKey sigKey) throws ScriptException { return addSignedInput(prevOut, scriptPubKey, null, sigKey); } /** * Adds an input that points to the given output and contains a valid signature for it, calculated using the * signing key. Defaults to {@link SigHash#ALL} and "false" for the anyoneCanPay flag. This is normally what you want. * @param output output to sign and use as input * @param sigKey The signing key * @return The newly created input */ public TransactionInput addSignedInput(TransactionOutput output, ECKey sigKey) { return addSignedInput(output, sigKey, SigHash.ALL, false); } /** * Adds an input that points to the given output and contains a valid signature for it, calculated using the * signing key. * @see Transaction#addSignedInput(TransactionOutPoint, Script, Coin, ECKey, SigHash, boolean) * @param output output to sign and use as input * @param sigKey The signing key * @param sigHash enum specifying how the transaction hash is calculated * @param anyoneCanPay anyone-can-pay hashing * @return The newly created input */ public TransactionInput addSignedInput(TransactionOutput output, ECKey sigKey, SigHash sigHash, boolean anyoneCanPay) { Objects.requireNonNull(output.getValue(), "TransactionOutput.getValue() must not be null"); checkState(output.getValue().value > 0, () -> "transactionOutput.getValue() must not be greater than zero"); return addSignedInput(output.getOutPointFor(), output.getScriptPubKey(), output.getValue(), sigKey, sigHash, anyoneCanPay); } /** * Removes all the outputs from this transaction. * Note that this also invalidates the length attribute */ public void clearOutputs() { for (TransactionOutput output : outputs) { output.setParent(null); } outputs.clear(); } /** * Adds the given output to this transaction. The output must be completely initialized. Returns the given output. */ public TransactionOutput addOutput(TransactionOutput to) { to.setParent(this); outputs.add(to); return to; } /** * Creates an output based on the given address and value, adds it to this transaction, and returns the new output. */ public TransactionOutput addOutput(Coin value, Address address) { return addOutput(new TransactionOutput(this, value, address)); } /** * Creates an output that pays to the given pubkey directly (no address) with the given value, adds it to this * transaction, and returns the new output. */ public TransactionOutput addOutput(Coin value, ECKey pubkey) { return addOutput(new TransactionOutput(this, value, pubkey)); } /** * Creates an output that pays to the given script. The address and key forms are specialisations of this method, * you won't normally need to use it unless you're doing unusual things. */ public TransactionOutput addOutput(Coin value, Script script) { return addOutput(new TransactionOutput(this, value, script.program())); } /** * Calculates a signature that is valid for being inserted into the input at the given position. This is simply * a wrapper around calling {@link Transaction#hashForSignature(int, byte[], Transaction.SigHash, boolean)} * followed by {@link ECKey#sign(Sha256Hash)} and then returning a new {@link TransactionSignature}. The key * must be usable for signing as-is: if the key is encrypted it must be decrypted first external to this method. * * @param inputIndex Which input to calculate the signature for, as an index. * @param key The private key used to calculate the signature. * @param redeemScript Byte-exact contents of the scriptPubKey that is being satisfied, or the P2SH redeem script. * @param hashType Signing mode, see the enum for documentation. * @param anyoneCanPay Signing mode, see the SigHash enum for documentation. * @return A newly calculated signature object that wraps the r, s and sighash components. */ public TransactionSignature calculateSignature(int inputIndex, ECKey key, byte[] redeemScript, SigHash hashType, boolean anyoneCanPay) { Sha256Hash hash = hashForSignature(inputIndex, redeemScript, hashType, anyoneCanPay); return new TransactionSignature(key.sign(hash), hashType, anyoneCanPay); } /** * Calculates a signature that is valid for being inserted into the input at the given position. This is simply * a wrapper around calling {@link Transaction#hashForSignature(int, byte[], Transaction.SigHash, boolean)} * followed by {@link ECKey#sign(Sha256Hash)} and then returning a new {@link TransactionSignature}. * * @param inputIndex Which input to calculate the signature for, as an index. * @param key The private key used to calculate the signature. * @param redeemScript The scriptPubKey that is being satisfied, or the P2SH redeem script. * @param hashType Signing mode, see the enum for documentation. * @param anyoneCanPay Signing mode, see the SigHash enum for documentation. * @return A newly calculated signature object that wraps the r, s and sighash components. */ public TransactionSignature calculateSignature(int inputIndex, ECKey key, Script redeemScript, SigHash hashType, boolean anyoneCanPay) { Sha256Hash hash = hashForSignature(inputIndex, redeemScript.program(), hashType, anyoneCanPay); return new TransactionSignature(key.sign(hash), hashType, anyoneCanPay); } /** * Calculates a signature that is valid for being inserted into the input at the given position. This is simply * a wrapper around calling {@link Transaction#hashForSignature(int, byte[], Transaction.SigHash, boolean)} * followed by {@link ECKey#sign(Sha256Hash)} and then returning a new {@link TransactionSignature}. The key * must be usable for signing as-is: if the key is encrypted it must be decrypted first external to this method. * * @param inputIndex Which input to calculate the signature for, as an index. * @param key The private key used to calculate the signature. * @param aesKey The AES key to use for decryption of the private key. If null then no decryption is required. * @param redeemScript Byte-exact contents of the scriptPubKey that is being satisfied, or the P2SH redeem script. * @param hashType Signing mode, see the enum for documentation. * @param anyoneCanPay Signing mode, see the SigHash enum for documentation. * @return A newly calculated signature object that wraps the r, s and sighash components. */ public TransactionSignature calculateSignature(int inputIndex, ECKey key, @Nullable AesKey aesKey, byte[] redeemScript, SigHash hashType, boolean anyoneCanPay) { Sha256Hash hash = hashForSignature(inputIndex, redeemScript, hashType, anyoneCanPay); return new TransactionSignature(key.sign(hash, aesKey), hashType, anyoneCanPay); } /** * Calculates a signature that is valid for being inserted into the input at the given position. This is simply * a wrapper around calling {@link Transaction#hashForSignature(int, byte[], Transaction.SigHash, boolean)} * followed by {@link ECKey#sign(Sha256Hash)} and then returning a new {@link TransactionSignature}. * * @param inputIndex Which input to calculate the signature for, as an index. * @param key The private key used to calculate the signature. * @param aesKey The AES key to use for decryption of the private key. If null then no decryption is required. * @param redeemScript The scriptPubKey that is being satisfied, or the P2SH redeem script. * @param hashType Signing mode, see the enum for documentation. * @param anyoneCanPay Signing mode, see the SigHash enum for documentation. * @return A newly calculated signature object that wraps the r, s and sighash components. */ public TransactionSignature calculateSignature(int inputIndex, ECKey key, @Nullable AesKey aesKey, Script redeemScript, SigHash hashType, boolean anyoneCanPay) { Sha256Hash hash = hashForSignature(inputIndex, redeemScript.program(), hashType, anyoneCanPay); return new TransactionSignature(key.sign(hash, aesKey), hashType, anyoneCanPay); } /** * <p>Calculates a signature hash, that is, a hash of a simplified form of the transaction. How exactly the transaction * is simplified is specified by the type and anyoneCanPay parameters.</p> * * <p>This is a low level API and when using the regular {@link Wallet} class you don't have to call this yourself. * When working with more complex transaction types and contracts, it can be necessary. When signing a P2SH output * the redeemScript should be the script encoded into the scriptSig field, for normal transactions, it's the * scriptPubKey of the output you're signing for.</p> * * @param inputIndex input the signature is being calculated for. Tx signatures are always relative to an input. * @param redeemScript the bytes that should be in the given input during signing. * @param type Should be SigHash.ALL * @param anyoneCanPay should be false. */ public Sha256Hash hashForSignature(int inputIndex, byte[] redeemScript, SigHash type, boolean anyoneCanPay) { byte sigHashType = (byte) TransactionSignature.calcSigHashValue(type, anyoneCanPay); return hashForSignature(inputIndex, redeemScript, sigHashType); } /** * <p>Calculates a signature hash, that is, a hash of a simplified form of the transaction. How exactly the transaction * is simplified is specified by the type and anyoneCanPay parameters.</p> * * <p>This is a low level API and when using the regular {@link Wallet} class you don't have to call this yourself. * When working with more complex transaction types and contracts, it can be necessary. When signing a P2SH output * the redeemScript should be the script encoded into the scriptSig field, for normal transactions, it's the * scriptPubKey of the output you're signing for.</p> * * @param inputIndex input the signature is being calculated for. Tx signatures are always relative to an input. * @param redeemScript the script that should be in the given input during signing. * @param type Should be SigHash.ALL * @param anyoneCanPay should be false. */ public Sha256Hash hashForSignature(int inputIndex, Script redeemScript, SigHash type, boolean anyoneCanPay) { int sigHash = TransactionSignature.calcSigHashValue(type, anyoneCanPay); return hashForSignature(inputIndex, redeemScript.program(), (byte) sigHash); } /** * This is required for signatures which use a sigHashType which cannot be represented using SigHash and anyoneCanPay * See transaction c99c49da4c38af669dea436d3e73780dfdb6c1ecf9958baa52960e8baee30e73, which has sigHashType 0 */ public Sha256Hash hashForSignature(int inputIndex, byte[] connectedScript, byte sigHashType) { // The SIGHASH flags are used in the design of contracts, please see this page for a further understanding of // the purposes of the code in this method: // // https://en.bitcoin.it/wiki/Contracts try { // Create a copy of this transaction to operate upon because we need make changes to the inputs and outputs. // It would not be thread-safe to change the attributes of the transaction object itself. Transaction tx = Transaction.read(ByteBuffer.wrap(serialize())); // Clear input scripts in preparation for signing. If we're signing a fresh // transaction that step isn't very helpful, but it doesn't add much cost relative to the actual // EC math so we'll do it anyway. for (int i = 0; i < tx.inputs.size(); i++) { TransactionInput input = tx.inputs.get(i); input.clearScriptBytes(); input.setWitness(null); } // This step has no purpose beyond being synchronized with Bitcoin Core's bugs. OP_CODESEPARATOR // is a legacy holdover from a previous, broken design of executing scripts that shipped in Bitcoin 0.1. // It was seriously flawed and would have let anyone take anyone elses money. Later versions switched to // the design we use today where scripts are executed independently but share a stack. This left the // OP_CODESEPARATOR instruction having no purpose as it was only meant to be used internally, not actually // ever put into scripts. Deleting OP_CODESEPARATOR is a step that should never be required but if we don't // do it, we could split off the best chain. connectedScript = Script.removeAllInstancesOfOp(connectedScript, ScriptOpCodes.OP_CODESEPARATOR); // Set the input to the script of its output. Bitcoin Core does this but the step has no obvious purpose as // the signature covers the hash of the prevout transaction which obviously includes the output script // already. Perhaps it felt safer to him in some way, or is another leftover from how the code was written. TransactionInput input = tx.inputs.get(inputIndex); input.setScriptBytes(connectedScript); if ((sigHashType & 0x1f) == SigHash.NONE.value) { // SIGHASH_NONE means no outputs are signed at all - the signature is effectively for a "blank cheque". tx.outputs = new ArrayList<>(0); // The signature isn't broken by new versions of the transaction issued by other parties. for (int i = 0; i < tx.inputs.size(); i++) if (i != inputIndex) tx.inputs.get(i).setSequenceNumber(0); } else if ((sigHashType & 0x1f) == SigHash.SINGLE.value) { // SIGHASH_SINGLE means only sign the output at the same index as the input (ie, my output). if (inputIndex >= tx.outputs.size()) { // The input index is beyond the number of outputs, it's a buggy signature made by a broken // Bitcoin implementation. Bitcoin Core also contains a bug in handling this case: // any transaction output that is signed in this case will result in both the signed output // and any future outputs to this public key being steal-able by anyone who has // the resulting signature and the public key (both of which are part of the signed tx input). // Bitcoin Core's bug is that SignatureHash was supposed to return a hash and on this codepath it // actually returns the constant "1" to indicate an error, which is never checked for. Oops. return Sha256Hash.wrap("0100000000000000000000000000000000000000000000000000000000000000"); } // In SIGHASH_SINGLE the outputs after the matching input index are deleted, and the outputs before // that position are "nulled out". Unintuitively, the value in a "null" transaction is set to -1. tx.outputs = new ArrayList<>(tx.outputs.subList(0, inputIndex + 1)); for (int i = 0; i < inputIndex; i++) tx.outputs.set(i, new TransactionOutput(tx, Coin.NEGATIVE_SATOSHI, new byte[] {})); // The signature isn't broken by new versions of the transaction issued by other parties. for (int i = 0; i < tx.inputs.size(); i++) if (i != inputIndex) tx.inputs.get(i).setSequenceNumber(0); } if ((sigHashType & SigHash.ANYONECANPAY.value) == SigHash.ANYONECANPAY.value) { // SIGHASH_ANYONECANPAY means the signature in the input is not broken by changes/additions/removals // of other inputs. For example, this is useful for building assurance contracts. tx.inputs = new ArrayList<>(); tx.inputs.add(input); } ByteArrayOutputStream bos = new ByteArrayOutputStream(255); // just a guess at an average tx length tx.bitcoinSerializeToStream(bos, false); // We also have to write a hash type (sigHashType is actually an unsigned char) writeInt32LE(0x000000ff & sigHashType, bos); // Note that this is NOT reversed to ensure it will be signed correctly. If it were to be printed out // however then we would expect that it is IS reversed. Sha256Hash hash = Sha256Hash.twiceOf(bos.toByteArray()); bos.close(); return hash; } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } } public TransactionSignature calculateWitnessSignature( int inputIndex, ECKey key, byte[] scriptCode, Coin value, SigHash hashType, boolean anyoneCanPay) { Sha256Hash hash = hashForWitnessSignature(inputIndex, scriptCode, value, hashType, anyoneCanPay); return new TransactionSignature(key.sign(hash), hashType, anyoneCanPay); } public TransactionSignature calculateWitnessSignature( int inputIndex, ECKey key, Script scriptCode, Coin value, SigHash hashType, boolean anyoneCanPay) { return calculateWitnessSignature(inputIndex, key, scriptCode.program(), value, hashType, anyoneCanPay); } public TransactionSignature calculateWitnessSignature( int inputIndex, ECKey key, @Nullable AesKey aesKey, byte[] scriptCode, Coin value, SigHash hashType, boolean anyoneCanPay) { Sha256Hash hash = hashForWitnessSignature(inputIndex, scriptCode, value, hashType, anyoneCanPay); return new TransactionSignature(key.sign(hash, aesKey), hashType, anyoneCanPay); } public TransactionSignature calculateWitnessSignature( int inputIndex, ECKey key, @Nullable AesKey aesKey, Script scriptCode, Coin value, SigHash hashType, boolean anyoneCanPay) { return calculateWitnessSignature(inputIndex, key, aesKey, scriptCode.program(), value, hashType, anyoneCanPay); } public synchronized Sha256Hash hashForWitnessSignature( int inputIndex, byte[] scriptCode, Coin prevValue, SigHash type, boolean anyoneCanPay) { int sigHash = TransactionSignature.calcSigHashValue(type, anyoneCanPay); return hashForWitnessSignature(inputIndex, scriptCode, prevValue, (byte) sigHash); } /** * <p>Calculates a signature hash, that is, a hash of a simplified form of the transaction. How exactly the transaction * is simplified is specified by the type and anyoneCanPay parameters.</p> * * <p>This is a low level API and when using the regular {@link Wallet} class you don't have to call this yourself. * When working with more complex transaction types and contracts, it can be necessary. When signing a Witness output * the scriptCode should be the script encoded into the scriptSig field, for normal transactions, it's the * scriptPubKey of the output you're signing for. (See BIP143: https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki)</p> * * @param inputIndex input the signature is being calculated for. Tx signatures are always relative to an input. * @param scriptCode the script that should be in the given input during signing. * @param prevValue the value of the coin being spent * @param type Should be SigHash.ALL * @param anyoneCanPay should be false. */ public synchronized Sha256Hash hashForWitnessSignature( int inputIndex, Script scriptCode, Coin prevValue, SigHash type, boolean anyoneCanPay) { return hashForWitnessSignature(inputIndex, scriptCode.program(), prevValue, type, anyoneCanPay); } public synchronized Sha256Hash hashForWitnessSignature( int inputIndex, byte[] scriptCode, Coin prevValue, byte sigHashType){ ByteArrayOutputStream bos = new ByteArrayOutputStream(255); // just a guess at an average tx length try { byte[] hashPrevouts = new byte[32]; byte[] hashSequence = new byte[32]; byte[] hashOutputs = new byte[32]; int basicSigHashType = sigHashType & 0x1f; boolean anyoneCanPay = (sigHashType & SigHash.ANYONECANPAY.value) == SigHash.ANYONECANPAY.value; boolean signAll = (basicSigHashType != SigHash.SINGLE.value) && (basicSigHashType != SigHash.NONE.value); if (!anyoneCanPay) { ByteArrayOutputStream bosHashPrevouts = new ByteArrayOutputStream(256); for (TransactionInput input : this.inputs) { bosHashPrevouts.write(input.getOutpoint().hash().serialize()); writeInt32LE(input.getOutpoint().index(), bosHashPrevouts); } hashPrevouts = Sha256Hash.hashTwice(bosHashPrevouts.toByteArray()); } if (!anyoneCanPay && signAll) { ByteArrayOutputStream bosSequence = new ByteArrayOutputStream(256); for (TransactionInput input : this.inputs) { writeInt32LE(input.getSequenceNumber(), bosSequence); } hashSequence = Sha256Hash.hashTwice(bosSequence.toByteArray()); } if (signAll) { ByteArrayOutputStream bosHashOutputs = new ByteArrayOutputStream(256); for (TransactionOutput output : this.outputs) { writeInt64LE( BigInteger.valueOf(output.getValue().getValue()), bosHashOutputs ); bosHashOutputs.write(VarInt.of(output.getScriptBytes().length).serialize()); bosHashOutputs.write(output.getScriptBytes()); } hashOutputs = Sha256Hash.hashTwice(bosHashOutputs.toByteArray()); } else if (basicSigHashType == SigHash.SINGLE.value && inputIndex < outputs.size()) { ByteArrayOutputStream bosHashOutputs = new ByteArrayOutputStream(256); writeInt64LE( BigInteger.valueOf(this.outputs.get(inputIndex).getValue().getValue()), bosHashOutputs ); bosHashOutputs.write(VarInt.of(this.outputs.get(inputIndex).getScriptBytes().length).serialize()); bosHashOutputs.write(this.outputs.get(inputIndex).getScriptBytes()); hashOutputs = Sha256Hash.hashTwice(bosHashOutputs.toByteArray()); } writeInt32LE(version, bos); bos.write(hashPrevouts); bos.write(hashSequence); bos.write(inputs.get(inputIndex).getOutpoint().hash().serialize()); writeInt32LE(inputs.get(inputIndex).getOutpoint().index(), bos); bos.write(VarInt.of(scriptCode.length).serialize()); bos.write(scriptCode); writeInt64LE(BigInteger.valueOf(prevValue.getValue()), bos); writeInt32LE(inputs.get(inputIndex).getSequenceNumber(), bos); bos.write(hashOutputs); writeInt32LE(this.vLockTime.rawValue(), bos); writeInt32LE(0x000000ff & sigHashType, bos); } catch (IOException e) { throw new RuntimeException(e); // Cannot happen. } return Sha256Hash.twiceOf(bos.toByteArray()); } @Override public int messageSize() { boolean useSegwit = hasWitnesses() && allowWitness(protocolVersion); int size = 4; // version if (useSegwit) size += 2; // marker, flag size += VarInt.sizeOf(inputs.size()); for (TransactionInput in : inputs) size += in.getMessageSize(); size += VarInt.sizeOf(outputs.size()); for (TransactionOutput out : outputs) size += out.getMessageSize(); if (useSegwit) for (TransactionInput in : inputs) size += in.getWitness().getMessageSize(); size += 4; // locktime return size; } @Override protected void bitcoinSerializeToStream(OutputStream stream) throws IOException { boolean useSegwit = hasWitnesses() && allowWitness(protocolVersion); bitcoinSerializeToStream(stream, useSegwit); } /** * Serialize according to <a href="https://github.com/bitcoin/bips/blob/master/bip-0144.mediawiki">BIP144</a> or the * <a href="https://en.bitcoin.it/wiki/Protocol_documentation#tx">classic format</a>, depending on if segwit is * desired. */ protected void bitcoinSerializeToStream(OutputStream stream, boolean useSegwit) throws IOException { // version writeInt32LE(version, stream); // marker, flag if (useSegwit) { stream.write(0); stream.write(1); } // txin_count, txins stream.write(VarInt.of(inputs.size()).serialize()); for (TransactionInput in : inputs) stream.write(in.serialize()); // txout_count, txouts stream.write(VarInt.of(outputs.size()).serialize()); for (TransactionOutput out : outputs) stream.write(out.serialize()); // script_witnisses if (useSegwit) { for (TransactionInput in : inputs) stream.write(in.getWitness().serialize()); } // lock_time writeInt32LE(vLockTime.rawValue(), stream); } /** * Transactions can have an associated lock time, specified either as a block height or as a timestamp (in seconds * since epoch). A transaction is not allowed to be confirmed by miners until the lock time is reached, and * since Bitcoin 0.8+ a transaction that did not end its lock period (non final) is considered to be non * standard and won't be relayed or included in the memory pool either. * @return lock time, wrapped in a {@link LockTime} */ public LockTime lockTime() { return vLockTime; } /** @deprecated use {@link #lockTime()} */ @Deprecated public long getLockTime() { return lockTime().rawValue(); } /** * Transactions can have an associated lock time, specified either as a block height or as a timestamp (in seconds * since epoch). A transaction is not allowed to be confirmed by miners until the lock time is reached, and * since Bitcoin 0.8+ a transaction that did not end its lock period (non final) is considered to be non * standard and won't be relayed or included in the memory pool either. */ public void setLockTime(long lockTime) { boolean seqNumSet = false; for (TransactionInput input : inputs) { if (input.getSequenceNumber() != TransactionInput.NO_SEQUENCE) { seqNumSet = true; break; } } if (lockTime != 0 && (!seqNumSet || inputs.isEmpty())) { // At least one input must have a non-default sequence number for lock times to have any effect. // For instance one of them can be set to zero to make this feature work. log.warn("You are setting the lock time on a transaction but none of the inputs have non-default sequence numbers. This will not do what you expect!"); } this.vLockTime = LockTime.of(lockTime); } public long getVersion() { return version; } public void setVersion(int version) { this.version = version; } /** Returns an unmodifiable view of all inputs. */ public List<TransactionInput> getInputs() { return Collections.unmodifiableList(inputs); } /** Returns an unmodifiable view of all outputs. */ public List<TransactionOutput> getOutputs() { return Collections.unmodifiableList(outputs); } /** * <p>Returns the list of transacion outputs, whether spent or unspent, that match a wallet by address or that are * watched by a wallet, i.e., transaction outputs whose script's address is controlled by the wallet and transaction * outputs whose script is watched by the wallet.</p> * * @param transactionBag The wallet that controls addresses and watches scripts. * @return linked list of outputs relevant to the wallet in this transaction */ public List<TransactionOutput> getWalletOutputs(TransactionBag transactionBag){ List<TransactionOutput> walletOutputs = new LinkedList<>(); for (TransactionOutput o : outputs) { if (!o.isMineOrWatched(transactionBag)) continue; walletOutputs.add(o); } return walletOutputs; } /** Randomly re-orders the transaction outputs: good for privacy */ public void shuffleOutputs() { Collections.shuffle(outputs); } /** Same as getInputs().get(index). */ public TransactionInput getInput(long index) { return inputs.get((int)index); } /** Same as getOutputs().get(index) */ public TransactionOutput getOutput(long index) { return outputs.get((int)index); } /** * Gets the output the gihven outpoint is referring to. Note the output must belong to this transaction, or else * an {@link IllegalArgumentException} will occur. * * @param outpoint outpoint referring to the output to get * @return output referred to by the given outpoint */ public TransactionOutput getOutput(TransactionOutPoint outpoint) { checkArgument(outpoint.hash().equals(this.getTxId()), () -> "outpoint poins to a different transaction"); return getOutput(outpoint.index()); } /** * Returns the confidence object for this transaction from the {@link TxConfidenceTable} * referenced by the implicit {@link Context}. */ public TransactionConfidence getConfidence() { return getConfidence(Context.get()); } /** * Returns the confidence object for this transaction from the {@link TxConfidenceTable} * referenced by the given {@link Context}. */ public TransactionConfidence getConfidence(Context context) { return getConfidence(context.getConfidenceTable()); } /** * Returns the confidence object for this transaction from the {@link TxConfidenceTable} */ public TransactionConfidence getConfidence(TxConfidenceTable table) { if (confidence == null) confidence = table.getOrCreate(getTxId()) ; return confidence; } /** Check if the transaction has a known confidence */ public boolean hasConfidence() { return getConfidence().getConfidenceType() != TransactionConfidence.ConfidenceType.UNKNOWN; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return getTxId().equals(((Transaction)o).getTxId()); } @Override public int hashCode() { return getTxId().hashCode(); } /** * Gets the count of regular SigOps in this transactions */ public int getSigOpCount() throws ScriptException { int sigOps = 0; for (TransactionInput input : inputs) sigOps += Script.getSigOpCount(input.getScriptBytes()); for (TransactionOutput output : outputs) sigOps += Script.getSigOpCount(output.getScriptBytes()); return sigOps; } /** * Check block height is in coinbase input script, for use after BIP 34 * enforcement is enabled. */ public void checkCoinBaseHeight(final int height) throws VerificationException { checkArgument(height >= Block.BLOCK_HEIGHT_GENESIS); checkState(isCoinBase()); // Check block height is in coinbase input script final TransactionInput in = this.getInput(0); final ScriptBuilder builder = new ScriptBuilder(); builder.number(height); final byte[] expected = builder.build().program(); final byte[] actual = in.getScriptBytes(); if (actual.length < expected.length) { throw new VerificationException.CoinbaseHeightMismatch("Block height mismatch in coinbase."); } for (int scriptIdx = 0; scriptIdx < expected.length; scriptIdx++) { if (actual[scriptIdx] != expected[scriptIdx]) { throw new VerificationException.CoinbaseHeightMismatch("Block height mismatch in coinbase."); } } } /** Loops the outputs of a coinbase transaction to locate the witness commitment. */ public Sha256Hash findWitnessCommitment() { checkState(isCoinBase()); List<TransactionOutput> reversed = new ArrayList<>(outputs); Collections.reverse(reversed); return reversed.stream() .map(TransactionOutput::getScriptPubKey) .filter(ScriptPattern::isWitnessCommitment) .findFirst() .map(ScriptPattern::extractWitnessCommitmentHash) .orElse(null); } /** * <p>A transaction is time-locked if at least one of its inputs is non-final and it has a lock time. A transaction can * also have a relative lock time which this method doesn't tell. Use {@link #hasRelativeLockTime()} to find out.</p> * * <p>To check if this transaction is final at a given height and time, see {@link Transaction#isFinal(int, long)} * </p> */ public boolean isTimeLocked() { if (!lockTime().isSet()) return false; for (TransactionInput input : getInputs()) if (input.hasSequence()) return true; return false; } /** * A transaction has a relative lock time * (<a href="https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki">BIP 68</a>) if it is version 2 or * higher and at least one of its inputs has its {@link TransactionInput#SEQUENCE_LOCKTIME_DISABLE_FLAG} cleared. */ public boolean hasRelativeLockTime() { if (version < 2) return false; for (TransactionInput input : getInputs()) if (input.hasRelativeLockTime()) return true; return false; } /** * Returns whether this transaction will opt into the * <a href="https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki">full replace-by-fee </a> semantics. */ public boolean isOptInFullRBF() { for (TransactionInput input : getInputs()) if (input.isOptInFullRBF()) return true; return false; } /** * <p>Returns true if this transaction is considered finalized and can be placed in a block. Non-finalized * transactions won't be included by miners and can be replaced with newer versions using sequence numbers. * This is useful in certain types of <a href="http://en.bitcoin.it/wiki/Contracts">contracts</a>, such as * micropayment channels.</p> * * <p>Note that currently the replacement feature is disabled in Bitcoin Core and will need to be * re-activated before this functionality is useful.</p> */ public boolean isFinal(int height, long blockTimeSeconds) { LockTime locktime = lockTime(); return locktime.rawValue() < (locktime instanceof HeightLock ? height : blockTimeSeconds) || !isTimeLocked(); } /** * Returns either the lock time, if it was specified as a timestamp, or an estimate based on the time in * the current head block if it was specified as a block height. */ public Instant estimateUnlockTime(AbstractBlockChain chain) { LockTime locktime = lockTime(); return locktime instanceof HeightLock ? chain.estimateBlockTimeInstant(((HeightLock) locktime).blockHeight()) : ((TimeLock) locktime).timestamp(); } /** @deprecated use {@link #estimateUnlockTime(AbstractBlockChain)} */ @Deprecated public Date estimateLockTime(AbstractBlockChain chain) { return Date.from(estimateUnlockTime(chain)); } /** * Returns the purpose for which this transaction was created. See the javadoc for {@link Purpose} for more * information on the point of this field and what it can be. */ public Purpose getPurpose() { return purpose; } /** * Marks the transaction as being created for the given purpose. See the javadoc for {@link Purpose} for more * information on the point of this field and what it can be. */ public void setPurpose(Purpose purpose) { this.purpose = purpose; } /** * Getter for {@link #exchangeRate}. */ @Nullable public ExchangeRate getExchangeRate() { return exchangeRate; } /** * Setter for {@link #exchangeRate}. */ public void setExchangeRate(ExchangeRate exchangeRate) { this.exchangeRate = exchangeRate; } /** * Returns the transaction {@link #memo}. */ @Nullable public String getMemo() { return memo; } /** * Set the transaction {@link #memo}. It can be used to record the memo of the payment request that initiated the * transaction. */ public void setMemo(String memo) { this.memo = memo; } /** * <p>Checks the transaction contents for sanity, in ways that can be done in a standalone manner. * Does <b>not</b> perform all checks on a transaction such as whether the inputs are already spent. * Specifically this method verifies:</p> * * <ul> * <li>That there is at least one input and output.</li> * <li>That the serialized size is not larger than the max block size.</li> * <li>That no outputs have negative value.</li> * <li>That the outputs do not sum to larger than the max allowed quantity of coin in the system.</li> * <li>If the tx is a coinbase tx, the coinbase scriptSig size is within range. Otherwise that there are no * coinbase inputs in the tx.</li> * </ul> * * @param network network for the verification rules * @param tx transaction to verify * @throws VerificationException if at least one of the rules is violated */ public static void verify(Network network, Transaction tx) throws VerificationException { if (tx.inputs.size() == 0 || tx.outputs.size() == 0) throw new VerificationException.EmptyInputsOrOutputs(); if (tx.messageSize() > Block.MAX_BLOCK_SIZE) throw new VerificationException.LargerThanMaxBlockSize(); HashSet<TransactionOutPoint> outpoints = new HashSet<>(); for (TransactionInput input : tx.inputs) { if (outpoints.contains(input.getOutpoint())) throw new VerificationException.DuplicatedOutPoint(); outpoints.add(input.getOutpoint()); } Coin valueOut = Coin.ZERO; for (TransactionOutput output : tx.outputs) { Coin value = output.getValue(); if (value.signum() < 0) throw new VerificationException.NegativeValueOutput(); try { valueOut = valueOut.add(value); } catch (ArithmeticException e) { throw new VerificationException.ExcessiveValue(); } if (network.exceedsMaxMoney(valueOut)) throw new VerificationException.ExcessiveValue(); } if (tx.isCoinBase()) { if (tx.inputs.get(0).getScriptBytes().length < 2 || tx.inputs.get(0).getScriptBytes().length > 100) throw new VerificationException.CoinbaseScriptSizeOutOfRange(); } else { for (TransactionInput input : tx.inputs) if (input.isCoinBase()) throw new VerificationException.UnexpectedCoinbaseInput(); } } /** * @deprecated use {@link #verify(Network, Transaction)} */ @Deprecated public static void verify(NetworkParameters params, Transaction tx) throws VerificationException { verify(params.network(), tx); } }
84,453
44.650811
163
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/NetworkParameters.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Address; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.base.LegacyAddress; import org.bitcoinj.base.Network; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.crypto.DumpedPrivateKey; import org.bitcoinj.params.BitcoinNetworkParams; import org.bitcoinj.params.Networks; import org.bitcoinj.protocols.payments.PaymentProtocol; import org.bitcoinj.script.Script; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.base.utils.MonetaryFormat; import org.bitcoinj.utils.VersionTally; import javax.annotation.Nullable; import java.math.BigInteger; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * <p>NetworkParameters contains the data needed for working with an instantiation of a Bitcoin chain.</p> * * <p>This is an abstract class, concrete instantiations can be found in the params package. There are four: * one for the main network ({@link org.bitcoinj.params.MainNetParams}), one for the public test network, and two others that are * intended for unit testing and local app development purposes. Although this class contains some aliases for * them, you are encouraged to call the static get() methods on each specific params class directly.</p> */ public abstract class NetworkParameters { /** The string used by the payment protocol to represent the main net. */ @Deprecated public static final String PAYMENT_PROTOCOL_ID_MAINNET = PaymentProtocol.PAYMENT_PROTOCOL_ID_MAINNET; /** The string used by the payment protocol to represent the test net. */ @Deprecated public static final String PAYMENT_PROTOCOL_ID_TESTNET = PaymentProtocol.PAYMENT_PROTOCOL_ID_TESTNET; /** The string used by the payment protocol to represent signet (note that this is non-standard). */ @Deprecated public static final String PAYMENT_PROTOCOL_ID_SIGNET = PaymentProtocol.PAYMENT_PROTOCOL_ID_SIGNET; /** The string used by the payment protocol to represent unit testing (note that this is non-standard). */ @Deprecated public static final String PAYMENT_PROTOCOL_ID_UNIT_TESTS = PaymentProtocol.PAYMENT_PROTOCOL_ID_UNIT_TESTS; @Deprecated public static final String PAYMENT_PROTOCOL_ID_REGTEST = PaymentProtocol.PAYMENT_PROTOCOL_ID_REGTEST; // TODO: Seed nodes should be here as well. protected BigInteger maxTarget; protected int port; protected int packetMagic; // Indicates message origin network and is used to seek to the next message when stream state is unknown. protected int addressHeader; protected int p2shHeader; protected int dumpedPrivateKeyHeader; protected String segwitAddressHrp; protected int interval; protected int targetTimespan; protected int bip32HeaderP2PKHpub; protected int bip32HeaderP2PKHpriv; protected int bip32HeaderP2WPKHpub; protected int bip32HeaderP2WPKHpriv; /** Used to check majorities for block version upgrade */ protected int majorityEnforceBlockUpgrade; protected int majorityRejectBlockOutdated; protected int majorityWindow; /** * See getId() */ protected final String id; protected final Network network; /** * The depth of blocks required for a coinbase transaction to be spendable. */ protected int spendableCoinbaseDepth; protected int subsidyDecreaseBlockCount; protected String[] dnsSeeds; protected int[] addrSeeds; protected Map<Integer, Sha256Hash> checkpoints = new HashMap<>(); protected volatile transient MessageSerializer defaultSerializer = null; protected NetworkParameters(Network network) { this.network = network; this.id = network.id(); } public static final int TARGET_TIMESPAN = 14 * 24 * 60 * 60; // 2 weeks per difficulty cycle, on average. public static final int TARGET_SPACING = 10 * 60; // 10 minutes per block. public static final int INTERVAL = TARGET_TIMESPAN / TARGET_SPACING; /** * Blocks with a timestamp after this should enforce BIP 16, aka "Pay to script hash". This BIP changed the * network rules in a soft-forking manner, that is, blocks that don't follow the rules are accepted but not * mined upon and thus will be quickly re-orged out as long as the majority are enforcing the rule. */ public static final int BIP16_ENFORCE_TIME = 1333238400; /** * The maximum number of coins to be generated * @deprecated Use {@link BitcoinNetwork#MAX_MONEY} */ @Deprecated public static final long MAX_COINS = BitcoinNetwork.MAX_MONEY.longValue(); /** * The maximum money to be generated * @deprecated Use {@link BitcoinNetwork#MAX_MONEY} */ @Deprecated public static final Coin MAX_MONEY = BitcoinNetwork.MAX_MONEY; /** * A Java package style string acting as unique ID for these parameters * @return network id string */ public String getId() { return id; } /** * @return Network enum for this network */ public Network network() { return network; } /** * @return the payment protocol network id string * @deprecated Use {@link PaymentProtocol#protocolIdFromParams(NetworkParameters)} */ @Deprecated public abstract String getPaymentProtocolId(); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return getId().equals(((NetworkParameters)o).getId()); } @Override public int hashCode() { return Objects.hash(getId()); } /** * Return network parameters for a network id * @param id the network id * @return the network parameters for the given string ID or NULL if not recognized * @deprecated Use {@link BitcoinNetworkParams#fromID(String)} */ @Deprecated @Nullable public static NetworkParameters fromID(String id) { return BitcoinNetworkParams.fromID(id); } /** * Return network parameters for a {@link Network}. * <p> * Alternative networks will be found if they have been registered with {@link Networks} registry. * @param network the network * @return the network parameters for the given string ID * @throws IllegalArgumentException if unknown network */ public static NetworkParameters of(Network network) { return (network instanceof BitcoinNetwork) ? BitcoinNetworkParams.of((BitcoinNetwork) network) : Networks.find(network).orElseThrow(() -> new IllegalArgumentException("Unknown network")); } /** * Return network parameters for a paymentProtocol ID string * @param pmtProtocolId paymentProtocol ID string * @return network parameters for the given string paymentProtocolID or NULL if not recognized * @deprecated Use {@link PaymentProtocol#paramsFromPmtProtocolID(String)} (String)} */ @Nullable @Deprecated public static NetworkParameters fromPmtProtocolID(String pmtProtocolId) { return PaymentProtocol.paramsFromPmtProtocolID(pmtProtocolId); } /** * Get a NetworkParameters from an Address. * Addresses should not be used for storing NetworkParameters. In the future Address will * be an {@code interface} that only makes a {@link Network} available. * @param address An address * @return network parameters * @deprecated You should be using {@link Address#network()} instead */ @Deprecated public static NetworkParameters fromAddress(Address address) { return address.getParameters(); } public int getSpendableCoinbaseDepth() { return spendableCoinbaseDepth; } /** * Throws an exception if the block's difficulty is not correct. * * @param storedPrev previous stored block * @param next proposed block * @param blockStore active BlockStore * @throws VerificationException if the block's difficulty is not correct. * @throws BlockStoreException if an error occurred accessing the BlockStore */ public abstract void checkDifficultyTransitions(StoredBlock storedPrev, Block next, final BlockStore blockStore) throws VerificationException, BlockStoreException; /** * Validate the hash for a given block height against checkpoints * @param height block height * @param hash hash for {@code height} * @return true if the block height is either not a checkpoint, or is a checkpoint and the hash matches */ public boolean passesCheckpoint(int height, Sha256Hash hash) { Sha256Hash checkpointHash = checkpoints.get(height); return checkpointHash == null || checkpointHash.equals(hash); } /** * Is height a checkpoint * @param height block height * @return true if the given height has a recorded checkpoint */ public boolean isCheckpoint(int height) { Sha256Hash checkpointHash = checkpoints.get(height); return checkpointHash != null; } public int getSubsidyDecreaseBlockCount() { return subsidyDecreaseBlockCount; } /** * Return DNS names that when resolved, give IP addresses of active peers * @return an array of DNS names */ public String[] getDnsSeeds() { return dnsSeeds; } /** * Return IP addresses of active peers * @return array of IP addresses */ public int[] getAddrSeeds() { return addrSeeds; } /** * <p>Genesis block for this chain.</p> * * <p>The first block in every chain is a well known constant shared between all Bitcoin implementations. For a * block to be valid, it must be eventually possible to work backwards to the genesis block by following the * prevBlockHash pointers in the block headers.</p> * * <p>The genesis blocks for both test and main networks contain the timestamp of when they were created, * and a message in the coinbase transaction. It says, <i>"The Times 03/Jan/2009 Chancellor on brink of second * bailout for banks"</i>.</p> * @return genesis block */ public abstract Block getGenesisBlock(); /** * Default TCP port on which to connect to nodes * @return default port for this network */ public int getPort() { return port; } /** * The header bytes that identify the start of a packet on this network. * @return header bytes as a long */ public int getPacketMagic() { return packetMagic; } /** * First byte of a base58 encoded address. See {@link LegacyAddress}. * @return the header value */ @Deprecated public int getAddressHeader() { return addressHeader; } /** * First byte of a base58 encoded P2SH address. P2SH addresses are defined as part of BIP0013. * @return the header value */ @Deprecated public int getP2SHHeader() { return p2shHeader; } /** * First byte of a base58 encoded dumped private key. See {@link DumpedPrivateKey}. * @return the header value */ public int getDumpedPrivateKeyHeader() { return dumpedPrivateKeyHeader; } /** * Human-readable part of bech32 encoded segwit address. * @return the human-readable part value * @deprecated Use {@link Network#segwitAddressHrp()} or {@link org.bitcoinj.base.SegwitAddress.SegwitHrp} */ @Deprecated public String getSegwitAddressHrp() { return segwitAddressHrp; } /** * How much time in seconds is supposed to pass between "interval" blocks. If the actual elapsed time is * significantly different from this value, the network difficulty formula will produce a different value. Both * test and main Bitcoin networks use 2 weeks (1209600 seconds). * @return target timespan in seconds */ public int getTargetTimespan() { return targetTimespan; } /** * If we are running in testnet-in-a-box mode, we allow connections to nodes with 0 non-genesis blocks. * @return true if allowed */ public boolean allowEmptyPeerChain() { return true; } /** * How many blocks pass between difficulty adjustment periods. Bitcoin standardises this to be 2016. * @return number of blocks */ public int getInterval() { return interval; } /** * Maximum target represents the easiest allowable proof of work. * @return maximum target integer */ public BigInteger getMaxTarget() { return maxTarget; } /** * Returns the 4 byte header for BIP32 wallet P2PKH - public key part. * @return the header value */ public int getBip32HeaderP2PKHpub() { return bip32HeaderP2PKHpub; } /** * Returns the 4 byte header for BIP32 wallet P2PKH - private key part. * @return the header value */ public int getBip32HeaderP2PKHpriv() { return bip32HeaderP2PKHpriv; } /** * Returns the 4 byte header for BIP32 wallet P2WPKH - public key part. * @return the header value */ public int getBip32HeaderP2WPKHpub() { return bip32HeaderP2WPKHpub; } /** * Returns the 4 byte header for BIP32 wallet P2WPKH - private key part. * @return the header value */ public int getBip32HeaderP2WPKHpriv() { return bip32HeaderP2WPKHpriv; } /** * Returns the number of coins that will be produced in total, on this * network. Where not applicable, a very large number of coins is returned * instead (e.g. the main coin issue for Dogecoin). * @return maximum number of coins for this network * @deprecated Use {@link Network#maxMoney()} */ @Deprecated public abstract Coin getMaxMoney(); /** * The monetary object for this currency. * @return formatting utility object * @deprecated Get one another way or construct your own {@link MonetaryFormat} as needed. */ @Deprecated public abstract MonetaryFormat getMonetaryFormat(); /** * Scheme part for URIs, for example "bitcoin". * @return a string with the "scheme" part * @deprecated Use {@link Network#uriScheme()} */ @Deprecated public abstract String getUriScheme(); /** * Returns whether this network has a maximum number of coins (finite supply) or * not. Always returns true for Bitcoin, but exists to be overridden for other * networks. * @return true if network has a fixed maximum number of coins * @deprecated Use {@link Network#hasMaxMoney()} */ @Deprecated public abstract boolean hasMaxMoney(); /** * Return the default serializer for this network. This is a shared serializer. * @return the default serializer for this network. */ 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(); } } } return defaultSerializer; } /** * Construct and return a custom serializer. * @return the serializer */ public abstract BitcoinSerializer getSerializer(); /** * The number of blocks in the last {@link #getMajorityWindow()} blocks * at which to trigger a notice to the user to upgrade their client, where * the client does not understand those blocks. * @return number of blocks */ public int getMajorityEnforceBlockUpgrade() { return majorityEnforceBlockUpgrade; } /** * The number of blocks in the last {@link #getMajorityWindow()} blocks * at which to enforce the requirement that all new blocks are of the * newer type (i.e. outdated blocks are rejected). * @return number of blocks */ public int getMajorityRejectBlockOutdated() { return majorityRejectBlockOutdated; } /** * The sampling window from which the version numbers of blocks are taken * in order to determine if a new block version is now the majority. * @return number of blocks */ public int getMajorityWindow() { return majorityWindow; } /** * 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. * @param tally caching tally counter * @return the 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 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 tally caching tally counter * @param height height of the block, if known, null otherwise. Returned * tests should be a safe subset if block height is unknown. * @return the flags */ 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; } /** * @deprecated use {@link ProtocolVersion#intValue()} */ @Deprecated public int getProtocolVersionNum(final ProtocolVersion version) { return version.intValue(); } }
20,273
35.139037
167
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/VersionMessage.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import com.google.common.net.InetAddresses; import org.bitcoinj.base.VarInt; import org.bitcoinj.base.internal.Buffers; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.base.internal.ByteUtils; import javax.annotation.Nullable; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Locale; import java.util.Objects; import static org.bitcoinj.base.internal.Preconditions.check; /** * <p>A VersionMessage holds information exchanged during connection setup with another peer. Most of the fields are not * particularly interesting. The subVer field, since BIP 14, acts as a User-Agent string would. You can and should * append to or change the subVer for your own software so other implementations can identify it, and you can look at * the subVer field received from other nodes to see what they are running.</p> * * <p>After creating yourself a VersionMessage, you can pass it to {@link PeerGroup#setVersionMessage(VersionMessage)} * to ensure it will be used for each new connection.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public class VersionMessage extends BaseMessage { /** The version of this library release, as a string. */ public static final String BITCOINJ_VERSION = "0.17-SNAPSHOT"; /** The value that is prepended to the subVer field of this application. */ public static final String LIBRARY_SUBVER = "/bitcoinj:" + BITCOINJ_VERSION + "/"; /** * The version number of the protocol spoken. */ public int clientVersion; /** * Flags defining what optional services are supported. */ public Services localServices; /** * What the other side believes the current time to be. */ public Instant time; /** * The services supported by the receiving node as perceived by the transmitting node. */ public Services receivingServices; /** * The network address of the receiving node as perceived by the transmitting node */ public InetSocketAddress receivingAddr; /** * User-Agent as defined in <a href="https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki">BIP 14</a>. * Bitcoin Core sets it to something like "/Satoshi:0.9.1/". */ public String subVer; /** * How many blocks are in the chain, according to the other side. */ public long bestHeight; /** * Whether or not to relay tx invs before a filter is received. * See <a href="https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki#extensions-to-existing-messages">BIP 37</a>. */ public boolean relayTxesBeforeFilter; private static final int NETADDR_BYTES = Services.BYTES + /* IPv6 */ 16 + /* port */ Short.BYTES; /** * Deserialize this message from a given payload. * * @param payload payload to deserialize from * @return read message * @throws BufferUnderflowException if the read message extends beyond the remaining bytes of the payload */ public static VersionMessage read(ByteBuffer payload) throws BufferUnderflowException, ProtocolException { int clientVersion = (int) ByteUtils.readUint32(payload); check(clientVersion >= ProtocolVersion.MINIMUM.intValue(), ProtocolException::new); Services localServices = Services.read(payload); Instant time = Instant.ofEpochSecond(ByteUtils.readInt64(payload)); Services receivingServices = Services.read(payload); InetAddress receivingInetAddress = PeerAddress.getByAddress(Buffers.readBytes(payload, 16)); int receivingPort = ByteUtils.readUint16BE(payload); InetSocketAddress receivingAddr = new InetSocketAddress(receivingInetAddress, receivingPort); Buffers.skipBytes(payload, NETADDR_BYTES); // addr_from // uint64 localHostNonce (random data) // We don't care about the localhost nonce. It's used to detect connecting back to yourself in cases where // there are NATs and proxies in the way. However we don't listen for inbound connections so it's // irrelevant. Buffers.skipBytes(payload, 8); // string subVer (currently "") String subVer = Buffers.readLengthPrefixedString(payload); // int bestHeight (size of known block chain). long bestHeight = ByteUtils.readUint32(payload); boolean relayTxesBeforeFilter = clientVersion >= ProtocolVersion.BLOOM_FILTER.intValue() ? payload.get() != 0 : true; return new VersionMessage(clientVersion, localServices, time, receivingServices, receivingAddr, subVer, bestHeight, relayTxesBeforeFilter); } /** * Construct own version message from given {@link NetworkParameters} and our best height of the chain. * * @param params network parameters to construct own version message from * @param bestHeight our best height to announce */ public VersionMessage(NetworkParameters params, int bestHeight) { this.clientVersion = ProtocolVersion.CURRENT.intValue(); this.localServices = Services.none(); this.time = TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS); InetAddress localhost = InetAddresses.forString("127.0.0.1"); this.receivingServices = Services.none(); this.receivingAddr = new InetSocketAddress(localhost, params.getPort()); this.subVer = LIBRARY_SUBVER; this.bestHeight = bestHeight; this.relayTxesBeforeFilter = true; } private VersionMessage(int clientVersion, Services localServices, Instant time, Services receivingServices, InetSocketAddress receivingAddr, String subVer, long bestHeight, boolean relayTxesBeforeFilter) { this.clientVersion = clientVersion; this.localServices = localServices; this.time = time; this.receivingServices = receivingServices; this.receivingAddr = receivingAddr; this.subVer = subVer; this.bestHeight = bestHeight; this.relayTxesBeforeFilter = relayTxesBeforeFilter; } /** * Gets the client version. * * @return client version */ public int clientVersion() { return clientVersion; } /** * Get the service bitfield that represents the node services being provided. * * @return service bitfield */ public Services services() { return localServices; } @Override public void bitcoinSerializeToStream(OutputStream buf) throws IOException { ByteUtils.writeInt32LE(clientVersion, buf); buf.write(localServices.serialize()); ByteUtils.writeInt64LE(time.getEpochSecond(), buf); buf.write(receivingServices.serialize()); buf.write(PeerAddress.mapIntoIPv6(receivingAddr.getAddress().getAddress())); ByteUtils.writeInt16BE(receivingAddr.getPort(), buf); buf.write(new byte[NETADDR_BYTES]); // addr_from // Next up is the "local host nonce", this is to detect the case of connecting // back to yourself. We don't care about this as we won't be accepting inbound // connections. ByteUtils.writeInt32LE(0, buf); ByteUtils.writeInt32LE(0, buf); // Now comes subVer. byte[] subVerBytes = subVer.getBytes(StandardCharsets.UTF_8); buf.write(VarInt.of(subVerBytes.length).serialize()); buf.write(subVerBytes); // Size of known block chain. ByteUtils.writeInt32LE(bestHeight, buf); buf.write(relayTxesBeforeFilter ? 1 : 0); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; VersionMessage other = (VersionMessage) o; return other.bestHeight == bestHeight && other.clientVersion == clientVersion && other.localServices == localServices && other.time.equals(time) && other.subVer.equals(subVer) && other.receivingServices.equals(receivingServices) && other.receivingAddr.equals(receivingAddr) && other.relayTxesBeforeFilter == relayTxesBeforeFilter; } @Override public int hashCode() { return Objects.hash(bestHeight, clientVersion, localServices, time, subVer, receivingServices, receivingAddr, relayTxesBeforeFilter); } @Override public String toString() { StringBuilder builder = new StringBuilder("\n"); builder.append("client version: ").append(clientVersion).append("\n"); if (localServices.hasAny()) builder.append("local services: ").append(localServices); builder.append("\n"); builder.append("time: ").append(TimeUtils.dateTimeFormat(time)).append("\n"); builder.append("receiving svc: ").append(receivingServices).append("\n"); builder.append("receiving addr: ").append(receivingAddr).append("\n"); builder.append("sub version: ").append(subVer).append("\n"); builder.append("best height: ").append(bestHeight).append("\n"); builder.append("delay tx relay: ").append(!relayTxesBeforeFilter).append("\n"); return builder.toString(); } public VersionMessage duplicate() { return new VersionMessage(clientVersion, localServices, time, receivingServices, receivingAddr, subVer, bestHeight, relayTxesBeforeFilter); } /** * <p>Appends the given user-agent information to the subVer field. The subVer is composed of a series of * name:version pairs separated by slashes in the form of a path. For example a typical subVer field for bitcoinj * users might look like "/bitcoinj:0.13/MultiBit:1.2/" where libraries come further to the left.</p> * * <p>There can be as many components as you feel a need for, and the version string can be anything, but it is * recommended to use A.B.C where A = major, B = minor and C = revision for software releases, and dates for * auto-generated source repository snapshots. A valid subVer begins and ends with a slash, therefore name * and version are not allowed to contain such characters.</p> * * <p>Anything put in the "comments" field will appear in brackets and may be used for platform info, or anything * else. For example, calling {@code appendToSubVer("MultiBit", "1.0", "Windows")} will result in a subVer being * set of "/bitcoinj:1.0/MultiBit:1.0(Windows)/". Therefore the / ( and ) characters are reserved in all these * components. If you don't want to add a comment (recommended), pass null.</p> * * <p>See <a href="https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki">BIP 14</a> for more information.</p> * * @param comments Optional (can be null) platform or other node specific information. * @throws IllegalArgumentException if name, version or comments contains invalid characters. */ public void appendToSubVer(String name, String version, @Nullable String comments) { checkSubVerComponent(name); checkSubVerComponent(version); if (comments != null) { checkSubVerComponent(comments); subVer = subVer.concat(String.format(Locale.US, "%s:%s(%s)/", name, version, comments)); } else { subVer = subVer.concat(String.format(Locale.US, "%s:%s/", name, version)); } } private static void checkSubVerComponent(String component) { if (component.contains("/") || component.contains("(") || component.contains(")")) throw new IllegalArgumentException("name contains invalid characters"); } /** @deprecated just assume {@link Ping} and {@link Pong} are supported */ @Deprecated public boolean isPingPongSupported() { return true; } }
12,859
44.122807
127
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/EmptyMessage.java
/* * Copyright 2011 Steve Coughlan. * Copyright 2015 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import java.io.IOException; import java.io.OutputStream; /** * <p>Parent class for header only messages that don't have a payload. * Currently this includes getaddr, verack and special bitcoinj class UnknownMessage.</p> * * <p>Instances of this class are not safe for use by multiple threads.</p> */ public abstract class EmptyMessage extends BaseMessage { public EmptyMessage() { super(); } @Override public final int messageSize() { return 0; } @Override protected final void bitcoinSerializeToStream(OutputStream stream) throws IOException { } }
1,271
27.909091
91
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/UTXO.java
/* * Copyright 2012 Matt Corallo. * Copyright 2021 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.script.Script; import java.math.BigInteger; import java.util.Locale; import java.util.Objects; // TODO: Fix this class: should not talk about addresses, height should be optional/support mempool height etc /** * A UTXO message contains the information necessary to check a spending transaction. * It avoids having to store the entire parentTransaction just to get the hash and index. * Useful when working with freestanding outputs. */ public class UTXO { private final Coin value; private final Script script; private final Sha256Hash hash; private final long index; private final int height; private final boolean coinbase; private final String address; /** * Creates a stored transaction output. * * @param hash The hash of the containing transaction. * @param index The outpoint. * @param value The value available. * @param height The height this output was created in. * @param coinbase The coinbase flag. */ public UTXO(Sha256Hash hash, long index, Coin value, int height, boolean coinbase, Script script) { this(hash, index, value, height, coinbase, script, ""); } /** * Creates a stored transaction output. * * @param hash The hash of the containing transaction. * @param index The outpoint. * @param value The value available. * @param height The height this output was created in. * @param coinbase The coinbase flag. * @param address The address. */ public UTXO(Sha256Hash hash, long index, Coin value, int height, boolean coinbase, Script script, String address) { this.hash = Objects.requireNonNull(hash); this.index = index; this.value = Objects.requireNonNull(value); this.height = height; this.script = script; this.coinbase = coinbase; this.address = address; } /** The value which this Transaction output holds. */ public Coin getValue() { return value; } /** The Script object which you can use to get address, script bytes or script type. */ public Script getScript() { return script; } /** The hash of the transaction which holds this output. */ public Sha256Hash getHash() { return hash; } /** The index of this output in the transaction which holds it. */ public long getIndex() { return index; } /** Gets the height of the block that created this output. */ public int getHeight() { return height; } /** Gets the flag of whether this was created by a coinbase tx. */ public boolean isCoinbase() { return coinbase; } /** The address of this output, can be the empty string if none was provided at construction time or was deserialized */ public String getAddress() { return address; } @Override public String toString() { return String.format(Locale.US, "Stored TxOut of %s (%s:%d)", value.toFriendlyString(), hash, index); } @Override public int hashCode() { return Objects.hash(getIndex(), getHash(), getValue()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UTXO other = (UTXO) o; return getIndex() == other.getIndex() && getHash().equals(other.getHash()) && getValue().equals(((UTXO) o).getValue()); } }
4,460
30.415493
127
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/PrunedException.java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; // TODO: Rename PrunedException to something like RequiredDataWasPrunedException import org.bitcoinj.base.Sha256Hash; /** * PrunedException is thrown in cases where a fully verifying node has deleted (pruned) old block data that turned * out to be necessary for handling a re-org. Normally this should never happen unless you're playing with the testnet * as the pruning parameters should be set very conservatively, such that an absolutely enormous re-org would be * required to trigger it. */ @SuppressWarnings("serial") public class PrunedException extends Exception { private Sha256Hash hash; public PrunedException(Sha256Hash hash) { super(hash.toString()); this.hash = hash; } public Sha256Hash getHash() { return hash; } }
1,404
34.125
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/VerificationException.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core; @SuppressWarnings("serial") public class VerificationException extends RuntimeException { public VerificationException() { super(); } public VerificationException(String msg) { super(msg); } public VerificationException(Exception e) { super(e); } public VerificationException(String msg, Throwable t) { super(msg, t); } public static class EmptyInputsOrOutputs extends VerificationException { public EmptyInputsOrOutputs() { super("Transaction had no inputs or no outputs."); } } public static class LargerThanMaxBlockSize extends VerificationException { public LargerThanMaxBlockSize() { super("Transaction larger than MAX_BLOCK_SIZE"); } } public static class DuplicatedOutPoint extends VerificationException { public DuplicatedOutPoint() { super("Duplicated outpoint"); } } public static class NegativeValueOutput extends VerificationException { public NegativeValueOutput() { super("Transaction output negative"); } } public static class ExcessiveValue extends VerificationException { public ExcessiveValue() { super("Total transaction output value greater than possible"); } } public static class CoinbaseScriptSizeOutOfRange extends VerificationException { public CoinbaseScriptSizeOutOfRange() { super("Coinbase script size out of range"); } } public static class BlockVersionOutOfDate extends VerificationException { public BlockVersionOutOfDate(final long version) { super("Block version #" + version + " is outdated."); } } public static class UnexpectedCoinbaseInput extends VerificationException { public UnexpectedCoinbaseInput() { super("Coinbase input as input in non-coinbase transaction"); } } public static class CoinbaseHeightMismatch extends VerificationException { public CoinbaseHeightMismatch(final String message) { super(message); } } public static class NoncanonicalSignature extends VerificationException { public NoncanonicalSignature() { super("Signature encoding is not canonical"); } } }
2,997
28.98
84
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/PeerDiscoveredEventListener.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerAddress; import org.bitcoinj.core.PeerGroup; import java.util.Set; /** * <p>Implementors can listen to events for peers being discovered.</p> */ public interface PeerDiscoveredEventListener { /** * <p>Called when peers are discovered, this happens at startup of {@link PeerGroup} or if we run out of * suitable {@link Peer}s to connect to.</p> * * @param peerAddresses the set of discovered {@link PeerAddress}es */ void onPeersDiscovered(Set<PeerAddress> peerAddresses); }
1,204
31.567568
108
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/PeerDisconnectedEventListener.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerGroup; /** * <p>Implementors can listen to events indicating a peer disconnecting.</p> */ public interface PeerDisconnectedEventListener { /** * Called when a peer is disconnected. Note that this won't be called if the listener is registered on a * {@link PeerGroup} and the group is in the process of shutting down. If this listener is registered to a * {@link Peer} instead of a {@link PeerGroup}, peerCount will always be 0. This handler can be called without * a corresponding invocation of onPeerConnected if the initial connection is never successful. * * @param peer * @param peerCount the total number of connected peers */ void onPeerDisconnected(Peer peer, int peerCount); }
1,430
36.657895
114
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/TransactionConfidenceEventListener.java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.Transaction; import org.bitcoinj.wallet.Wallet; /** * Implementors are called when confidence of a transaction changes. */ public interface TransactionConfidenceEventListener { /** * Called when a transaction changes its confidence level. You can also attach event listeners to * the individual transactions, if you don't care about all of them. Usually you would save the wallet to disk after * receiving this callback unless you already set up autosaving. * <p> * You should pay attention to this callback in case a transaction becomes <i>dead</i>, that is, a transaction * you believed to be active (send or receive) becomes overridden by the network. This can happen if: * * <ol> * <li>You are sharing keys between wallets and accidentally create/broadcast a double spend.</li> * <li>Somebody is attacking the network and reversing transactions, ie, the user is a victim of fraud.</li> * <li>A bug: for example you create a transaction, broadcast it but fail to commit it. The {@link Wallet} * will then re-use the same outputs when creating the next spend.</li> * </ol> * * To find if the transaction is dead, you can use: * <pre> * {@code * tx.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.DEAD} * </pre> * If it is, you should notify the user in some way so they know the thing they bought may not arrive/the thing they sold should not be dispatched. * <p> * Note that this callback will be invoked for every transaction in the wallet, for every new block that is * received (because the depth has changed). <b>If you want to update a UI view from the contents of the wallet * it is more efficient to use onWalletChanged instead.</b> */ void onTransactionConfidenceChanged(Wallet wallet, Transaction tx); }
2,554
46.314815
151
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/ReorganizeListener.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.BlockChain; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.VerificationException; import java.util.List; /** * Listener interface for when the best chain has changed. */ public interface ReorganizeListener { /** * Called by the {@link BlockChain} when the best chain * (representing total work done) has changed. In this case, * we need to go through our transactions and find out if any have become invalid. It's possible for our balance * to go down in this case: money we thought we had can suddenly vanish if the rest of the network agrees it * should be so.<p> * * The oldBlocks/newBlocks lists are ordered height-wise from top first to bottom last (i.e. newest blocks first). */ void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) throws VerificationException; }
1,564
36.261905
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/BlockchainDownloadEventListener.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; /** * Event Listener for blockchain download. Replaces deprecated {@link PeerDataEventListener} because most (all?) * implementations of {@code PeerDataEventListener} were only using {@link BlocksDownloadedEventListener} and {@link ChainDownloadStartedEventListener} anyway. */ public interface BlockchainDownloadEventListener extends BlocksDownloadedEventListener, ChainDownloadStartedEventListener { }
1,077
40.461538
159
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/PeerDataEventListener.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerGroup; /** * <p>Implementors can listen to events like blocks being downloaded/transactions being broadcast/connect/disconnects, * they can pre-filter messages before they are processed by a {@link Peer} or {@link PeerGroup}, and they can * provide transactions to remote peers when they ask for them.</p> * @deprecated use {@link BlockchainDownloadEventListener} */ @Deprecated public interface PeerDataEventListener extends BlocksDownloadedEventListener, ChainDownloadStartedEventListener, GetDataEventListener, PreMessageReceivedEventListener { }
1,257
38.3125
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/AddressEventListener.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.AddressMessage; import org.bitcoinj.core.Peer; /** * <p>Implementors can listen to addresses being received from remote peers.</p> */ public interface AddressEventListener { /** * Called when a peer receives an {@code addr} or {@code addrv2} message, usually in response to a * {@code getaddr} message. * * @param peer the peer that received the addr or addrv2 message * @param message the addr or addrv2 message that was received */ void onAddr(Peer peer, AddressMessage message); }
1,205
32.5
102
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/TransactionReceivedInBlockListener.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.BlockChain; import org.bitcoinj.core.FilteredBlock; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.VerificationException; /** * Listener interface for when we receive a new block that contains a relevant * transaction. */ public interface TransactionReceivedInBlockListener { /** * <p>Called by the {@link BlockChain} when we receive a new block that contains a relevant transaction.</p> * * <p>A transaction may be received multiple times if is included into blocks in parallel chains. The blockType * parameter describes whether the containing block is on the main/best chain or whether it's on a presently * inactive side chain.</p> * * <p>The relativityOffset parameter is an arbitrary number used to establish an ordering between transactions * within the same block. In the case where full blocks are being downloaded, it is simply the index of the * transaction within that block. When Bloom filtering is in use, we don't find out the exact offset into a block * that a transaction occurred at, so the relativity count is not reflective of anything in an absolute sense but * rather exists only to order the transaction relative to the others.</p> */ void receiveFromBlock(Transaction tx, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException; /** * <p>Called by the {@link BlockChain} when we receive a new {@link FilteredBlock} that contains the given * transaction hash in its merkle tree.</p> * * <p>A transaction may be received multiple times if is included into blocks in parallel chains. The blockType * parameter describes whether the containing block is on the main/best chain or whether it's on a presently * inactive side chain.</p> * * <p>The relativityOffset parameter in this case is an arbitrary (meaningless) number, that is useful only when * compared to the relativity count of another transaction received inside the same block. It is used to establish * an ordering of transactions relative to one another.</p> * * <p>This method should return false if the given tx hash isn't known about, e.g. because the the transaction was * a Bloom false positive. If it was known about and stored, it should return true. The caller may need to know * this to calculate the effective FP rate.</p> * * @return whether the transaction is known about i.e. was considered relevant previously. */ boolean notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, BlockChain.NewBlockType blockType, int relativityOffset) throws VerificationException; }
3,567
50.710145
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/BlocksDownloadedEventListener.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.Block; import org.bitcoinj.core.FilteredBlock; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerGroup; import javax.annotation.Nullable; /** * <p>Implementors can listen to events like blocks being downloaded/transactions being broadcast/connect/disconnects, * they can pre-filter messages before they are processed by a {@link Peer} or {@link PeerGroup}, and they can * provide transactions to remote peers when they ask for them.</p> */ public interface BlocksDownloadedEventListener { // TODO: Fix the Block/FilteredBlock type hierarchy so we can avoid the stupid typeless API here. /** * <p>Called on a Peer thread when a block is received.</p> * * <p>The block may be a Block object that contains transactions, a Block object that is only a header when * fast catchup is being used. If set, filteredBlock can be used to retrieve the list of associated transactions.</p> * * @param peer the peer receiving the block * @param block the downloaded block * @param filteredBlock if non-null, the object that wraps the block header passed as the block param. * @param blocksLeft the number of blocks left to download */ void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft); }
1,974
41.021277
121
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/ChainDownloadStartedEventListener.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerGroup; /** * <p>Implementors can listen to events like blocks being downloaded/transactions being broadcast/connect/disconnects, * they can pre-filter messages before they are processed by a {@link Peer} or {@link PeerGroup}, and they can * provide transactions to remote peers when they ask for them.</p> */ public interface ChainDownloadStartedEventListener { /** * Called when a download is started with the initial number of blocks to be downloaded. * * @param peer the peer receiving the block * @param blocksLeft the number of blocks left to download */ void onChainDownloadStarted(Peer peer, int blocksLeft); }
1,356
35.675676
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/DownloadProgressTracker.java
/* * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.Block; import org.bitcoinj.core.FilteredBlock; import org.bitcoinj.core.Peer; import org.bitcoinj.utils.ListenableCompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.time.Instant; import java.util.Date; import java.util.Locale; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; /** * <p>An implementation of {@link BlockchainDownloadEventListener} that listens to chain download events and tracks progress * as a percentage. The default implementation prints progress to stdout, but you can subclass it and override the * progress method to update a GUI instead.</p> */ public class DownloadProgressTracker implements BlockchainDownloadEventListener { private static final Logger log = LoggerFactory.getLogger(DownloadProgressTracker.class); private int originalBlocksLeft = -1; private int lastPercent = 0; private final CompletableFuture<Long> future = new CompletableFuture<>(); private boolean caughtUp = false; @Override public void onChainDownloadStarted(Peer peer, int blocksLeft) { if (blocksLeft > 0 && originalBlocksLeft == -1) startDownload(blocksLeft); // Only mark this the first time, because this method can be called more than once during a chain download // if we switch peers during it. if (originalBlocksLeft == -1) originalBlocksLeft = blocksLeft; else log.info("Chain download switched to {}", peer); if (blocksLeft == 0) { doneDownload(); future.complete(peer.getBestHeight()); } } @Override public void onBlocksDownloaded(Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) { if (caughtUp) return; if (blocksLeft == 0) { caughtUp = true; if (lastPercent != 100) { lastPercent = 100; progress(lastPercent, blocksLeft, block.time()); } doneDownload(); future.complete(peer.getBestHeight()); return; } if (blocksLeft < 0 || originalBlocksLeft <= 0) return; double pct = 100.0 - (100.0 * (blocksLeft / (double) originalBlocksLeft)); if ((int) pct != lastPercent) { progress(pct, blocksLeft, block.time()); lastPercent = (int) pct; } } /** * Called when download progress is made. * * @param pct the percentage of chain downloaded, estimated * @param time the time of the last block downloaded */ protected void progress(double pct, int blocksSoFar, Instant time) { log.info(String.format(Locale.US, "Chain download %d%% done with %d blocks to go, block date %s", (int) pct, blocksSoFar, TimeUtils.dateTimeFormat(time))); } /** * Called when download is initiated. * * @param blocks the number of blocks to download, estimated */ protected void startDownload(int blocks) { log.info("Downloading block chain of size " + blocks + ". " + (blocks > 1000 ? "This may take a while." : "")); } /** * Called when we are done downloading the block chain. */ protected void doneDownload() { } /** * Wait for the chain to be downloaded. */ public void await() throws InterruptedException { try { future.get(); } catch (ExecutionException e) { throw new RuntimeException(e); } } /** * Returns a listenable future that completes with the height of the best chain (as reported by the peer) once chain * download seems to be finished. */ public ListenableCompletableFuture<Long> getFuture() { return ListenableCompletableFuture.of(future); } }
4,658
33.511111
129
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/PeerConnectedEventListener.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerGroup; /** * <p>Implementors can listen to events indicating a new peer connecting.</p> */ public interface PeerConnectedEventListener { /** * Called when a peer is connected. If this listener is registered to a {@link Peer} instead of a {@link PeerGroup}, * peerCount will always be 1. * * @param peer * @param peerCount the total number of connected peers */ void onPeerConnected(Peer peer, int peerCount); }
1,146
30.861111
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/OnTransactionBroadcastListener.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.Peer; import org.bitcoinj.core.Transaction; /** * Called when a new transaction is broadcast over the network. */ public interface OnTransactionBroadcastListener { /** * Called when a new transaction is broadcast over the network. */ void onTransaction(Peer peer, Transaction t); }
980
30.645161
75
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/PreMessageReceivedEventListener.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.Message; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerGroup; import org.bitcoinj.utils.Threading; /** * <p>Implementors can listen to events like blocks being downloaded/transactions being broadcast/connect/disconnects, * they can pre-filter messages before they are processed by a {@link Peer} or {@link PeerGroup}, and they can * provide transactions to remote peers when they ask for them.</p> */ public interface PreMessageReceivedEventListener { /** * <p>Called when a message is received by a peer, before the message is processed. The returned message is * processed instead. Returning null will cause the message to be ignored by the Peer returning the same message * object allows you to see the messages received but not change them. The result from one event listeners * callback is passed as "m" to the next, forming a chain.</p> * * <p>Note that this will never be called if registered with any executor other than * {@link Threading#SAME_THREAD}</p> */ Message onPreMessageReceived(Peer peer, Message m); }
1,748
40.642857
118
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/NewBestBlockListener.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.AbstractBlockChain; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.VerificationException; /** * Listener interface for when a new block on the best chain is seen. */ public interface NewBestBlockListener { /** * Called when a new block on the best chain is seen, after relevant * transactions are extracted and sent to us via either * {@link TransactionReceivedInBlockListener#receiveFromBlock(Transaction, StoredBlock, AbstractBlockChain.NewBlockType, int)} * or {@link TransactionReceivedInBlockListener#notifyTransactionIsInBlock(Sha256Hash, StoredBlock, AbstractBlockChain.NewBlockType, int)}. * If this block is causing a re-organise to a new chain, this method is NOT * called even though the block may be the new best block: your reorganize * implementation is expected to do whatever would normally be done do for a * new best block in this case. */ void notifyNewBestBlock(final StoredBlock block) throws VerificationException; }
1,746
41.609756
143
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/core/listeners/GetDataEventListener.java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.core.listeners; import org.bitcoinj.core.GetDataMessage; import org.bitcoinj.core.Message; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerGroup; import org.bitcoinj.utils.Threading; import javax.annotation.Nullable; import java.util.List; /** * <p>Implementors can listen to events like blocks being downloaded/transactions being broadcast/connect/disconnects, * they can pre-filter messages before they are processed by a {@link Peer} or {@link PeerGroup}, and they can * provide transactions to remote peers when they ask for them.</p> */ public interface GetDataEventListener { /** * <p>Called when a peer receives a getdata message, usually in response to an "inv" being broadcast. Return as many * items as possible which appear in the {@link GetDataMessage}, or null if you're not interested in responding.</p> * * <p>Note that this will never be called if registered with any executor other than * {@link Threading#SAME_THREAD}</p> */ @Nullable List<Message> getData(Peer peer, GetDataMessage m); }
1,685
36.466667
120
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/testing/FakeTxBuilder.java
/* * Copyright 2011 Google Inc. * Copyright 2016 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.testing; import com.google.common.annotations.VisibleForTesting; import org.bitcoinj.base.Network; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.Address; import org.bitcoinj.base.internal.ByteUtils; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.core.Block; import org.bitcoinj.base.Coin; import org.bitcoinj.crypto.ECKey; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.ProtocolException; import org.bitcoinj.base.Sha256Hash; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.VerificationException; import org.bitcoinj.crypto.TransactionSignature; import org.bitcoinj.script.ScriptBuilder; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.time.Instant; import java.util.Random; import static org.bitcoinj.base.Coin.COIN; import static org.bitcoinj.base.Coin.valueOf; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Methods for building fake transactions for unit tests. Since these methods are currently used both in the `bitcoinj-core` * unit tests and in the `integration-test` subproject, they are (for now) included in the `bitcoinj-core` JAR. They should * not be considered part of the API. */ @VisibleForTesting public class FakeTxBuilder { /** Create a fake transaction, without change. */ public static Transaction createFakeTx(Network network) { return createFakeTxWithoutChangeAddress(Coin.COIN, randomAddress(network)); } /** * Create a fake transaction, without change. * @deprecated use {@link FakeTxBuilder#createFakeTx(Network)} */ @Deprecated public static Transaction createFakeTx(final NetworkParameters params) { return createFakeTxWithoutChangeAddress(Coin.COIN, randomAddress(params.network())); } /** Create a fake transaction, without change. */ public static Transaction createFakeTxWithoutChange(final TransactionOutput output) { Transaction prevTx = FakeTxBuilder.createFakeTx(Coin.COIN, randomKey()); Transaction tx = new Transaction(); tx.addOutput(output); tx.addInput(prevTx.getOutput(0)); return tx; } /** Create a fake coinbase transaction. */ public static Transaction createFakeCoinbaseTx() { Transaction tx = Transaction.coinbase(); TransactionOutput outputToMe = new TransactionOutput(tx, Coin.FIFTY_COINS, randomKey()); checkState(tx.isCoinBase()); tx.addOutput(outputToMe); return tx; } /** * Create a fake TX of sufficient realism to exercise the unit tests. Two outputs, one to us, one to somewhere * else to simulate change. There is one random input. */ public static Transaction createFakeTxWithChangeAddress(Coin value, Address to, Address changeOutput) { Transaction t = new Transaction(); TransactionOutput outputToMe = new TransactionOutput(t, value, to); t.addOutput(outputToMe); TransactionOutput change = new TransactionOutput(t, valueOf(1, 11), changeOutput); t.addOutput(change); // Make a previous tx simply to send us sufficient coins. This prev tx is not really valid but it doesn't // matter for our purposes. Transaction prevTx = new Transaction(); TransactionOutput prevOut = new TransactionOutput(prevTx, value, to); prevTx.addOutput(prevOut); // Connect it. t.addInput(prevOut).setScriptSig(ScriptBuilder.createInputScript(TransactionSignature.dummy())); // Fake signature. // Serialize/deserialize to ensure internal state is stripped, as if it had been read from the wire. return roundTripTransaction(t); } /** * Create a fake TX for unit tests, for use with unit tests that need greater control. One outputs, 2 random inputs, * split randomly to create randomness. */ public static Transaction createFakeTxWithoutChangeAddress(Coin value, Address to) { Transaction t = new Transaction(); TransactionOutput outputToMe = new TransactionOutput(t, value, to); t.addOutput(outputToMe); // Make a random split in the output value so we get a distinct hash when we call this multiple times with same args long split = new Random().nextLong(); if (split < 0) { split *= -1; } if (split == 0) { split = 15; } while (split > value.getValue()) { split /= 2; } // Make a previous tx simply to send us sufficient coins. This prev tx is not really valid but it doesn't // matter for our purposes. Transaction prevTx1 = new Transaction(); TransactionOutput prevOut1 = new TransactionOutput(prevTx1, Coin.valueOf(split), to); prevTx1.addOutput(prevOut1); // Connect it. t.addInput(prevOut1).setScriptSig(ScriptBuilder.createInputScript(TransactionSignature.dummy())); // Fake signature. // Do it again Transaction prevTx2 = new Transaction(); TransactionOutput prevOut2 = new TransactionOutput(prevTx2, Coin.valueOf(value.getValue() - split), to); prevTx2.addOutput(prevOut2); t.addInput(prevOut2).setScriptSig(ScriptBuilder.createInputScript(TransactionSignature.dummy())); // Serialize/deserialize to ensure internal state is stripped, as if it had been read from the wire. return roundTripTransaction(t); } /** * Create a fake TX of sufficient realism to exercise the unit tests. Two outputs, one to us, one to somewhere * else to simulate change. There is one random input. */ public static Transaction createFakeTx(Network network, Coin value, Address to) { return createFakeTxWithChangeAddress(value, to, randomAddress(network)); } /** * Create a fake TX of sufficient realism to exercise the unit tests. Two outputs, one to us, one to somewhere * else to simulate change. There is one random input. * @deprecated use {@link #createFakeTx(Network, Coin, Address)} */ @Deprecated public static Transaction createFakeTx(NetworkParameters params, Coin value, Address to) { return createFakeTx(params.network(), value, to); } /** * Create a fake TX of sufficient realism to exercise the unit tests. Two outputs, one to us, one to somewhere * else to simulate change. There is one random input. */ public static Transaction createFakeTx(Coin value, ECKey to) { Transaction t = new Transaction(); TransactionOutput outputToMe = new TransactionOutput(t, value, to); t.addOutput(outputToMe); TransactionOutput change = new TransactionOutput(t, valueOf(1, 11), new ECKey()); t.addOutput(change); // Make a previous tx simply to send us sufficient coins. This prev tx is not really valid but it doesn't // matter for our purposes. Transaction prevTx = new Transaction(); TransactionOutput prevOut = new TransactionOutput(prevTx, value, to); prevTx.addOutput(prevOut); // Connect it. t.addInput(prevOut); // Serialize/deserialize to ensure internal state is stripped, as if it had been read from the wire. return roundTripTransaction(t); } /** * Transaction[0] is a feeder transaction, supplying BTC to Transaction[1] */ public static Transaction[] createFakeTx(Coin value, Address to, Address from) { // Create fake TXes of sufficient realism to exercise the unit tests. This transaction send BTC from the // from address, to the to address with to one to somewhere else to simulate change. Transaction t = new Transaction(); TransactionOutput outputToMe = new TransactionOutput(t, value, to); t.addOutput(outputToMe); TransactionOutput change = new TransactionOutput(t, valueOf(1, 11), randomKey()); t.addOutput(change); // Make a feeder tx that sends to the from address specified. This feeder tx is not really valid but it doesn't // matter for our purposes. Transaction feederTx = new Transaction(); TransactionOutput feederOut = new TransactionOutput(feederTx, value, from); feederTx.addOutput(feederOut); // make a previous tx that sends from the feeder to the from address Transaction prevTx = new Transaction(); TransactionOutput prevOut = new TransactionOutput(prevTx, value, to); prevTx.addOutput(prevOut); // Connect up the txes prevTx.addInput(feederOut); t.addInput(prevOut); // roundtrip the tx so that they are just like they would be from the wire return new Transaction[]{roundTripTransaction(prevTx), roundTripTransaction(t)}; } /** * Roundtrip a transaction so that it appears as if it has just come from the wire */ public static Transaction roundTripTransaction(Transaction tx) { return Transaction.read(ByteBuffer.wrap(tx.serialize())); } public static class DoubleSpends { public Transaction t1, t2, prevTx; } /** * Creates two transactions that spend the same (fake) output. t1 spends to "to". t2 spends somewhere else. * The fake output goes to the same address as t2. */ public static DoubleSpends createFakeDoubleSpendTxns(Address to) { DoubleSpends doubleSpends = new DoubleSpends(); Coin value = COIN; ECKey someBadGuy = randomKey(); doubleSpends.prevTx = new Transaction(); TransactionOutput prevOut = new TransactionOutput(doubleSpends.prevTx, value, someBadGuy); doubleSpends.prevTx.addOutput(prevOut); doubleSpends.t1 = new Transaction(); TransactionOutput o1 = new TransactionOutput(doubleSpends.t1, value, to); doubleSpends.t1.addOutput(o1); doubleSpends.t1.addInput(prevOut); doubleSpends.t2 = new Transaction(); doubleSpends.t2.addInput(prevOut); TransactionOutput o2 = new TransactionOutput(doubleSpends.t2, value, someBadGuy); doubleSpends.t2.addOutput(o2); try { doubleSpends.t1 = roundTripTransaction(doubleSpends.t1); doubleSpends.t2 = roundTripTransaction(doubleSpends.t2); } catch (ProtocolException e) { throw new RuntimeException(e); } return doubleSpends; } public static class BlockPair { public StoredBlock storedBlock; public Block block; } /** Emulates receiving a valid block that builds on top of the chain. */ public static BlockPair createFakeBlock(BlockStore blockStore, long version, Instant time, Transaction... transactions) { return createFakeBlock(blockStore, version, time, 0, transactions); } /** @deprecated use {@link #createFakeBlock(BlockStore, long, Instant, Transaction...)} */ @Deprecated public static BlockPair createFakeBlock(BlockStore blockStore, long version, long timeSecs, Transaction... transactions) { return createFakeBlock(blockStore, version, Instant.ofEpochSecond(timeSecs), transactions); } /** Emulates receiving a valid block */ public static BlockPair createFakeBlock(BlockStore blockStore, StoredBlock previousStoredBlock, long version, Instant time, int height, Transaction... transactions) { try { Block previousBlock = previousStoredBlock.getHeader(); Block b = previousBlock.createNextBlock(null, version, time, height); // Coinbase tx was already added. for (Transaction tx : transactions) { tx.getConfidence().setSource(TransactionConfidence.Source.NETWORK); b.addTransaction(tx); } b.solve(); BlockPair pair = new BlockPair(); pair.block = b; pair.storedBlock = previousStoredBlock.build(b); blockStore.put(pair.storedBlock); blockStore.setChainHead(pair.storedBlock); return pair; } catch (VerificationException | BlockStoreException e) { throw new RuntimeException(e); // Cannot happen. } } /** @deprecated use {@link #createFakeBlock(BlockStore, StoredBlock, long, Instant, int, Transaction...)} */ @Deprecated public static BlockPair createFakeBlock(BlockStore blockStore, StoredBlock previousStoredBlock, long version, long timeSecs, int height, Transaction... transactions) { return createFakeBlock(blockStore, previousStoredBlock, version, Instant.ofEpochSecond(timeSecs), height, transactions); } public static BlockPair createFakeBlock(BlockStore blockStore, StoredBlock previousStoredBlock, int height, Transaction... transactions) { return createFakeBlock(blockStore, previousStoredBlock, Block.BLOCK_VERSION_BIP66, TimeUtils.currentTime(), height, transactions); } /** Emulates receiving a valid block that builds on top of the chain. */ public static BlockPair createFakeBlock(BlockStore blockStore, long version, Instant time, int height, Transaction... transactions) { try { return createFakeBlock(blockStore, blockStore.getChainHead(), version, time, height, transactions); } catch (BlockStoreException e) { throw new RuntimeException(e); // Cannot happen. } } /** @deprecated use {@link #createFakeBlock(BlockStore, long, Instant, int, Transaction...)} */ @Deprecated public static BlockPair createFakeBlock(BlockStore blockStore, long version, long timeSecs, int height, Transaction... transactions) { return createFakeBlock(blockStore, version, Instant.ofEpochSecond(timeSecs), height, transactions); } /** Emulates receiving a valid block that builds on top of the chain. */ public static BlockPair createFakeBlock(BlockStore blockStore, int height, Transaction... transactions) { return createFakeBlock(blockStore, Block.BLOCK_VERSION_GENESIS, TimeUtils.currentTime(), height, transactions); } /** Emulates receiving a valid block that builds on top of the chain. */ public static BlockPair createFakeBlock(BlockStore blockStore, Transaction... transactions) { return createFakeBlock(blockStore, Block.BLOCK_VERSION_GENESIS, TimeUtils.currentTime(), 0, transactions); } public static Block makeSolvedTestBlock(BlockStore blockStore, Address coinsTo) throws BlockStoreException { Block b = blockStore.getChainHead().getHeader().createNextBlock(coinsTo); b.solve(); return b; } public static Block makeSolvedTestBlock(Block prev, Transaction... transactions) throws BlockStoreException { return makeSolvedTestBlock(prev, null, transactions); } public static Block makeSolvedTestBlock(Block prev, @Nullable Address to, Transaction... transactions) throws BlockStoreException { Block b = prev.createNextBlock(to); // Coinbase tx already exists. for (Transaction tx : transactions) { b.addTransaction(tx); } b.solve(); return b; } private static Address randomAddress(Network network) { return randomKey().toAddress(ScriptType.P2PKH, network); } private static ECKey randomKey() { return new ECKey(); } }
16,593
43.727763
142
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/testing/MockAltNetworkParams.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.testing; import org.bitcoinj.base.Coin; import org.bitcoinj.base.utils.MonetaryFormat; import org.bitcoinj.core.BitcoinSerializer; import org.bitcoinj.core.Block; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.StoredBlock; import org.bitcoinj.core.VerificationException; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; /** * Mock Alt-net subclass of {@link NetworkParameters} for unit tests. */ public class MockAltNetworkParams extends NetworkParameters { public static final String MOCKNET_GOOD_ADDRESS = "LLxSnHLN2CYyzB5eWTR9K9rS9uWtbTQFb6"; public MockAltNetworkParams() { super(new MockAltNetwork()); addressHeader = 48; p2shHeader = 5; } @Override public String getPaymentProtocolId() { return null; } @Override public void checkDifficultyTransitions(StoredBlock storedPrev, Block next, BlockStore blockStore) throws VerificationException, BlockStoreException { } @Override public Block getGenesisBlock() { return null; } @Override public Coin getMaxMoney() { return (Coin) this.network.maxMoney(); } @Override public MonetaryFormat getMonetaryFormat() { return null; } @Override public String getUriScheme() { return this.network.uriScheme(); } @Override public boolean hasMaxMoney() { return this.network.hasMaxMoney(); } @Override public BitcoinSerializer getSerializer() { return null; } }
2,195
26.111111
153
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/testing/MockAltNetwork.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.testing; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Monetary; import org.bitcoinj.base.Network; /** * Mock Alt-net implementation of {@link Network} for unit tests. */ public class MockAltNetwork implements Network { @Override public String id() { return "mock.alt.network"; } @Override public int legacyAddressHeader() { return 48; } @Override public int legacyP2SHHeader() { return 5; } @Override public String segwitAddressHrp() { return "mock"; } @Override public String uriScheme() { return "mockcoin"; } @Override public boolean hasMaxMoney() { return false; } @Override public Monetary maxMoney() { return Coin.valueOf(Long.MAX_VALUE); } @Override public boolean exceedsMaxMoney(Monetary monetary) { return false; } }
1,543
22.044776
75
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/kits/package-info.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * High level wrapper APIs around the bitcoinj building blocks. WalletAppKit is suitable for many different types of * apps that require an SPV wallet. */ package org.bitcoinj.kits;
801
37.190476
116
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/kits/WalletAppKit.java
/* * Copyright 2013 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.kits; import com.google.common.io.Closeables; import com.google.common.util.concurrent.AbstractIdleService; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.ScriptType; import org.bitcoinj.base.internal.PlatformUtils; import org.bitcoinj.core.BlockChain; import org.bitcoinj.core.CheckpointManager; import org.bitcoinj.core.Context; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.PeerAddress; import org.bitcoinj.core.PeerGroup; import org.bitcoinj.core.listeners.DownloadProgressTracker; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.net.discovery.DnsDiscovery; import org.bitcoinj.net.discovery.PeerDiscovery; import org.bitcoinj.store.BlockStore; import org.bitcoinj.store.BlockStoreException; import org.bitcoinj.store.SPVBlockStore; import org.bitcoinj.wallet.DeterministicSeed; import org.bitcoinj.wallet.KeyChainGroup; import org.bitcoinj.wallet.KeyChainGroupStructure; import org.bitcoinj.wallet.Wallet; import org.bitcoinj.wallet.WalletExtension; import org.bitcoinj.wallet.WalletProtobufSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.channels.FileLock; import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * <p>Utility class that wraps the boilerplate needed to set up a new SPV bitcoinj app. Instantiate it with a directory * and file prefix, optionally configure a few things, then use startAsync and optionally awaitRunning. The object will * construct and configure a {@link BlockChain}, {@link SPVBlockStore}, {@link Wallet} and {@link PeerGroup}. Depending * on the value of the blockingStartup property, startup will be considered complete once the block chain has fully * synchronized, so it can take a while.</p> * * <p>To add listeners and modify the objects that are constructed, you can either do that by overriding the * {@link #onSetupCompleted()} method (which will run on a background thread) and make your changes there, * or by waiting for the service to start and then accessing the objects from wherever you want. However, you cannot * access the objects this class creates until startup is complete.</p> * * <p>The asynchronous design of this class may seem puzzling (just use {@link #awaitRunning()} if you don't want that). * It is to make it easier to fit bitcoinj into GUI apps, which require a high degree of responsiveness on their main * thread which handles all the animation and user interaction. Even when blockingStart is false, initializing bitcoinj * means doing potentially blocking file IO, generating keys and other potentially intensive operations. By running it * on a background thread, there's no risk of accidentally causing UI lag.</p> * * <p>Note that {@link #awaitRunning()} can throw an unchecked {@link IllegalStateException} * if anything goes wrong during startup - you should probably handle it and use {@link Exception#getCause()} to figure * out what went wrong more precisely. Same thing if you just use the {@link #startAsync()} method.</p> */ public class WalletAppKit extends AbstractIdleService implements Closeable { protected static final Logger log = LoggerFactory.getLogger(WalletAppKit.class); protected final BitcoinNetwork network; protected final NetworkParameters params; protected final ScriptType preferredOutputScriptType; protected final KeyChainGroupStructure structure; protected final String filePrefix; protected volatile BlockChain vChain; protected volatile SPVBlockStore vStore; protected volatile Wallet vWallet; protected volatile PeerGroup vPeerGroup; protected final File directory; protected volatile File vWalletFile; protected boolean useAutoSave = true; protected PeerAddress[] peerAddresses; protected DownloadProgressTracker downloadListener = new DownloadProgressTracker(); protected boolean autoStop = true; protected InputStream checkpoints; protected boolean blockingStartup = true; protected String userAgent, version; @Nonnull protected WalletProtobufSerializer.WalletFactory walletFactory = WalletProtobufSerializer.WalletFactory.DEFAULT; @Nullable protected DeterministicSeed restoreFromSeed; @Nullable protected DeterministicKey restoreFromKey; @Nullable protected PeerDiscovery discovery; /** * Creates a new WalletAppKit, with a newly created {@link Context}. Files will be stored in the given directory. * @deprecated Use {@link #WalletAppKit(BitcoinNetwork, ScriptType, KeyChainGroupStructure, File, String)} */ @Deprecated public WalletAppKit(NetworkParameters params, File directory, String filePrefix) { this((BitcoinNetwork) params.network(), ScriptType.P2PKH, KeyChainGroupStructure.BIP32, directory, filePrefix); } /** * Creates a new WalletAppKit, with a newly created {@link Context}. Files will be stored in the given directory. * @deprecated Use {@link #WalletAppKit(BitcoinNetwork, ScriptType, KeyChainGroupStructure, File, String)} */ @Deprecated public WalletAppKit(NetworkParameters params, ScriptType preferredOutputScriptType, @Nullable KeyChainGroupStructure structure, File directory, String filePrefix) { this((BitcoinNetwork) params.network(), preferredOutputScriptType, structure, directory, filePrefix); } /** * Creates a new WalletAppKit, on the specified {@link BitcoinNetwork}. Files will be stored in the given directory. * * @param network The network the wallet connects to * @param preferredOutputScriptType The output script type (and therefore {@code Address} type) of the wallet * @param structure The keychain group structure (e.g. {@link KeyChainGroupStructure#BIP43} or {@link KeyChainGroupStructure#BIP32} * @param directory The directory for creating {@code .wallet} and {@code .spvchain} files * @param filePrefix The base name for the {@code .wallet} and {@code .spvchain} files */ public WalletAppKit(BitcoinNetwork network, ScriptType preferredOutputScriptType, KeyChainGroupStructure structure, File directory, String filePrefix) { this.network = Objects.requireNonNull(network); this.params = NetworkParameters.of(this.network); this.preferredOutputScriptType = Objects.requireNonNull(preferredOutputScriptType); this.structure = Objects.requireNonNull(structure); this.directory = Objects.requireNonNull(directory); this.filePrefix = Objects.requireNonNull(filePrefix); } /** * Launch an instance of WalletAppKit with asynchronous startup. Wait until the PeerGroup is initialized. * * @param network The network the wallet connects to * @param directory The directory for creating {@code .wallet} and {@code .spvchain} files * @param filePrefix The base name for the {@code .wallet} and {@code .spvchain} files * @return the instance */ public static WalletAppKit launch(BitcoinNetwork network, File directory, String filePrefix) { return WalletAppKit.launch(network, directory, filePrefix, 0); } /** * Launch an instance of WalletAppKit with asynchronous startup. Wait until the PeerGroup is initialized. * * @param network The network the wallet connects to * @param directory The directory for creating {@code .wallet} and {@code .spvchain} files * @param filePrefix The base name for the {@code .wallet} and {@code .spvchain} files * @param configurer Callback to allow configuring the kit before it is started * @return the instance */ public static WalletAppKit launch(BitcoinNetwork network, File directory, String filePrefix, Consumer<WalletAppKit> configurer) { return WalletAppKit.launch(network, directory, filePrefix, configurer, 0); } /** * Launch an instance of WalletAppKit with asynchronous startup. Wait until the PeerGroup is initialized. * * @param network The network the wallet connects to * @param directory The directory for creating {@code .wallet} and {@code .spvchain} files * @param filePrefix The base name for the {@code .wallet} and {@code .spvchain} files * @param maxConnections maximum number of peer connections. * @return the instance */ public static WalletAppKit launch(BitcoinNetwork network, File directory, String filePrefix, int maxConnections) { return WalletAppKit.launch(network, directory, filePrefix, (c) -> {}, maxConnections); } /** * Launch an instance of WalletAppKit with asynchronous startup. Wait until the PeerGroup is initialized. * * @param network The network the wallet connects to * @param directory The directory for creating {@code .wallet} and {@code .spvchain} files * @param filePrefix The base name for the {@code .wallet} and {@code .spvchain} files * @param configurer Callback to allow configuring the kit before it is started * @param maxConnections maximum number of peer connections. * @return the instance */ public static WalletAppKit launch(BitcoinNetwork network, File directory, String filePrefix, Consumer<WalletAppKit> configurer, int maxConnections) { WalletAppKit kit = new WalletAppKit(network, ScriptType.P2WPKH, KeyChainGroupStructure.BIP32, directory, filePrefix); if (network == BitcoinNetwork.REGTEST) { // Regression test mode is designed for testing and development only, so there's no public network for it. // If you pick this mode, you're expected to be running a local "bitcoind -regtest" instance. kit.connectToLocalHost(); } kit.setBlockingStartup(false); // Don't wait for blockchain synchronization before entering RUNNING state configurer.accept(kit); // Call configurer before startup kit.startAsync(); // Connect to the network and start downloading transactions kit.awaitRunning(); // Wait for the service to reach the RUNNING state if (maxConnections > 0) { kit.peerGroup().setMaxConnections(maxConnections); } return kit; } /** Will only connect to the given addresses. Cannot be called after startup. */ public WalletAppKit setPeerNodes(PeerAddress... addresses) { checkState(state() == State.NEW, () -> "cannot call after startup"); this.peerAddresses = addresses; return this; } /** Will only connect to localhost. Cannot be called after startup. */ public WalletAppKit connectToLocalHost() { return setPeerNodes(PeerAddress.localhost(params)); } /** If true, the wallet will save itself to disk automatically whenever it changes. */ public WalletAppKit setAutoSave(boolean value) { checkState(state() == State.NEW, () -> "cannot call after startup"); useAutoSave = value; return this; } /** * If you want to learn about the sync process, you can provide a listener here. For instance, a * {@link DownloadProgressTracker} is a good choice. This has no effect unless setBlockingStartup(false) has been called * too, due to some missing implementation code. */ public WalletAppKit setDownloadListener(DownloadProgressTracker listener) { Objects.requireNonNull(listener); this.downloadListener = listener; return this; } /** If true, will register a shutdown hook to stop the library. Defaults to true. */ public WalletAppKit setAutoStop(boolean autoStop) { this.autoStop = autoStop; return this; } /** * If set, the file is expected to contain a checkpoints file calculated with BuildCheckpoints. It makes initial * block sync faster for new users - please refer to the documentation on the bitcoinj website * (https://bitcoinj.github.io/speeding-up-chain-sync) for further details. */ public WalletAppKit setCheckpoints(InputStream checkpoints) { if (this.checkpoints != null) Closeables.closeQuietly(checkpoints); this.checkpoints = Objects.requireNonNull(checkpoints); return this; } /** * If true (the default) then the startup of this service won't be considered complete until the network has been * brought up, peer connections established and the block chain synchronised. Therefore {@link #awaitRunning()} can * potentially take a very long time. If false, then startup is considered complete once the network activity * begins and peer connections/block chain sync will continue in the background. */ public WalletAppKit setBlockingStartup(boolean blockingStartup) { this.blockingStartup = blockingStartup; return this; } /** * Sets the string that will appear in the subver field of the version message. * @param userAgent A short string that should be the name of your app, e.g. "My Wallet" * @param version A short string that contains the version number, e.g. "1.0-BETA" */ public WalletAppKit setUserAgent(String userAgent, String version) { this.userAgent = Objects.requireNonNull(userAgent); this.version = Objects.requireNonNull(version); return this; } /** * Sets a wallet factory which will be used when the kit creates a new wallet. * @param walletFactory Factory for making new wallets (Use {@link WalletProtobufSerializer.WalletFactory#DEFAULT} for default behavior) * @return WalletAppKit for method chaining purposes */ public WalletAppKit setWalletFactory(@Nonnull WalletProtobufSerializer.WalletFactory walletFactory) { Objects.requireNonNull(walletFactory); this.walletFactory = walletFactory; return this; } /** * If a seed is set here then any existing wallet that matches the file name will be renamed to a backup name, * the chain file will be deleted, and the wallet object will be instantiated with the given seed instead of * a fresh one being created. This is intended for restoring a wallet from the original seed. To implement restore * you would shut down the existing appkit, if any, then recreate it with the seed given by the user, then start * up the new kit. The next time your app starts it should work as normal (that is, don't keep calling this each * time). */ public WalletAppKit restoreWalletFromSeed(DeterministicSeed seed) { this.restoreFromSeed = seed; return this; } /** * If an account key is set here then any existing wallet that matches the file name will be renamed to a backup name, * the chain file will be deleted, and the wallet object will be instantiated with the given key instead of * a fresh seed being created. This is intended for restoring a wallet from an account key. To implement restore * you would shut down the existing appkit, if any, then recreate it with the key given by the user, then start * up the new kit. The next time your app starts it should work as normal (that is, don't keep calling this each * time). */ public WalletAppKit restoreWalletFromKey(DeterministicKey accountKey) { this.restoreFromKey = accountKey; return this; } /** * Sets the peer discovery class to use. If none is provided then DNS is used, which is a reasonable default. */ public WalletAppKit setDiscovery(@Nullable PeerDiscovery discovery) { this.discovery = discovery; return this; } /** * <p>Override this to return wallet extensions if any are necessary.</p> * * <p>When this is called, chain(), store(), and peerGroup() will return the created objects, however they are not * initialized/started.</p> */ protected List<WalletExtension> provideWalletExtensions() throws Exception { return Collections.emptyList(); } /** * This method is invoked on a background thread after all objects are initialised, but before the peer group * or block chain download is started. You can tweak the objects configuration here. */ protected void onSetupCompleted() { } /** * Tests to see if the spvchain file has an operating system file lock on it. Useful for checking if your app * is already running. If another copy of your app is running and you start the appkit anyway, an exception will * be thrown during the startup process. Returns false if the chain file does not exist or is a directory. */ public boolean isChainFileLocked() throws IOException { RandomAccessFile file2 = null; try { File file = new File(directory, filePrefix + ".spvchain"); if (!file.exists()) return false; if (file.isDirectory()) return false; file2 = new RandomAccessFile(file, "rw"); FileLock lock = file2.getChannel().tryLock(); if (lock == null) return true; lock.release(); return false; } finally { if (file2 != null) file2.close(); } } @Override protected void startUp() throws Exception { // Runs in a separate thread. if (!directory.exists()) { if (!directory.mkdirs()) { throw new IOException("Could not create directory " + directory.getAbsolutePath()); } } log.info("Starting up with directory = {}", directory); File chainFile = new File(directory, filePrefix + ".spvchain"); boolean chainFileExists = chainFile.exists(); vWalletFile = new File(directory, filePrefix + ".wallet"); boolean shouldReplayWallet = (vWalletFile.exists() && !chainFileExists) || restoreFromSeed != null || restoreFromKey != null; vWallet = createOrLoadWallet(shouldReplayWallet); // Initiate Bitcoin network objects (block store, blockchain and peer group) vStore = new SPVBlockStore(params, chainFile); if (!chainFileExists || restoreFromSeed != null || restoreFromKey != null) { if (checkpoints == null && !PlatformUtils.isAndroidRuntime()) { checkpoints = CheckpointManager.openStream(params); } if (checkpoints != null) { // Initialize the chain file with a checkpoint to speed up first-run sync. Instant time; if (restoreFromSeed != null) { time = restoreFromSeed.creationTime().orElse(Instant.EPOCH); if (chainFileExists) { log.info("Clearing the chain file in preparation for restore."); vStore.clear(); } } else if (restoreFromKey != null) { time = restoreFromKey.creationTime().orElse(Instant.EPOCH); if (chainFileExists) { log.info("Clearing the chain file in preparation for restore."); vStore.clear(); } } else { time = vWallet.earliestKeyCreationTime(); } if (time.isAfter(Instant.EPOCH)) CheckpointManager.checkpoint(params, checkpoints, vStore, time); else log.warn("Creating a new uncheckpointed block store due to a wallet with a creation time of zero: this will result in a very slow chain sync"); } else if (chainFileExists) { log.info("Clearing the chain file in preparation for restore."); vStore.clear(); } } vChain = new BlockChain(params, vStore); vPeerGroup = createPeerGroup(); if (this.userAgent != null) vPeerGroup.setUserAgent(userAgent, version); // Set up peer addresses or discovery first, so if wallet extensions try to broadcast a transaction // before we're actually connected the broadcast waits for an appropriate number of connections. if (peerAddresses != null) { for (PeerAddress addr : peerAddresses) vPeerGroup.addAddress(addr); vPeerGroup.setMaxConnections(peerAddresses.length); peerAddresses = null; } else if (params.network() != BitcoinNetwork.REGTEST) { vPeerGroup.addPeerDiscovery(discovery != null ? discovery : new DnsDiscovery(params)); } vChain.addWallet(vWallet); vPeerGroup.addWallet(vWallet); // vChain, vWallet, and vPeerGroup all initialized; allow subclass (if any) a chance to adjust configuration onSetupCompleted(); // Start the PeerGroup (asynchronously) and start downloading the blockchain (asynchronously) vPeerGroup.startAsync().whenComplete((result, t) -> { if (t == null) { vPeerGroup.startBlockChainDownload(downloadListener); } else { throw new RuntimeException(t); } }); // Make sure we shut down cleanly. installShutdownHook(); if (blockingStartup) { downloadListener.await(); // Wait for the blockchain to download } } private Wallet createOrLoadWallet(boolean shouldReplayWallet) throws Exception { Wallet wallet; maybeMoveOldWalletOutOfTheWay(); if (vWalletFile.exists()) { wallet = loadWallet(shouldReplayWallet); } else { wallet = createWallet(); wallet.freshReceiveKey(); for (WalletExtension e : provideWalletExtensions()) { wallet.addExtension(e); } // Currently the only way we can be sure that an extension is aware of its containing wallet is by // deserializing the extension (see WalletExtension#deserializeWalletExtension(Wallet, byte[])) // Hence, we first save and then load wallet to ensure any extensions are correctly initialized. wallet.saveToFile(vWalletFile); wallet = loadWallet(false); } if (useAutoSave) { this.setupAutoSave(wallet); } return wallet; } protected void setupAutoSave(Wallet wallet) { wallet.autosaveToFile(vWalletFile, 5, TimeUnit.SECONDS, null); } private Wallet loadWallet(boolean shouldReplayWallet) throws Exception { WalletExtension[] extensions = provideWalletExtensions().toArray(new WalletExtension[0]); return Wallet.loadFromFile(vWalletFile, walletFactory, shouldReplayWallet, false, extensions ); } protected Wallet createWallet() { KeyChainGroup.Builder kcg = KeyChainGroup.builder(network, structure); if (restoreFromSeed != null) kcg.fromSeed(restoreFromSeed, preferredOutputScriptType); else if (restoreFromKey != null) kcg.fromKey(restoreFromKey, preferredOutputScriptType).build(); else kcg.fromRandom(preferredOutputScriptType); return walletFactory.create(network, kcg.build()); } private void maybeMoveOldWalletOutOfTheWay() { if (restoreFromSeed == null && restoreFromKey == null) return; if (!vWalletFile.exists()) return; int counter = 1; File newName; do { newName = new File(vWalletFile.getParent(), "Backup " + counter + " for " + vWalletFile.getName()); counter++; } while (newName.exists()); log.info("Renaming old wallet file {} to {}", vWalletFile, newName); if (!vWalletFile.renameTo(newName)) { // This should not happen unless something is really messed up. throw new RuntimeException("Failed to rename wallet for restore"); } } protected PeerGroup createPeerGroup() { return new PeerGroup(network, vChain); } private void installShutdownHook() { if (autoStop) { Runtime.getRuntime().addShutdownHook(new Thread(this::shutdownHook, "shutdownHook")); } } private void shutdownHook() { try { stopAsync(); awaitTerminated(); } catch (Exception e) { throw new RuntimeException(e); } } @Override protected void shutDown() throws Exception { // Runs in a separate thread. try { vPeerGroup.stop(); vWallet.saveToFile(vWalletFile); vStore.close(); vPeerGroup = null; vWallet = null; vStore = null; vChain = null; } catch (BlockStoreException e) { throw new IOException(e); } } /** * Close and release resources. Implements {@link Closeable}. This should be idempotent. */ @Override public void close() { stopAsync(); awaitTerminated(); } public BitcoinNetwork network() { return network; } public NetworkParameters params() { return params; } public BlockChain chain() { checkState(state() == State.STARTING || state() == State.RUNNING, () -> "cannot call until startup is complete"); return vChain; } public BlockStore store() { checkState(state() == State.STARTING || state() == State.RUNNING, () -> "cannot call until startup is complete"); return vStore; } public Wallet wallet() { checkState(state() == State.STARTING || state() == State.RUNNING, () -> "cannot call until startup is complete"); return vWallet; } public PeerGroup peerGroup() { checkState(state() == State.STARTING || state() == State.RUNNING, () -> "cannot call until startup is complete"); return vPeerGroup; } public File directory() { return directory; } }
27,327
43.148627
163
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/DeterministicSeed.java
/* * Copyright 2014 Google Inc. * Copyright 2014 Andreas Schildbach * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import com.google.common.base.MoreObjects; import org.bitcoinj.base.internal.TimeUtils; import org.bitcoinj.base.internal.InternalUtils; import org.bitcoinj.crypto.AesKey; import org.bitcoinj.crypto.EncryptableItem; import org.bitcoinj.crypto.EncryptedData; import org.bitcoinj.crypto.KeyCrypter; import org.bitcoinj.crypto.MnemonicCode; import org.bitcoinj.crypto.MnemonicException; import javax.annotation.Nullable; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Objects; import java.util.Optional; import org.bitcoinj.base.internal.ByteUtils; import static org.bitcoinj.base.internal.Preconditions.checkArgument; import static org.bitcoinj.base.internal.Preconditions.checkState; /** * Holds the seed bytes for the BIP32 deterministic wallet algorithm, inside a * {@link DeterministicKeyChain}. The purpose of this wrapper is to simplify the encryption * code. */ public class DeterministicSeed implements EncryptableItem { // It would take more than 10^12 years to brute-force a 128 bit seed using $1B worth of computing equipment. public static final int DEFAULT_SEED_ENTROPY_BITS = 128; public static final int MAX_SEED_ENTROPY_BITS = 512; @Nullable private final byte[] seed; @Nullable private final List<String> mnemonicCode; // only one of mnemonicCode/encryptedMnemonicCode will be set @Nullable private final EncryptedData encryptedMnemonicCode; @Nullable private final EncryptedData encryptedSeed; // Creation time of the seed, or null if the seed was deserialized from a version that did not have this field. @Nullable private Instant creationTime = null; /** * Constructs a seed from a BIP 39 mnemonic code. See {@link MnemonicCode} for more * details on this scheme. * @param mnemonicCode list of words, space separated * @param passphrase user supplied passphrase, or empty string if there is no passphrase * @param creationTime when the seed was originally created */ public static DeterministicSeed ofMnemonic(String mnemonicCode, String passphrase, Instant creationTime) { return new DeterministicSeed(mnemonicCode, null, passphrase, Objects.requireNonNull(creationTime)); } /** * Constructs a seed from a BIP 39 mnemonic code. See {@link MnemonicCode} for more * details on this scheme. Use this if you don't know the seed's creation time. * @param mnemonicCode list of words, space separated * @param passphrase user supplied passphrase, or empty string if there is no passphrase */ public static DeterministicSeed ofMnemonic(String mnemonicCode, String passphrase) { return new DeterministicSeed(mnemonicCode, null, passphrase, null); } /** * Constructs a seed from a BIP 39 mnemonic code. See {@link MnemonicCode} for more * details on this scheme. * @param mnemonicCode list of words * @param passphrase user supplied passphrase, or empty string if there is no passphrase * @param creationTime when the seed was originally created */ public static DeterministicSeed ofMnemonic(List<String> mnemonicCode, String passphrase, Instant creationTime) { return new DeterministicSeed(mnemonicCode, null, passphrase, Objects.requireNonNull(creationTime)); } /** * Constructs a seed from a BIP 39 mnemonic code. See {@link MnemonicCode} for more * details on this scheme. Use this if you don't know the seed's creation time. * @param mnemonicCode list of words * @param passphrase user supplied passphrase, or empty string if there is no passphrase */ public static DeterministicSeed ofMnemonic(List<String> mnemonicCode, String passphrase) { return new DeterministicSeed(mnemonicCode, null, passphrase, null); } /** * Constructs a BIP 39 mnemonic code and a seed from a given entropy. See {@link MnemonicCode} for more * details on this scheme. * @param entropy entropy bits, length must be at least 128 bits and a multiple of 32 bits * @param passphrase user supplied passphrase, or empty string if there is no passphrase * @param creationTime when the seed was originally created */ public static DeterministicSeed ofEntropy(byte[] entropy, String passphrase, Instant creationTime) { return new DeterministicSeed(entropy, passphrase, Objects.requireNonNull(creationTime)); } /** * Constructs a BIP 39 mnemonic code and a seed from a given entropy. See {@link MnemonicCode} for more * details on this scheme. Use this if you don't know the seed's creation time. * @param entropy entropy bits, length must be at least 128 bits and a multiple of 32 bits * @param passphrase user supplied passphrase, or empty string if there is no passphrase */ public static DeterministicSeed ofEntropy(byte[] entropy, String passphrase) { return new DeterministicSeed(entropy, passphrase, null); } /** * Constructs a BIP 39 mnemonic code and a seed randomly. See {@link MnemonicCode} for more * details on this scheme. * @param random random source for the entropy * @param bits number of bits of entropy, must be at least 128 bits and a multiple of 32 bits * @param passphrase user supplied passphrase, or empty string if there is no passphrase */ public static DeterministicSeed ofRandom(SecureRandom random, int bits, String passphrase) { return new DeterministicSeed(random, bits, passphrase); } /** * Internal use only – will be restricted to private in a future release. * Use {@link #ofMnemonic(String, String, Instant)} or {@link #ofMnemonic(String, String)} instead. */ DeterministicSeed(String mnemonicString, byte[] seed, String passphrase, @Nullable Instant creationTime) { this(decodeMnemonicCode(mnemonicString), seed, passphrase, creationTime); } /** @deprecated use {@link #ofMnemonic(String, String, Instant)} or {@link #ofMnemonic(String, String)} */ @Deprecated public DeterministicSeed(String mnemonicString, byte[] seed, String passphrase, long creationTimeSecs) { this(mnemonicString, seed, passphrase, creationTimeSecs > 0 ? Instant.ofEpochSecond(creationTimeSecs) : null); } /** Internal use only. */ private DeterministicSeed(byte[] seed, List<String> mnemonic, @Nullable Instant creationTime) { this.seed = Objects.requireNonNull(seed); this.mnemonicCode = Objects.requireNonNull(mnemonic); this.encryptedMnemonicCode = null; this.encryptedSeed = null; this.creationTime = creationTime; } /** Internal use only – will be restricted to private in a future release. */ DeterministicSeed(EncryptedData encryptedMnemonic, @Nullable EncryptedData encryptedSeed, @Nullable Instant creationTime) { this.seed = null; this.mnemonicCode = null; this.encryptedMnemonicCode = Objects.requireNonNull(encryptedMnemonic); this.encryptedSeed = encryptedSeed; this.creationTime = creationTime; } /** @deprecated will be removed in a future release */ @Deprecated public DeterministicSeed(EncryptedData encryptedMnemonic, @Nullable EncryptedData encryptedSeed, long creationTimeSecs) { this(encryptedMnemonic, encryptedSeed, creationTimeSecs > 0 ? Instant.ofEpochSecond(creationTimeSecs) : null); } /** Internal use only. */ private DeterministicSeed(List<String> mnemonicCode, @Nullable byte[] seed, String passphrase, @Nullable Instant creationTime) { this((seed != null ? seed : MnemonicCode.toSeed(mnemonicCode, Objects.requireNonNull(passphrase))), mnemonicCode, creationTime); } /** @deprecated use {@link #ofMnemonic(List, String, Instant)} or {@link #ofMnemonic(List, String)} */ @Deprecated public DeterministicSeed(List<String> mnemonicCode, @Nullable byte[] seed, String passphrase, long creationTimeSecs) { this(mnemonicCode, seed, passphrase, creationTimeSecs > 0 ? Instant.ofEpochSecond(creationTimeSecs) : null); } /** @deprecated use {@link #ofRandom(SecureRandom, int, String)} */ @Deprecated public DeterministicSeed(SecureRandom random, int bits, String passphrase) { this(getEntropy(random, bits), Objects.requireNonNull(passphrase), TimeUtils.currentTime().truncatedTo(ChronoUnit.SECONDS)); } /** Internal use only. */ private DeterministicSeed(byte[] entropy, String passphrase, @Nullable Instant creationTime) { checkArgument(entropy.length * 8 >= DEFAULT_SEED_ENTROPY_BITS, () -> "entropy size too small"); Objects.requireNonNull(passphrase); this.mnemonicCode = MnemonicCode.INSTANCE.toMnemonic(entropy); this.seed = MnemonicCode.toSeed(mnemonicCode, passphrase); this.encryptedMnemonicCode = null; this.encryptedSeed = null; this.creationTime = creationTime; } /** @deprecated use {@link #ofEntropy(byte[], String, Instant)} or {@link #ofEntropy(byte[], String)} */ @Deprecated public DeterministicSeed(byte[] entropy, String passphrase, long creationTimeSecs) { this(entropy, passphrase, creationTimeSecs > 0 ? Instant.ofEpochSecond(creationTimeSecs) : null); } private static byte[] getEntropy(SecureRandom random, int bits) { checkArgument(bits <= MAX_SEED_ENTROPY_BITS, () -> "requested entropy size too large"); byte[] seed = new byte[bits / 8]; random.nextBytes(seed); return seed; } @Override public boolean isEncrypted() { checkState(mnemonicCode != null || encryptedMnemonicCode != null); return encryptedMnemonicCode != null; } @Override public String toString() { return toString(false); } public String toString(boolean includePrivate) { MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues(); if (isEncrypted()) helper.addValue("encrypted"); else if (includePrivate) helper.addValue(toHexString()).add("mnemonicCode", getMnemonicString()); else helper.addValue("unencrypted"); return helper.toString(); } /** Returns the seed as hex or null if encrypted. */ @Nullable public String toHexString() { return seed != null ? ByteUtils.formatHex(seed) : null; } @Nullable @Override public byte[] getSecretBytes() { return getMnemonicAsBytes(); } @Nullable public byte[] getSeedBytes() { return seed; } @Nullable @Override public EncryptedData getEncryptedData() { return encryptedMnemonicCode; } @Override public Protos.Wallet.EncryptionType getEncryptionType() { return Protos.Wallet.EncryptionType.ENCRYPTED_SCRYPT_AES; } @Nullable public EncryptedData getEncryptedSeedData() { return encryptedSeed; } @Override public Optional<Instant> creationTime() { return Optional.ofNullable(creationTime); } /** * Sets the creation time of this seed. * @param creationTime creation time of this seed */ public void setCreationTime(Instant creationTime) { this.creationTime = Objects.requireNonNull(creationTime); } /** * Clears the creation time of this seed. This is mainly used deserialization and cloning. Normally you should not * need to use this, as keys should have proper creation times whenever possible. */ public void clearCreationTime() { this.creationTime = null; } /** @deprecated use {@link #setCreationTime(Instant)} */ @Deprecated public void setCreationTimeSeconds(long creationTimeSecs) { if (creationTimeSecs > 0) setCreationTime(Instant.ofEpochSecond(creationTimeSecs)); else if (creationTimeSecs == 0) clearCreationTime(); else throw new IllegalArgumentException("Cannot set creation time to negative value: " + creationTimeSecs); } public DeterministicSeed encrypt(KeyCrypter keyCrypter, AesKey aesKey) { checkState(encryptedMnemonicCode == null, () -> "trying to encrypt seed twice"); checkState(mnemonicCode != null, () -> "mnemonic missing so cannot encrypt"); EncryptedData encryptedMnemonic = keyCrypter.encrypt(getMnemonicAsBytes(), aesKey); EncryptedData encryptedSeed = keyCrypter.encrypt(seed, aesKey); return new DeterministicSeed(encryptedMnemonic, encryptedSeed, creationTime); } private byte[] getMnemonicAsBytes() { return getMnemonicString().getBytes(StandardCharsets.UTF_8); } public DeterministicSeed decrypt(KeyCrypter crypter, String passphrase, AesKey aesKey) { checkState(isEncrypted()); Objects.requireNonNull(encryptedMnemonicCode); List<String> mnemonic = decodeMnemonicCode(crypter.decrypt(encryptedMnemonicCode, aesKey)); byte[] seed = encryptedSeed == null ? null : crypter.decrypt(encryptedSeed, aesKey); return new DeterministicSeed(mnemonic, seed, passphrase, creationTime); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DeterministicSeed other = (DeterministicSeed) o; return Objects.equals(creationTime, other.creationTime) && Objects.equals(encryptedMnemonicCode, other.encryptedMnemonicCode) && Objects.equals(mnemonicCode, other.mnemonicCode); } @Override public int hashCode() { return Objects.hash(creationTime, encryptedMnemonicCode, mnemonicCode); } /** * Check if our mnemonic is a valid mnemonic phrase for our word list. * Does nothing if we are encrypted. * * @throws org.bitcoinj.crypto.MnemonicException if check fails */ public void check() throws MnemonicException { if (mnemonicCode != null) MnemonicCode.INSTANCE.check(mnemonicCode); } byte[] getEntropyBytes() throws MnemonicException { return MnemonicCode.INSTANCE.toEntropy(mnemonicCode); } /** Get the mnemonic code, or null if unknown. */ @Nullable public List<String> getMnemonicCode() { return mnemonicCode; } /** Get the mnemonic code as string, or null if unknown. */ @Nullable public String getMnemonicString() { return mnemonicCode != null ? InternalUtils.SPACE_JOINER.join(mnemonicCode) : null; } private static List<String> decodeMnemonicCode(byte[] mnemonicCode) { return decodeMnemonicCode(new String(mnemonicCode, StandardCharsets.UTF_8)); } private static List<String> decodeMnemonicCode(String mnemonicCode) { return InternalUtils.WHITESPACE_SPLITTER.splitToList(mnemonicCode); } }
15,711
40.787234
136
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/CoinSelection.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import org.bitcoinj.base.Coin; import org.bitcoinj.core.TransactionOutput; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Represents the results of a {@link CoinSelector#select(Coin, List)} operation. A coin selection represents a list * of spendable transaction outputs that sum together to a {@link #totalValue()} value gathered. Different coin selections * could be produced by different coin selectors from the same input set, according to their varying policies. */ public class CoinSelection { /** * @deprecated Use {@link #totalValue()} */ @Deprecated public final Coin valueGathered; /** * @deprecated Use {@link #outputs()} */ @Deprecated public final List<TransactionOutput> gathered; public CoinSelection(List<TransactionOutput> gathered) { this.valueGathered = sumOutputValues(gathered); this.gathered = gathered; } /** * @deprecated use {@link #CoinSelection(List)} */ @Deprecated public CoinSelection(Coin valueGathered, Collection<TransactionOutput> gathered) { // ignore valueGathered this(new ArrayList<>(gathered)); } private static Coin sumOutputValues(List<TransactionOutput> outputs) { return outputs.stream() .map(TransactionOutput::getValue) .reduce(Coin.ZERO, Coin::add); } /** * @return Total value of gathered outputs. */ public Coin totalValue() { return valueGathered; } /** * @return List of gathered outputs */ public List<TransactionOutput> outputs() { return gathered; } }
2,317
29.103896
122
java
bitcoinj
bitcoinj-master/core/src/main/java/org/bitcoinj/wallet/DefaultCoinSelector.java
/* * Copyright by the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bitcoinj.wallet; import com.google.common.annotations.VisibleForTesting; import org.bitcoinj.base.BitcoinNetwork; import org.bitcoinj.base.Coin; import org.bitcoinj.base.Network; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.core.TransactionOutput; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * This class implements a {@link CoinSelector} which attempts to get the highest priority * possible. This means that the transaction is the most likely to get confirmed. Note that this means we may end up * "spending" more priority than would be required to get the transaction we are creating confirmed. */ public class DefaultCoinSelector implements CoinSelector { private final Network network; protected DefaultCoinSelector() { this.network = null; } private DefaultCoinSelector(Network network) { this.network = network; } @Override public CoinSelection select(Coin target, List<TransactionOutput> candidates) { ArrayList<TransactionOutput> selected = new ArrayList<>(); // Sort the inputs by age*value so we get the highest "coindays" spent. // TODO: Consider changing the wallets internal format to track just outputs and keep them ordered. ArrayList<TransactionOutput> sortedOutputs = new ArrayList<>(candidates); // When calculating the wallet balance, we may be asked to select all possible coins, if so, avoid sorting // them in order to improve performance. if (!target.equals(BitcoinNetwork.MAX_MONEY)) { sortOutputs(sortedOutputs); } // Now iterate over the sorted outputs until we have got as close to the target as possible or a little // bit over (excessive value will be change). long total = 0; for (TransactionOutput output : sortedOutputs) { if (total >= target.value) break; // Only pick chain-included transactions, or transactions that are ours and pending. if (!shouldSelect(output.getParentTransaction())) continue; selected.add(output); total = Math.addExact(total, output.getValue().value); } // Total may be lower than target here, if the given candidates were insufficient to create to requested // transaction. return new CoinSelection(selected); } @VisibleForTesting static void sortOutputs(ArrayList<TransactionOutput> outputs) { Collections.sort(outputs, (a, b) -> { int depth1 = a.getParentTransactionDepthInBlocks(); int depth2 = b.getParentTransactionDepthInBlocks(); Coin aValue = a.getValue(); Coin bValue = b.getValue(); BigInteger aCoinDepth = BigInteger.valueOf(aValue.value).multiply(BigInteger.valueOf(depth1)); BigInteger bCoinDepth = BigInteger.valueOf(bValue.value).multiply(BigInteger.valueOf(depth2)); int c1 = bCoinDepth.compareTo(aCoinDepth); if (c1 != 0) return c1; // The "coin*days" destroyed are equal, sort by value alone to get the lowest transaction size. int c2 = bValue.compareTo(aValue); if (c2 != 0) return c2; // They are entirely equivalent (possibly pending) so sort by hash to ensure a total ordering. BigInteger aHash = a.getParentTransactionHash().toBigInteger(); BigInteger bHash = b.getParentTransactionHash().toBigInteger(); return aHash.compareTo(bHash); }); } /** Sub-classes can override this to just customize whether transactions are usable, but keep age sorting. */ protected boolean shouldSelect(Transaction tx) { if (tx != null) { return isSelectable(tx, network); } return true; } /** * Helper to determine if this selector would select a given transaction. Note that in a regtest network outgoing * payments will likely not see propagation, so there is a special exception. * * @param tx transaction to determine if it would be selected * @param network network the transaction is on * @return true if it would be selected, false otherwise */ public static boolean isSelectable(Transaction tx, Network network) { // Only pick chain-included transactions, or transactions that are ours and pending. TransactionConfidence confidence = tx.getConfidence(); TransactionConfidence.ConfidenceType type = confidence.getConfidenceType(); return type.equals(TransactionConfidence.ConfidenceType.BUILDING) || type.equals(TransactionConfidence.ConfidenceType.PENDING) && confidence.getSource().equals(TransactionConfidence.Source.SELF) && // In regtest mode we expect to have only one peer, so we won't see transactions propagate. (confidence.numBroadcastPeers() > 0 || network == BitcoinNetwork.REGTEST); } public static CoinSelector get(Network network) { return new DefaultCoinSelector(network); } }
5,797
45.015873
117
java