(bytecode: Hex)
| 22 | | ErrorType |
| 23 | |
| 24 | export function hashBytecode(bytecode: Hex): Uint8Array { |
| 25 | const bytecodeBytes = toBytes(bytecode) |
| 26 | if (bytecodeBytes.length % 32 !== 0) |
| 27 | throw new BytecodeLengthMustBeDivisibleBy32Error({ |
| 28 | givenLength: bytecodeBytes.length, |
| 29 | }) |
| 30 | |
| 31 | if (bytecodeBytes.length > maxBytecodeSize) |
| 32 | throw new BytecodeLengthExceedsMaxSizeError({ |
| 33 | givenLength: bytecodeBytes.length, |
| 34 | maxBytecodeSize, |
| 35 | }) |
| 36 | |
| 37 | const hashStr = sha256(bytecodeBytes) |
| 38 | const hash = toBytes(hashStr) |
| 39 | |
| 40 | // Note that the length of the bytecode |
| 41 | // should be provided in 32-byte words. |
| 42 | const bytecodeLengthInWords = bytecodeBytes.length / 32 |
| 43 | if (bytecodeLengthInWords % 2 === 0) { |
| 44 | throw new BytecodeLengthInWordsMustBeOddError({ |
| 45 | givenLengthInWords: bytecodeLengthInWords, |
| 46 | }) |
| 47 | } |
| 48 | |
| 49 | const bytecodeLength = toBytes(bytecodeLengthInWords) |
| 50 | |
| 51 | // The bytecode should always take the first 2 bytes of the bytecode hash, |
| 52 | // so we pad it from the left in case the length is smaller than 2 bytes. |
| 53 | const bytecodeLengthPadded = pad(bytecodeLength, { size: 2 }) |
| 54 | |
| 55 | const codeHashVersion = new Uint8Array([1, 0]) |
| 56 | hash.set(codeHashVersion, 0) |
| 57 | hash.set(bytecodeLengthPadded, 2) |
| 58 | |
| 59 | return hash |
| 60 | } |
no test coverage detected