Gross transaction – Why do witnesses use value rather than length?

Note that cookies are not scripts. They do not contain opcode. These are stack elements. Cookies do not have explicit opcodes (witnessScripts are scripts but are only cookie elements, so their opcodes do not count).

The number is used because it clearly defines between the end of the stack elements for an entry and the beginning of the stack elements for the next entry. The use of an account follows the standard serialization methodology used elsewhere in Bitcoin for the serialization of arrays of elements. In this case, the input data of an input is an array of byte arrays (in code this is std :: vector <std :: vector>).

So, following the standard serialization method of std :: vectors, at the highest level, we obtain the number of items from the next level (ie the number of std :: vector elements) which is the number of elements in the stack. Then, at the next serialization level, we get another length for the number of elements in the lower level (ie the number of unsigned character in each vector). We now have the length of each element of the stack. Then comes the stack element itself.

The reason this method was used for segwit is probably due to the fact that the stacks in Bitcoin Core are implemented as std :: vector <std :: vector>. In addition, vector serialization in this manner is used throughout Bitcoin, so the corresponding serialization code already existed in all existing portfolio software.