11// SPDX-License-Identifier: Apache-2.0
22pragma solidity ^ 0.8.28 ;
33
4+ import "forge-std/console.sol " ;
45import "../ReadCbor.sol " ;
56
67// we will only encounter CID v1 dag-cbor sha256, which perfectly fits uint256.
@@ -45,10 +46,8 @@ library ReadCidSha256 {
4546 // 12 │ multihash type sha-256
4647 // 20 │ multihash size 32 bytes
4748 // ─────────┴─────────
48- bytes6 private constant cborTag42_cborBytes37_multibaseCidV1 = hex "D82A58250001 " ;
49- bytes1 private constant multicodecDagCbor = hex "71 " ;
50- bytes1 private constant multicodecRaw = hex "55 " ;
51- bytes2 private constant multihashSha256_multihashBytes32 = hex "1220 " ;
49+ bytes9 private constant cborTag42_cborBytes37_multibaseCidV1_multicodecZERO_multihashSha256_multihashBytes32 =
50+ hex "D82A58250001001220 " ;
5251
5352 /**
5453 * @notice Reads a CID from CBOR encoded data at the specified byte index
@@ -65,27 +64,30 @@ library ReadCidSha256 {
6564 * @return CidSha256 The representative hash
6665 */
6766 function Cid (bytes memory cbor , uint32 i ) internal pure returns (uint32 , CidSha256) {
68- return Cid (cbor, i, multicodecDagCbor );
67+ return Cid (cbor, i, 0x71 );
6968 }
7069
7170 function Cid (bytes memory cbor , uint32 i , bytes1 multicodec )
7271 internal
7372 pure
7473 returns (uint32 n , CidSha256 cidSha256 )
7574 {
76- assert (multicodec == multicodecDagCbor || multicodec == multicodecRaw);
77- bytes9 cborMultibase;
78- bytes9 expect =
79- bytes9 (bytes .concat (cborTag42_cborBytes37_multibaseCidV1, multicodec, multihashSha256_multihashBytes32));
80-
75+ bytes9 expect;
76+ bytes9 cborHeader;
8177 assembly ("memory-safe" ) {
78+ // expected head
79+ expect :=
80+ or (
81+ cborTag42_cborBytes37_multibaseCidV1_multicodecZERO_multihashSha256_multihashBytes32,
82+ shr (0x30 , multicodec)
83+ )
8284 // cbor header at index
83- cborMultibase := mload (add (cbor, add (0x20 , i)))
85+ cborHeader := mload (add (cbor, add (0x20 , i)))
8486 cidSha256 := mload (add (cbor, add (0x29 , i)))
8587 n := add (i, 41 ) // 4 bytes cbor header + 5 bytes multibase header + 32 bytes hash
8688 }
8789
88- require (cborMultibase == expect , "Expected CBOR tag 42 and 37-byte CIDv1 " );
90+ require (expect == cborHeader , "Expected CBOR tag 42 and 37-byte CIDv1 " );
8991 require (! cidSha256.isNull (), "Expected non-zero CID value " );
9092
9193 cbor.requireRange (n);
0 commit comments