How To Find UTXO of Inputs Given A Bitcoin Transaction
How To Find UTXO of Inputs Given A Bitcoin Transaction
To retrieve a UTXO, you should query the database for UTXO with the transaction's
txid, which is the hash value.
The database ultimately is the blockchain itself. In a vanilla design, you can iterate
through the blockchain data structure for the txid. But there are a couple of other
things you may want to consider:
1. Besides the blockchain that consists of all the "verified" transactions, you may have some
floating transactions that are not verified, like the one you are currently handling. They
may spend some UTXOs of the blockchain. And your current transaction's input may be
the output of one of the floating transactions. Hence you should also iterate through these
floating transactions in order to validate or discard your current transaction, assuming
you have validated those floating transactions.
2. To iterate through the whole blockchain may be unnecessary since most outputs of the
transactions in it are already spent. To save your time, a cache for all the actual UTXOs
can be built as a summary, so that you only need to query this cache database for the txid
in order to validate your transaction. (Of course, you should then maintain this cache
database to ensure its consistency with the blockchain.)
In Bitcoin, the "verified" floating transactions are arranged in Mempool pending to be
mined (i.e., included in a block), and all the UTXOs are arranged as UTXO set in
LevelDB.
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
public Transaction() {
inputs = new ArrayList<Input>();
outputs = new ArrayList<Output>();
}
}
byte[] tx = new byte[rawTx.size()];
int i = 0;
for (Byte b : rawTx)
tx[i++] = b;
return tx;
}