Encode `data` into a single EIP-4844 [`Blob`]. Returns a [`BlobEncodeError::DataTooLarge`] if the input exceeds [`BLOB_MAX_DATA_SIZE`] bytes.
(data: &[u8])
| 66 | /// Returns a [`BlobEncodeError::DataTooLarge`] if the input exceeds |
| 67 | /// [`BLOB_MAX_DATA_SIZE`] bytes. |
| 68 | pub fn encode(data: &[u8]) -> Result<Box<Blob>, BlobEncodeError> { |
| 69 | if data.len() > Self::BLOB_MAX_DATA_SIZE { |
| 70 | return Err(BlobEncodeError::DataTooLarge { size: data.len() }); |
| 71 | } |
| 72 | |
| 73 | // Pad the input so the encoder always has enough data to read from. |
| 74 | let mut input = vec![0u8; Self::BLOB_MAX_DATA_SIZE]; |
| 75 | input[..data.len()].copy_from_slice(data); |
| 76 | |
| 77 | let mut blob = Box::new(Blob::ZERO); |
| 78 | let out: &mut [u8; BYTES_PER_BLOB] = blob.as_mut(); |
| 79 | |
| 80 | // --- Round 0 (field elements 0..3) --- |
| 81 | // |
| 82 | // FE0 layout: [high_byte | version | len[1] | len[2] | len[3] | 27 payload bytes] |
| 83 | // |
| 84 | // The Base blob encoding stores payload data across field elements. |
| 85 | // Each field element is 32 bytes: [high_byte | 31 payload bytes]. |
| 86 | // Every 4 field elements the 4 high bytes carry 6-bit chunks that |
| 87 | // reassemble into 3 additional payload bytes (x, y, z). |
| 88 | // |
| 89 | // The decoder produces output in this order per round: |
| 90 | // [FE0 payload] [reassembled x] [FE1 payload] [reassembled y] |
| 91 | // [FE2 payload] [reassembled z] [FE3 payload] |
| 92 | |
| 93 | // Write version and 3-byte big-endian length into FE0. |
| 94 | let len_be = (data.len() as u32).to_be_bytes(); |
| 95 | out[VERSIONED_HASH_VERSION_KZG as usize] = Self::BLOB_ENCODING_VERSION; |
| 96 | out[2] = len_be[1]; |
| 97 | out[3] = len_be[2]; |
| 98 | out[4] = len_be[3]; |
| 99 | |
| 100 | // FE0 payload: 27 bytes (bytes 5..32). |
| 101 | out[5..32].copy_from_slice(&input[0..27]); |
| 102 | let mut ipos = 27usize; |
| 103 | |
| 104 | // Read the 3 reassembly bytes that get distributed across high bytes. |
| 105 | let x = input[ipos]; |
| 106 | ipos += 1; |
| 107 | // FE1 payload: 31 bytes. |
| 108 | out[33..64].copy_from_slice(&input[ipos..ipos + 31]); |
| 109 | ipos += 31; |
| 110 | let y = input[ipos]; |
| 111 | ipos += 1; |
| 112 | // FE2 payload: 31 bytes. |
| 113 | out[65..96].copy_from_slice(&input[ipos..ipos + 31]); |
| 114 | ipos += 31; |
| 115 | let z = input[ipos]; |
| 116 | ipos += 1; |
| 117 | // FE3 payload: 31 bytes. |
| 118 | out[97..128].copy_from_slice(&input[ipos..ipos + 31]); |
| 119 | ipos += 31; |
| 120 | |
| 121 | // Compute encoded high bytes from x, y, z (inverse of reassemble_bytes). |
| 122 | out[0] = x & 0x3F; |
| 123 | out[32] = ((x >> 6) & 0x03) << 4 | (y & 0x0F); |
| 124 | out[64] = z & 0x3F; |
| 125 | out[96] = ((y >> 4) & 0x0F) | (((z >> 6) & 0x03) << 4); |
no test coverage detected