ivilata / pymultihash

Python implementation of the multihash specification
18 stars 8 forks source link

AttributeError: module 'multihash' has no attribute 'Multihash', how to verify ipfs hash #12

Closed avatar-lavventura closed 1 year ago

avatar-lavventura commented 4 years ago

[Q] Can I check the given ipfs-hash is valid or not?

I tried to follows the verification example but I am facing with following error: AttributeError: module 'multihash' has no attribute 'Multihash'

>>> import hashlib
>>> data = QmZT8e5XwdYz1gHkBaW4NUwXztYQjTCCkUeMYssWm93Swy'
>>> hash = hashlib.sha1(data)
>>> mh = Multihash.from_hash(hash)
>>> mh.verify(data)
True
>>> mh.verify(b'foo QmZT8e5XwdYz1gHkBaW4NUwXztYQjTCCkUeMYssWm93Swy')
False
ivilata commented 1 year ago

Hi @avatar-lavventura, that Qm… string looks like a base58-encoded multihash, so you first need to decode it into a Multihash instance, then you may use it to verify data. For instance:

>>> import multihash
>>> mh = multihash.decode(b'QmRJzsvyCQyizr73Gmms8ZRtvNxmgqumxc2KUp71dfEmoj', 'base58')  # hash of b'foo'
>>> mh.verify(b'foo')
True
>>> mh.verify(b'foo bar')
False

Please note that you'll need to have the base58 package installed (or install pymultihash with the base58 extra), and that you need to give the explicit encoding to decode, as it can't guess it.

avatar-lavventura commented 1 year ago

@ivilata Thanks, I had to install base58==2.1.1.

avatar-lavventura commented 1 year ago

Sorry, how did you get hash of b'foo'?

Like this?

$ echo "foo" > ff.tex
$ ipfs add --only-hash ff.txt
added QmYNmQKp6SuaVrpgWRsPTgCQCnpxUYGq76YEKBXuj2N4H6 ff.txt
ivilata commented 1 year ago

Hi! I got the hash of b'foo' like this:

>>> multihash.digest(b'foo', 'sha2-256').encode('base58')
b'QmRJzsvyCQyizr73Gmms8ZRtvNxmgqumxc2KUp71dfEmoj'

Since I remembered that IPFS' Qm… multihashes represent a base58-encoded SHA2-256 digest.

However, as explained in #3, while multihash.digest() hashes the raw byte string that you pass to it, IPFS does some wrapping on the data that you pass to ipfs add. This project's code knows nothing about the way IPFS wraps data, you'll need some external tool for that! :slightly_smiling_face: