james campbell wrote: > I have been currently trying to get a small piece of code to work, but > keep getting an error: > > header_bin = header_hex.decode('hex') > AttributeError: 'str' object has no attribute 'decode' > > > The source of this code is from: > https://en.bitcoin.it/wiki/Block_hashing_algorithm Here is the the code: > >>> import hashlib >>> header_hex = ("01000000" + > "81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000" + > "e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0f1fc122b" + > "c7f5d74d" + "f2b9441a" + "42a14695") >>> header_bin = > header_hex.decode('hex') >>> hash = > hashlib.sha256(hashlib.sha256(header_bin).digest()).digest() >>> > hash.encode('hex_codec') > '1dbd981fe6985776b644b173a4d0385ddc1aa2a829688d1e0000000000000000' >>> > hash[::-1].encode('hex_codec') > '00000000000000001e8d6829a8a21adc5d38d0a473b144b6765798e61f98bd1d' > > I get the above error when I input this line by line into Win7 IDLE 3.3.3. > Hopefully somebody can point me in the right direction. Thanks.
With the move from Python 2 to Python 3 string handling was changed py2 --> py3 ----------------- str --> bytes unicode --> str Also the encode decode methods have changed. bytes.decode() always gives you a str and str.encode() always returns bytes; there are no bytes.encode or str.decode methods. Unfortunately the bytes --> bytes conversion codecs in Python 2 have no convenient analog in Python 3 yet. This will change in Python 3.4, where you can use >>> import codecs >>> codecs.decode(b"ff10", "hex") b'\xff\x10' >>> codecs.encode(b"\xff\x10", "hex") b'ff10' But for now you are stuck with binascii.b2a_hex() etc. Converting the 2x code of your example to 3x gives >>> import hashlib >>> import binascii >>> header_hex = ( ... b"01000000" ... b"81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000" ... b"e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0f1fc122b" ... b"c7f5d74d" ... b"f2b9441a" ... b"42a14695") >>> header_bin = binascii.a2b_hex(header_hex) >>> hash = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest() >>> binascii.b2a_hex(hash) b'1dbd981fe6985776b644b173a4d0385ddc1aa2a829688d1e0000000000000000' >>> binascii.b2a_hex(hash[::-1]) b'00000000000000001e8d6829a8a21adc5d38d0a473b144b6765798e61f98bd1d' _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor