|
| 1 | +import { Bool, Field, Poseidon } from "o1js"; |
| 2 | +import { RollupMerkleTree } from "@proto-kit/common"; |
| 3 | +import { |
| 4 | + BlockHashMerkleTree, |
| 5 | + BlockHashTreeEntry, |
| 6 | + BlockProverState, |
| 7 | + MandatoryProtocolModulesRecord, |
| 8 | + NetworkState, |
| 9 | + Protocol, |
| 10 | + ProtocolModulesRecord, |
| 11 | + ProvableBlockHook, |
| 12 | + RuntimeTransaction, |
| 13 | +} from "@proto-kit/protocol"; |
| 14 | +import { inject, injectable, Lifecycle, scoped } from "tsyringe"; |
| 15 | + |
| 16 | +import { |
| 17 | + Block, |
| 18 | + BlockResult, |
| 19 | + TransactionExecutionResult, |
| 20 | +} from "../../../storage/model/Block"; |
| 21 | +import { AsyncMerkleTreeStore } from "../../../state/async/AsyncMerkleTreeStore"; |
| 22 | +import { CachedMerkleTreeStore } from "../../../state/merkle/CachedMerkleTreeStore"; |
| 23 | +import { UntypedStateTransition } from "../helpers/UntypedStateTransition"; |
| 24 | +import type { StateRecord } from "../BatchProducerModule"; |
| 25 | + |
| 26 | +import { executeWithExecutionContext } from "./TransactionExecutionService"; |
| 27 | + |
| 28 | +function collectStateDiff( |
| 29 | + stateTransitions: UntypedStateTransition[] |
| 30 | +): StateRecord { |
| 31 | + return stateTransitions.reduce<Record<string, Field[] | undefined>>( |
| 32 | + (state, st) => { |
| 33 | + if (st.toValue.isSome.toBoolean()) { |
| 34 | + state[st.path.toString()] = st.toValue.value; |
| 35 | + } |
| 36 | + return state; |
| 37 | + }, |
| 38 | + {} |
| 39 | + ); |
| 40 | +} |
| 41 | + |
| 42 | +function createCombinedStateDiff(transactions: TransactionExecutionResult[]) { |
| 43 | + // Flatten diff list into a single diff by applying them over each other |
| 44 | + return transactions |
| 45 | + .map((tx) => { |
| 46 | + const transitions = tx.protocolTransitions.concat( |
| 47 | + tx.status.toBoolean() ? tx.stateTransitions : [] |
| 48 | + ); |
| 49 | + return collectStateDiff(transitions); |
| 50 | + }) |
| 51 | + .reduce<StateRecord>((accumulator, diff) => { |
| 52 | + // accumulator properties will be overwritten by diff's values |
| 53 | + return Object.assign(accumulator, diff); |
| 54 | + }, {}); |
| 55 | +} |
| 56 | + |
| 57 | +@injectable() |
| 58 | +@scoped(Lifecycle.ContainerScoped) |
| 59 | +export class BlockResultService { |
| 60 | + private readonly blockHooks: ProvableBlockHook<unknown>[]; |
| 61 | + |
| 62 | + public constructor( |
| 63 | + @inject("Protocol") |
| 64 | + protocol: Protocol<MandatoryProtocolModulesRecord & ProtocolModulesRecord> |
| 65 | + ) { |
| 66 | + this.blockHooks = |
| 67 | + protocol.dependencyContainer.resolveAll("ProvableBlockHook"); |
| 68 | + } |
| 69 | + |
| 70 | + public async generateMetadataForNextBlock( |
| 71 | + block: Block, |
| 72 | + merkleTreeStore: AsyncMerkleTreeStore, |
| 73 | + blockHashTreeStore: AsyncMerkleTreeStore, |
| 74 | + modifyTreeStore = true |
| 75 | + ): Promise<{ |
| 76 | + result: BlockResult; |
| 77 | + treeStore: CachedMerkleTreeStore; |
| 78 | + blockHashTreeStore: CachedMerkleTreeStore; |
| 79 | + }> { |
| 80 | + const combinedDiff = createCombinedStateDiff(block.transactions); |
| 81 | + |
| 82 | + const inMemoryStore = new CachedMerkleTreeStore(merkleTreeStore); |
| 83 | + const tree = new RollupMerkleTree(inMemoryStore); |
| 84 | + const blockHashInMemoryStore = new CachedMerkleTreeStore( |
| 85 | + blockHashTreeStore |
| 86 | + ); |
| 87 | + const blockHashTree = new BlockHashMerkleTree(blockHashInMemoryStore); |
| 88 | + |
| 89 | + await inMemoryStore.preloadKeys(Object.keys(combinedDiff).map(BigInt)); |
| 90 | + |
| 91 | + // In case the diff is empty, we preload key 0 in order to |
| 92 | + // retrieve the root, which we need later |
| 93 | + if (Object.keys(combinedDiff).length === 0) { |
| 94 | + await inMemoryStore.preloadKey(0n); |
| 95 | + } |
| 96 | + |
| 97 | + // TODO This can be optimized a lot (we are only interested in the root at this step) |
| 98 | + await blockHashInMemoryStore.preloadKey(block.height.toBigInt()); |
| 99 | + |
| 100 | + Object.entries(combinedDiff).forEach(([key, state]) => { |
| 101 | + const treeValue = state !== undefined ? Poseidon.hash(state) : Field(0); |
| 102 | + tree.setLeaf(BigInt(key), treeValue); |
| 103 | + }); |
| 104 | + |
| 105 | + const stateRoot = tree.getRoot(); |
| 106 | + const fromBlockHashRoot = blockHashTree.getRoot(); |
| 107 | + |
| 108 | + const state: BlockProverState = { |
| 109 | + stateRoot, |
| 110 | + transactionsHash: block.transactionsHash, |
| 111 | + networkStateHash: block.networkState.during.hash(), |
| 112 | + eternalTransactionsHash: block.toEternalTransactionsHash, |
| 113 | + blockHashRoot: fromBlockHashRoot, |
| 114 | + incomingMessagesHash: block.toMessagesHash, |
| 115 | + }; |
| 116 | + |
| 117 | + // TODO Set StateProvider for @state access to state |
| 118 | + const context = { |
| 119 | + networkState: block.networkState.during, |
| 120 | + transaction: RuntimeTransaction.dummyTransaction(), |
| 121 | + }; |
| 122 | + |
| 123 | + const executionResult = await executeWithExecutionContext( |
| 124 | + async () => |
| 125 | + await this.blockHooks.reduce<Promise<NetworkState>>( |
| 126 | + async (networkState, hook) => |
| 127 | + await hook.afterBlock(await networkState, state), |
| 128 | + Promise.resolve(block.networkState.during) |
| 129 | + ), |
| 130 | + context |
| 131 | + ); |
| 132 | + |
| 133 | + const { stateTransitions, methodResult } = executionResult; |
| 134 | + |
| 135 | + // Update the block hash tree with this block |
| 136 | + blockHashTree.setLeaf( |
| 137 | + block.height.toBigInt(), |
| 138 | + new BlockHashTreeEntry({ |
| 139 | + blockHash: Poseidon.hash([block.height, state.transactionsHash]), |
| 140 | + closed: Bool(true), |
| 141 | + }).hash() |
| 142 | + ); |
| 143 | + const blockHashWitness = blockHashTree.getWitness(block.height.toBigInt()); |
| 144 | + const newBlockHashRoot = blockHashTree.getRoot(); |
| 145 | + |
| 146 | + return { |
| 147 | + result: { |
| 148 | + afterNetworkState: methodResult, |
| 149 | + stateRoot: stateRoot.toBigInt(), |
| 150 | + blockHashRoot: newBlockHashRoot.toBigInt(), |
| 151 | + blockHashWitness, |
| 152 | + |
| 153 | + blockStateTransitions: stateTransitions.map((st) => |
| 154 | + UntypedStateTransition.fromStateTransition(st) |
| 155 | + ), |
| 156 | + blockHash: block.hash.toBigInt(), |
| 157 | + }, |
| 158 | + treeStore: inMemoryStore, |
| 159 | + blockHashTreeStore: blockHashInMemoryStore, |
| 160 | + }; |
| 161 | + } |
| 162 | +} |
0 commit comments