2

I want to use this tool: http://blockchain.info/pushtx to push transaction. I don't understand the input data. It says it is hex string representation. I've read information about that in the raw transaction of the RPC API, but I am working with bitcoinj, it there a way to get this hex string ?

Thank you

EDIT: I want to do that to compose and broadcast a transaction

For now I did this:

final StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
try {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    transaction.bitcoinSerialize(os);
    byte[] bytes = os.toByteArray();
    for (byte b : bytes) {
        formatter.format("%02x", b);  
    }

    return sb.toString();
}catch (IOException e) {
    return "Couldn't serialize to hex string.";
} finally {
    formatter.close();
}
  • To compose and broadcast a transaction, or to re-broadcast a transaction that the network has already seen? – Stephen Gornick Mar 18 '13 at 17:35
  • To compose and broadcast a transaction. – Baptiste Pernet Mar 18 '13 at 18:43
  • I am using your code and it works very well, thanks – Riccardo Casatta Aug 28 '14 at 9:34
2

A shorter version could be:

String hex = DatatypeConverter.printHexBinary(tx.unsafeBitcoinSerialize());

Where the hex converter used is standard at least since Java 7:

http://docs.oracle.com/javase/7/docs/api/javax/xml/bind/DatatypeConverter.html

  • If you use unsafeBitcoinSerialize, make a note of the warnings in the API. – Nick ODell Sep 12 '14 at 15:49
  • 1
    As for the example, the result is only temporary used to convert it to hex and the discarded, so it's safe to be used this way. Problems arise only if you decide to modify the returned buffer. – Alessandro Polverini Sep 12 '14 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.