[feature] add basic decoding support for swarm

Signed-off-by: yenda <eric@status.im>
This commit is contained in:
yenda 2019-05-30 11:33:00 +02:00
parent 131b423a0a
commit 4b6e5763e1
No known key found for this signature in database
GPG Key ID: 0095623C0069DCE6
3 changed files with 40 additions and 13 deletions

View File

@ -105,8 +105,12 @@
:method "contenthash(bytes32)"
:params [(namehash ens-name)]
:on-success
(fn [hash]
(cb hash))}))
(fn [raw-hash]
;; NOTE: it would be better if our abi-spec/decode was able to do that
(let [hash (subs raw-hash 130)
[cid & hash-and-zeros] (string/split hash "1b20")
hash (str "0x" cid "1b20" (subs (apply str hash-and-zeros) 0 64))]
(cb hash)))}))
(defn content
[resolver ens-name cb]

View File

@ -23,17 +23,36 @@
hash))]
(str "0xe301" (hex/encode (b58/decode b58-hash))))))
(defn decode [hex]
(when (and hex (not= hex "0x")
(string/starts-with? hex "0xe30101")
;; TODO properly decode the CID
;; extract the content-type using varint ns
(= 78 (count hex)))
{:namespace :ipfs
:hash (-> hex
(subs 10)
hex/decode
b58/encode)}))
(defn decode
"TODO properly decode the CID
extract the content-type using varint ns"
[hex]
(when (and hex (not= hex "0x"))
(cond
(and (string/starts-with? hex "0xe40101"))
;; content type can be 2 or 4 bytes
;; we expect 1b20 (hash algorithm and hash length 64)
;; before the hash so we split the contenthash there
(when-let [hash (second (string/split hex "1b20"))]
(when (= 0x20 (count hash)))
{:namespace :swarm
:hash hash})
(and (= 78 (count hex))
(string/starts-with? hex "0xe3010170"))
;; for retrocompatibility with old CIDv0
{:namespace :ipfs
:hash (-> hex
(subs 10)
hex/decode
b58/encode)}
(and (= 78 (count hex))
(string/starts-with? hex "0xe30101"))
;; new CIDv1
{:namespace :ipfs
:hash (str "z" (-> hex
(subs 6)
hex/decode
b58/encode))})))
(fx/defn cat
[cofx {:keys [contenthash on-success on-failure]}]

View File

@ -10,6 +10,10 @@
(is (= (contenthash/decode "0xe3010170122029f2d17be6139079dc48696d1f582a8530eb9805b561eda517e22a892c7e3f1f")
{:namespace :ipfs
:hash "QmRAQB6YaCyidP37UdDnjFY5vQuiBrcqdyoW1CuDgwxkD4"})))
(testing "decoding a valid swarm hash"
(is (= (contenthash/decode "0xe40101fa011b20d1de9994b4d039f6548d191eb26786769f580809256b4685ef316805265ea162")
{:namespace :swarm
:hash "d1de9994b4d039f6548d191eb26786769f580809256b4685ef316805265ea162"})))
(testing "decoding an invalid ipfs hash"
(is (nil? (contenthash/decode "0xe301122029f2d17be6139079dc48696d1f582a8530eb9805b561eda517e2"))))
(testing "decoding random garbage"