1. Get a txid from one of my wallet transactions.
2. getrawtransaction (the txid). This gave me a hex string.
3. decoderawtransaction (the hex string). This gives me a single vin with a txid and a vout with two objects that each contained a scriptPubKey (my address was in one of them, and I assume the "change" address for the payer was in the other). I recorded the sum of the values of these two objects as PayerOriginalBalance.
4. getrawtransaction (the vin's txid). This gave me a large hex string.
5. decoderawtransaction (the large hex string). This gave me a vin that I am ignoring - it's how the payer got the bitcoin he sent me, right? It also gave me a vout that held two objects, each with an address. Only one of the objects had a value greater or equal to what I received (in fact, it was exactly 0.0005 more than PayerOriginalBalance - the Tx Fee, I assume). I assume that when there are multiple objects in the vout (usually two, the source and an address for change), the payer controls all of them, so any of them is suitable for the refund. That's why you wrote this, right?
Step 3 can give you multiple inputs (vin) but each has both a txid and a vout. The vout of each txid tells you which of the multiple outputs you see in step 5 to look at.
It isn't safe at all to assume that the payer controls anything other than the output he sent you. He could be spending his earnings from a mining pool. Those payments typically have many outputs, one to each participant in the pool.
Here's some Python code to get the return address (the address of the first input) given a txid from your wallet:
import json, posix, sys
bitcoind = "~/Bin/bitcoind"
def raw(tx):
return json.load(posix.popen("%s decoderawtransaction $(%s getrawtransaction %s)" % (bitcoind, bitcoind, tx)))
first_input = raw(sys.argv[1])['vin'][0]
print raw(first_input['txid'])['vout'][first_input['vout']]['scriptPubKey']['addresses'][0]
and an example of its use:
17org1nf9JJNfEQQuBir8VSNL16cfudo8t
The transaction I used has multiple inputs and outputs: