Chapter 5, Exercise 2: inputs parsing part of the `parse` method in `Tx` and the `parse` method for `TxIn`.
In the TxIn class, the solution for the parse method is as follows:
# tag::answer2.2[]
@classmethod
def parse(cls, s):
'''Takes a byte stream and parses the tx_input at the start.
Returns a TxIn object.
'''
prev_tx = s.read(32)[::-1]
prev_index = little_endian_to_int(s.read(4))
script_sig = Script.parse(s)
sequence = little_endian_to_int(s.read(4))
return cls(prev_tx, prev_index, script_sig, sequence)
# end::answer2.2[]
I've re-read through pages 87-96 a couple times looking for the rationale for this line of code
prev_tx = s.read(32)[::-1]
While I understand that [::-1] reverses the s.read(32), it's not clear to me why this is done. The best conclusion I could draw was: if there are multiple inputs, the bytes would be pushed onto the stack one after another resulting in the first input showing up last and the last input showing up first in the byte stream (i.e. Stack = LIFO).
Can someone help clarify this for me? Thanks!
While I understand that
[::-1]reverses thes.read(32), it's not clear to me why this is done.
I am new to this topic, but I believe that this quote from the learnmeabitcoin site sheds light on this issue:
TXID Byte Order: When you refer to a TXID within transaction data, you have to reverse the byte order to get it in its original format. The byte-order used when searching for a TXID is in reverse (due to a historical mistake in the way the original bitcoin client works).
P 93:
"Note that the previous transaction ID is 32 bytes and that the previous transaction index is 4 bytes. Both are in little-endian."