jimmysong / programmingbitcoin

Repository for the book
Other
1.75k stars 656 forks source link

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

Open owari-taro opened 4 years ago

owari-taro commented 4 years ago

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)
karpathy commented 3 years ago

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.