1
1
I'm reading bitcoin core source code. I want to know how to get bitcoin address from CTxIn object.
I have a CTransaction object. I found the way how to get addresses from vout like the following. But I don't know about vin.
UniValue out(UniValue::VOBJ);
ScriptPubKeyToUniv(txout.scriptPubKey, out, true);
UniValue u = find_value(out, "addresses");
UniValue uv = u.getValues()[0];
newDestination = uv.get_str();
CTxIn has a scriptSig. I think I can get address from it.
CTxIn
https://dev.visucore.com/bitcoin/doxygen/class_c_tx_in.html
Update 1
I found how to get the pubkey by using ScriptToAsmStr. I know this works for only P2PKH address.
vector<string> array;
CScript s = _tx.vin[0].scriptSig;
string a = ScriptToAsmStr(s, true);
boost::algorithm::split(array, a, boost::is_any_of(" "));
if (array.size() == 2) {
cout << array[1] << endl; // 0396f8781a4900372a5d72d84718d146170d5983e67dff8b4a28fef80690c09767
}
I'm now looking into how to convert the pubkey to bitcoin address on mainnet.
Update 2
I tried it like following but "invalid" is showed..
const char *cstr = "0396f8781a4900372a5d72d84718d146170d5983e67dff8b4a28fef80690c09767";
std::vector<unsigned char> vec(cstr, cstr + strlen(cstr));
CPubKey pubkey(vec);
if (pubkey.IsValid()) {
cout << "valid" << endl;
} else {
cout << "invalid" << endl;
}
Update 3
Thanks to the Andrew Chow's answer, I could make a CPubKey object. All that is left is to output the bitcoin address from the object.
#include "utilstrencodings.h"
std::vector<unsigned char> vec = ParseHex("0396f8781a4900372a5d72d84718d146170d5983e67dff8b4a28fef80690c09767");
CPubKey pubkey(vec);
if (pubkey.IsValid()) {
cout << "valid" << endl;
} else {
cout << "invalid" << endl;
}
Update 4
Finally, I got a bitcoin address from a CTxIn object. I think this is not smart way. There might be other ways. And still not sure about CKeyID's meaning. I will look into it in detail.
CKeyID id = pubkey.GetID();
CBitcoinAddress address(id);
if (address.IsValid()) {
cout << "valid" << endl;
} else {
cout << "invalid" << endl;
}
cout << address.ToString() << endl; // 15L7U55PAsHLEpQkZqz62e3eqWd9AHb2DH