Skip to content

Instantly share code, notes, and snippets.

@s1na

s1na/ssz.ts Secret

Last active Oct 9, 2020
Embed
What would you like to do?
Code merkleization ssz schema
import { ContainerType, VectorType, ListType, ByteVectorType, NumberUintType, byteType } from '@chainsafe/ssz'
import { keccak256 } from 'ethereumjs-util'
// Each leaf in the code trie, which contains actual chunk code
const Chunk = new ContainerType({
fields: {
firstInstructionOffset: byteType,
codeChunk: new ListType({ elementType: byteType, limit: 32 }) // Last chunk could be shorter than 32 bytes
}
})
const Code = new ListType({ elementType: Chunk, limit: 1024 })
const Metadata = new ContainerType({
fields: {
metadataVersion: byteType,
codeHash: new ByteVectorType({ length: 32 }),
codeLength: new NumberUintType({ byteLength: 2 })
},
})
const CodeTrie = new ContainerType({
fields: {
metadata: Metadata,
code: Code
}
})
const bytecode = Buffer.from('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeedddddddddddddddddddddddddddddddddddddddddddddddddddddddd', 'hex')
const md = Metadata.defaultValue()
md.metadataVersion = 3
md.codeHash = keccak256(bytecode)
md.codeLength = bytecode.byteLength
const chunk0 = Chunk.defaultValue()
chunk0.firstInstructionOffset = 13
chunk0.codeChunk = bytecode.slice(0, 32)
const chunk1 = Chunk.defaultValue()
chunk1.firstInstructionOffset = 17
chunk1.codeChunk = bytecode.slice(32, 64)
const chunk2 = Chunk.defaultValue()
chunk2.firstInstructionOffset = 19
chunk2.codeChunk = bytecode.slice(64)
const code = [chunk0, chunk1, chunk2]
const codeTrie = CodeTrie.defaultValue()
codeTrie.metadata = md
codeTrie.code = code
const codeTrieT = CodeTrie.tree.defaultValue()
codeTrieT.metadata = md
codeTrieT.code = code
for (let i = 1; i < 40; i++) {
let n = codeTrieT.tree().getNode(BigInt(i))
console.log('GINDEX', i, ': ', n)
}
console.log('proof', codeTrieT.tree().getSingleProof(BigInt(12288)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment