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