diff --git a/src/status_im/ethereum/ens.cljs b/src/status_im/ethereum/ens.cljs index 0fed931683..dee1cd0643 100644 --- a/src/status_im/ethereum/ens.cljs +++ b/src/status_im/ethereum/ens.cljs @@ -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] diff --git a/src/status_im/utils/contenthash.cljs b/src/status_im/utils/contenthash.cljs index 162393ada2..fd3450df60 100644 --- a/src/status_im/utils/contenthash.cljs +++ b/src/status_im/utils/contenthash.cljs @@ -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]}] diff --git a/test/cljs/status_im/test/utils/contenthash.cljs b/test/cljs/status_im/test/utils/contenthash.cljs index 3b2a215515..edf16eaefc 100644 --- a/test/cljs/status_im/test/utils/contenthash.cljs +++ b/test/cljs/status_im/test/utils/contenthash.cljs @@ -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"