programmingbitcoin icon indicating copy to clipboard operation
programmingbitcoin copied to clipboard

meaning of having if-statments at tx_fetcher's fetch method

Open owari-taro opened this issue 5 years ago • 1 comments

what does it mean to write this if -statement in TxFetcher's fetch method?

https://github.com/jimmysong/programmingbitcoin/blob/261a5115a35e1145b85236a4dd9036b5f111e90c/code-ch08/tx.py

if raw[4] == 0:
                raw = raw[:4] + raw[6:]
                tx = Tx.parse(BytesIO(raw), testnet=testnet)
                tx.locktime = little_endian_to_int(raw[-4:])
 else:
                tx = Tx.parse(BytesIO(raw), testnet=testnet)

Are there any problem with just writing like below?

 tx = Tx.parse(BytesIO(raw), testnet=testnet)

owari-taro avatar May 07 '20 08:05 owari-taro

I had the same question, it is unfortunate that this is not commented. raw[4] == 0 denotes that this is a Segwit transaction, where bytes 5, 6 are the Segwit marker and flag respectively, and are being cropped out here to awkwardly "simulate" a legacy transaction. The rest of transaction is identical except that a Segwit transaction also has witness bytes near the end, inserted just before the locktime. So this "legacy parsing" code will "buffer overflow" into the segwit witness when it tries to parse what it thinks is the locktime, which is why we see one more line here manually overriding the locktime to be (correctly) based on the last 4 bytes. See Chapter 13: Segwit for more details.

karpathy avatar May 02 '21 20:05 karpathy