com.google.bitcoin.core
Class Utils

java.lang.Object
  extended by com.google.bitcoin.core.Utils

public class Utils
extends Object

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.


Field Summary
static String BITCOIN_SIGNED_MESSAGE_HEADER
          The string that prefixes all text messages signed using Bitcoin keys.
static byte[] BITCOIN_SIGNED_MESSAGE_HEADER_BYTES
           
static BigInteger CENT
          How many "nanocoins" there are in 0.01 BitCoins.
static BigInteger COIN
          How many "nanocoins" there are in a Bitcoin.
static Date mockTime
          If non-null, overrides the return value of now().
static BigInteger NEGATIVE_ONE
           
 
Constructor Summary
Utils()
           
 
Method Summary
static byte[] appendByte(byte[] bytes, byte b)
          Creates a copy of bytes and appends b to the end of it
static byte[] bigIntegerToBytes(BigInteger b, int numBytes)
          The regular BigInteger.toByteArray() method isn't quite what we often need: it appends a leading zero to indicate that the number is positive and may need padding.
static String bitcoinValueToFriendlyString(BigInteger value)
          Returns the given value in nanocoins as a 0.12 type string.
static String bitcoinValueToPlainString(BigInteger value)
           Returns the given value as a plain string denominated in BTC.
static String bytesToHexString(byte[] bytes)
          Returns the given byte array hex encoded.
static boolean checkBitLE(byte[] data, int index)
           
static byte[] copyOf(byte[] in, int length)
           
static long currentTimeMillis()
          Returns the current time in seconds since the epoch, or a mocked out equivalent.
static BigInteger decodeCompactBits(long compact)
           
static BigInteger decodeMPI(byte[] mpi, boolean hasLength)
          MPI encoded numbers are produced by the OpenSSL BN_bn2mpi function.
static byte[] doubleDigest(byte[] input)
          See doubleDigest(byte[], int, int).
static byte[] doubleDigest(byte[] input, int offset, int length)
          Calculates the SHA-256 hash of the given byte range, and then hashes the resulting hash again.
static byte[] doubleDigestTwoBuffers(byte[] input1, int offset1, int length1, byte[] input2, int offset2, int length2)
          Calculates SHA256(SHA256(byte range 1 + byte range 2)).
static byte[] encodeMPI(BigInteger value, boolean includeLength)
          MPI encoded numbers are produced by the OpenSSL BN_bn2mpi function.
static void finishMockSleep()
          Let the sleeping thread pass the synchronization point any number of times.
static byte[] formatMessageForSigning(String message)
          Given a textual message, returns a byte buffer formatted as follows:
static void int64ToByteStreamLE(long val, OutputStream stream)
           
static boolean isLessThanUnsigned(long n1, long n2)
          Work around lack of unsigned types in Java.
static boolean isWindows()
           
static int maxOfMostFreq(int... items)
           
static int maxOfMostFreq(List<Integer> items)
           
static Date now()
          Returns the current time, or a mocked out equivalent.
static byte[] parseAsHexOrBase58(String data)
          Attempts to parse the given string as arbitrary-length hex or base58 and then return the results, or null if neither parse was successful.
static void passMockSleep()
          Let sleeping thread pass the synchronization point.
static long readInt64(byte[] bytes, int offset)
           
static int readUint16BE(byte[] bytes, int offset)
           
static long readUint32(byte[] bytes, int offset)
           
static long readUint32BE(byte[] bytes, int offset)
           
static byte[] reverseBytes(byte[] bytes)
          Returns a copy of the given byte array in reverse order.
static byte[] reverseDwordBytes(byte[] bytes, int trimLength)
          Returns a copy of the given byte array with the bytes of each double-word (4 bytes) reversed.
static Date rollMockClock(int seconds)
          Advances (or rewinds) the mock clock by the given number of seconds.
static Date rollMockClockMillis(long millis)
          Advances (or rewinds) the mock clock by the given number of milliseconds.
static void setBitLE(byte[] data, int index)
           
static void setMockClock()
          Sets the mock clock to the current time.
static void setMockClock(long mockClock)
          Sets the mock clock to the given time (in seconds).
static void setMockSleep(boolean isEnable)
          Enable or disable mock sleep.
static byte[] sha256hash160(byte[] input)
          Calculates RIPEMD160(SHA256(input)).
static byte[] singleDigest(byte[] input, int offset, int length)
           
static void sleep(long millis)
          Sleep for a span of time, or mock sleep if enabled
static BigInteger toNanoCoins(int coins, int cents)
          Convert an amount expressed in the way humans are used to into nanocoins.
static BigInteger toNanoCoins(String coins)
          Convert an amount expressed in the way humans are used to into nanocoins.
static void uint32ToByteArrayBE(long val, byte[] out, int offset)
           
static void uint32ToByteArrayLE(long val, byte[] out, int offset)
           
static void uint32ToByteStreamLE(long val, OutputStream stream)
           
static void uint64ToByteArrayLE(long val, byte[] out, int offset)
           
static void uint64ToByteStreamLE(BigInteger val, OutputStream stream)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

NEGATIVE_ONE

public static final BigInteger NEGATIVE_ONE

BITCOIN_SIGNED_MESSAGE_HEADER

public static final String BITCOIN_SIGNED_MESSAGE_HEADER
The string that prefixes all text messages signed using Bitcoin keys.

See Also:
Constant Field Values

BITCOIN_SIGNED_MESSAGE_HEADER_BYTES

public static final byte[] BITCOIN_SIGNED_MESSAGE_HEADER_BYTES

COIN

public static final BigInteger COIN
How many "nanocoins" there are in a Bitcoin.

A nanocoin is the smallest unit that can be transferred using Bitcoin. The term nanocoin is very misleading, though, because there are only 100 million of them in a coin (whereas one would expect 1 billion.


CENT

public static final BigInteger CENT
How many "nanocoins" there are in 0.01 BitCoins.

A nanocoin is the smallest unit that can be transferred using Bitcoin. The term nanocoin is very misleading, though, because there are only 100 million of them in a coin (whereas one would expect 1 billion).


mockTime

public static volatile Date mockTime
If non-null, overrides the return value of now().

Constructor Detail

Utils

public Utils()
Method Detail

toNanoCoins

public static BigInteger toNanoCoins(int coins,
                                     int cents)
Convert an amount expressed in the way humans are used to into nanocoins.


bigIntegerToBytes

public static byte[] bigIntegerToBytes(BigInteger b,
                                       int numBytes)
The regular BigInteger.toByteArray() method isn't quite what we often need: it appends a leading zero to indicate that the number is positive and may need padding.

Parameters:
b - the integer to format into a byte array
numBytes - the desired size of the resulting byte array
Returns:
numBytes byte long array.

toNanoCoins

public static BigInteger toNanoCoins(String coins)
Convert an amount expressed in the way humans are used to into nanocoins.

This takes string in a format understood by BigDecimal.BigDecimal(String), for example "0", "1", "0.10", "1.23E3", "1234.5E-5".

Throws:
ArithmeticException - if you try to specify fractional nanocoins, or nanocoins out of range.

uint32ToByteArrayBE

public static void uint32ToByteArrayBE(long val,
                                       byte[] out,
                                       int offset)

uint32ToByteArrayLE

public static void uint32ToByteArrayLE(long val,
                                       byte[] out,
                                       int offset)

uint64ToByteArrayLE

public static void uint64ToByteArrayLE(long val,
                                       byte[] out,
                                       int offset)

uint32ToByteStreamLE

public static void uint32ToByteStreamLE(long val,
                                        OutputStream stream)
                                 throws IOException
Throws:
IOException

int64ToByteStreamLE

public static void int64ToByteStreamLE(long val,
                                       OutputStream stream)
                                throws IOException
Throws:
IOException

uint64ToByteStreamLE

public static void uint64ToByteStreamLE(BigInteger val,
                                        OutputStream stream)
                                 throws IOException
Throws:
IOException

doubleDigest

public static byte[] doubleDigest(byte[] input)
See doubleDigest(byte[], int, int).


doubleDigest

public static byte[] doubleDigest(byte[] input,
                                  int offset,
                                  int length)
Calculates the SHA-256 hash of the given byte range, and then hashes the resulting hash again. This is standard procedure in Bitcoin. The resulting hash is in big endian form.


singleDigest

public static byte[] singleDigest(byte[] input,
                                  int offset,
                                  int length)

doubleDigestTwoBuffers

public static byte[] doubleDigestTwoBuffers(byte[] input1,
                                            int offset1,
                                            int length1,
                                            byte[] input2,
                                            int offset2,
                                            int length2)
Calculates SHA256(SHA256(byte range 1 + byte range 2)).


isLessThanUnsigned

public static boolean isLessThanUnsigned(long n1,
                                         long n2)
Work around lack of unsigned types in Java.


bytesToHexString

public static String bytesToHexString(byte[] bytes)
Returns the given byte array hex encoded.


reverseBytes

public static byte[] reverseBytes(byte[] bytes)
Returns a copy of the given byte array in reverse order.


reverseDwordBytes

public static byte[] reverseDwordBytes(byte[] bytes,
                                       int trimLength)
Returns a copy of the given byte array with the bytes of each double-word (4 bytes) reversed.

Parameters:
bytes - length must be divisible by 4.
trimLength - trim output to this length. If positive, must be divisible by 4.

readUint32

public static long readUint32(byte[] bytes,
                              int offset)

readInt64

public static long readInt64(byte[] bytes,
                             int offset)

readUint32BE

public static long readUint32BE(byte[] bytes,
                                int offset)

readUint16BE

public static int readUint16BE(byte[] bytes,
                               int offset)

sha256hash160

public static byte[] sha256hash160(byte[] input)
Calculates RIPEMD160(SHA256(input)). This is used in Address calculations.


bitcoinValueToFriendlyString

public static String bitcoinValueToFriendlyString(BigInteger value)
Returns the given value in nanocoins as a 0.12 type string. More digits after the decimal place will be used if necessary, but two will always be present.


bitcoinValueToPlainString

public static String bitcoinValueToPlainString(BigInteger value)

Returns the given value as a plain string denominated in BTC. The result is unformatted with no trailing zeroes. For instance, an input value of BigInteger.valueOf(150000) nanocoin gives an output string of "0.0015" BTC

Parameters:
value - The value in nanocoins to convert to a string (denominated in BTC)
Throws:
IllegalArgumentException - If the input value is null

decodeMPI

public static BigInteger decodeMPI(byte[] mpi,
                                   boolean hasLength)
MPI encoded numbers are produced by the OpenSSL BN_bn2mpi function. They consist of a 4 byte big endian length field, followed by the stated number of bytes representing the number in big endian format (with a sign bit).

Parameters:
hasLength - can be set to false if the given array is missing the 4 byte length field

encodeMPI

public static byte[] encodeMPI(BigInteger value,
                               boolean includeLength)
MPI encoded numbers are produced by the OpenSSL BN_bn2mpi function. They consist of a 4 byte big endian length field, followed by the stated number of bytes representing the number in big endian format (with a sign bit).

Parameters:
includeLength - indicates whether the 4 byte length field should be included

decodeCompactBits

public static BigInteger decodeCompactBits(long compact)

rollMockClock

public static Date rollMockClock(int seconds)
Advances (or rewinds) the mock clock by the given number of seconds.


rollMockClockMillis

public static Date rollMockClockMillis(long millis)
Advances (or rewinds) the mock clock by the given number of milliseconds.


setMockClock

public static void setMockClock()
Sets the mock clock to the current time.


setMockClock

public static void setMockClock(long mockClock)
Sets the mock clock to the given time (in seconds).


now

public static Date now()
Returns the current time, or a mocked out equivalent.


currentTimeMillis

public static long currentTimeMillis()
Returns the current time in seconds since the epoch, or a mocked out equivalent.


copyOf

public static byte[] copyOf(byte[] in,
                            int length)

appendByte

public static byte[] appendByte(byte[] bytes,
                                byte b)
Creates a copy of bytes and appends b to the end of it


parseAsHexOrBase58

public static byte[] parseAsHexOrBase58(String data)
Attempts to parse the given string as arbitrary-length hex or base58 and then return the results, or null if neither parse was successful.


isWindows

public static boolean isWindows()

formatMessageForSigning

public static byte[] formatMessageForSigning(String message)

Given a textual message, returns a byte buffer formatted as follows:

[24] "Bitcoin Signed Message:\n" [message.length as a varint] message


checkBitLE

public static boolean checkBitLE(byte[] data,
                                 int index)

setBitLE

public static void setBitLE(byte[] data,
                            int index)

sleep

public static void sleep(long millis)
Sleep for a span of time, or mock sleep if enabled


setMockSleep

public static void setMockSleep(boolean isEnable)
Enable or disable mock sleep. If enabled, set mock time to current time.


passMockSleep

public static void passMockSleep()
Let sleeping thread pass the synchronization point.


finishMockSleep

public static void finishMockSleep()
Let the sleeping thread pass the synchronization point any number of times.


maxOfMostFreq

public static int maxOfMostFreq(int... items)

maxOfMostFreq

public static int maxOfMostFreq(List<Integer> items)


Copyright © 2014. All rights reserved.