Post
Topic
Board Development & Technical Discussion
Merits 10 from 5 users
Re: Private key and filling change in bitcoin core v0.1
by
pooya87
on 05/03/2025, 14:22:31 UTC
⭐ Merited by ABCbits (4) ,DaveF (3) ,vapourminer (1) ,nc50lc (1) ,mcdouglasx (1)
// Fill vin
                foreach(CWalletTx* pcoin, setCoins)
                    for (int nOut = 0; nOut < pcoin->vout.size(); nOut++)
                        if (pcoin->vout[nOut].IsMine())
                            wtxNew.vin.push_back(CTxIn(pcoin->GetHash(), nOut));

I believe this is where a new adress is created for the change, is that correct?
I don't think so. "vin" is the list of inputs not outputs and here inside the loop it is just setting the input.

Quote
If so, how is it created exactly? I mean I am scanning the code to find where exactly is computed the private key of the change adress.
It looks like the change is being sent to the public key of one of the inputs a couple of lines above what you posted L2545. The code checks if the "coin" belongs to the wallet then extracts its pubkey script to be used for change.
Code:
// Fill vout[1] back to self with any change
if (nValueIn > nValue)
{
    // Use the same key as one of the coins
    vector<unsigned char> vchPubKey;
    CTransaction& txFirst = *(*setCoins.begin());
    foreach(const CTxOut& txout, txFirst.vout)
        if (txout.IsMine())
            if (ExtractPubKey(txout.scriptPubKey, true, vchPubKey))
                break;
    if (vchPubKey.empty())
        return false;

    // Fill vout[1] to ourself
    CScript scriptPubKey;
    scriptPubKey << vchPubKey << OP_CHECKSIG;
    wtxNew.vout.push_back(CTxOut(nValueIn - nValue, scriptPubKey));
}