How does an SPV client forms a transaction which is then Broadcasted? As per my understanding, an SPV client only keeps a track of the block headers in its own database. So when a user tries to send bitcoins using that particular SPV client, how is the transaction constructed?

A user using that client will probably enter the amount he wants to send and the destination address. And he probably will be signed in using his private key.

So using these 3 data i.e. amount, destination and privateKey how will the SPV construct the whole transaction object.

Because I know that if I have to manually write a transaction by hand, I need:


Previous Transaction Hash (Funding Transaction).
Sequence Number of the UTXO I am trying to spend.
ScriptSig or the unlocking key, which is constructed using the privateKey and the hash of the entire transaction body.
Output Value.
ScriptPubKey which is constructed using the destination address.
SigHash Code.


So I am just supplying amount, destination and private key. How will the SPV client get the remaining values such as Prevout hash, sequence Number, how many UTXOs to be unlocked and how many new UTXOs should be formed?

It will be very helpful, if someone mentions a codebase where the implementation is given.
Generally speaking, the SPV wallet receives the transaction and a merkle-proof from a validating full-node when funds are sent to an address controlled by the wallet.

The merkle-proof guarantees that the transaction with the output spendable by the wallet is committed to the header of its local (strong) header-chain. Since the wallet controls the private keys to this output, it indexes this as a local UTXO, without any knowledge of the full UTXO set found on the validating node.

When spending funds to another address, the local wallet will solve for an optimal set of local UTXOs for this transaction. Prevout Points, spendable by the wallet are indexed as mentioned before. All other transaction fields you describe are independent of the UTXO, or can be inferred from the indexed previous transaction (e.g. timelocks enforced by CSV/CLTV output script operations). The destination address will tell the wallet what output to spend to, as is the case with all other wallet types (P2PKH, P2WPKH,P2SH, P2WSH etc).

The SPV wallet described above necessarily reveals the addresses it is interested in to receive merkle-proofs from the validating node. There are several techniques for the SPV client to improve privacy and leak less information, at a certain bandwidth cost.


Server side filters (e.g. Bloom filter (to be deprecated))
Client side filters (e.g. Neutrino)