bitcoin-dev-project / bitcoiner-intro-to-rust

The Bitcoiner's Introduction to Rust
81 stars 23 forks source link

Edit Chapter 04 #13

Closed edilmedeiros closed 6 months ago

edilmedeiros commented 6 months ago

This has more heavy text changes, please review commits individually. In particular, I expanded the section about endianness which is a common source of confusion.

edilmedeiros commented 6 months ago

Man, the whole little vs. big-endian thing is so easy to understand and so hard to explain without confusing people...

All the other suggestions are already in a local commit here to not break the flow of discussion.

sb1752 commented 6 months ago

Hm, I see the confusion. I would simplify all this quite a bit. Something like the following:

"At its heart, Bitcoin is a communication protocol. For communication protocols, the endianness is crucial to understand because bytes will be sent in a specific sequence. If the receiver expects to see data in a different order from the sender, it will misinterpret that data. Thus, communication protocols specify which order bytes will be sent. In the Bitcoin protocol, bytes are transmitted in little-endian order. That means that the least significant byte is sent first.

When looking at decimal numbers, humans in the West typically read it from left to right with the most significant digit first to the least significant digit last. For example, in the number, 201, the most significant digit is 2 and the least significant digit is 1. But in the case of this transaction version data, the least significant byte will appear first as we just saw. This is a common cause of confusion when learning the Bitcoin protocol.

So, the version 1 field bytes are sent in the following order: “01” followed by three “00”s. “01” is the least significant byte and is sent first. So when doing base math to convert these bytes to integers, we can conceptualize it in reverse so that the “01” is in the least significant position. In other words, we can think of it as “00 00 00 01” and then do our normal base 16 math to convert this to an integer.

Don't forget that 01, two hexadecimal digits, represents a single byte and is to be taken as a unit (there's no little vs. big-endian dichotomy inside single bytes).

Now, we can do our normal base math which is 0 16^7 + ... + 1 16^0. We don't need to write all of it out since the other values will just be zero. Therefore the version number is just 1 * 16^0 which is 1."

edilmedeiros commented 6 months ago

Sounds good. Just committed it.

sb1752 commented 6 months ago

Looks great!