Segwit txin. Witness data association I am trying to learn more about the bitcoin protocol and I am writing some python software to make a light wallet. I have advanced quite far and I have come across something that I dont really understand while reading about segregated witness protocol changes in terms of transactions.

https://bitcoincore.org/en/segwit_wallet_dev/

If you go here and read the part with a heading "Transaction Serialization" the text reads like so:


  If a txin is not associated with any witness data, its corresponding witness field is an exact 0x00, indicating that the number of witness stack items is zero.


How do I know if an input I am using in my script is associated with witness data? I have tried using public API's to look at the outputs I am using and I cant understand what it means. I see witness fields associated with the inputs of the transaction that produced the outputs I am trying to include in my transaction but not the other way around..
How do I know if an input I am using in my script is associated with witness data? I have tried using public API's to look at the outputs I am using and I cant understand what it means. I see witness fields associated with the inputs of the transaction that produced the outputs I am trying to include in my transaction but not the other way around.


I believe your confusion is due to this line 


  If a txin is not associated with any witness data, its corresponding witness field is an exact 0x00, indicating that the number of witness stack items is zero.


not applying to the serialization format, but to the contents.

A witness is always serialized as:


A variable-length integer indicating the number of witness stack items n.
For each of the n stack items:


A variable-length integer indicating the size of the stack element b
A b-byte array with the contents of that stack element.



A corollary is that an empty witness is always serialized as just a 0x00 byte (indicating that there are zero stack items).

So your serialization and parsing code does not need to know whether a particular txin has associated witness data. It just serializes/parses the witness, which may be empty.

It so happens that the validity rules require that the witness for a non-segwit spend always has to be empty, and as a result, the serialization of such a witness will always be just 0x00.