jimmysong / programmingbitcoin

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

Chapter 7: help me understand decode_base58 #259

Closed Seriousaccident closed 2 years ago

Seriousaccident commented 2 years ago

I'm perplexed by this function on p. 139 and can't work it out for myself:

def decode_base58(s):
    num = 0
    for c in s:  # <1>
        num *= 58
        num += BASE58_ALPHABET.index(c)
    combined = num.to_bytes(25, byteorder='big')  # <2>
    checksum = combined[-4:]
    if hash256(combined[:-4])[:4] != checksum:
        raise ValueError('bad address: {} {}'.format(checksum, 
          hash256(combined[:-4])[:4]))
    return combined[1:-4]  # <3>`

The first thing I would expect us to do here would be to take the base58 string and convert it to the number it's supposed to represent. The opposite of something like this, from the encode_base58 function:


    while num > 0:
        num, mod = divmod(num, 58)
        result = BASE58_ALPHABET[mod] + result

Instead, we do this:


    for c in s: 
        num *= 58
        num += BASE58_ALPHABET.index(c)

Unless I'm reading it wrong, this is not a proper base58-to-int conversion so what is the purpose of this loop? Can someone help me parse this, please?

Seriousaccident commented 2 years ago

Solved. I realized I was calculating from the wrong end.