Skip to content

Commit

Permalink
vm: stateManager: add verifyProof
Browse files Browse the repository at this point in the history
  • Loading branch information
jochem-brouwer committed Mar 31, 2021
1 parent 01d5fcb commit 096d130
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions packages/vm/lib/state/stateManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
PrefixedHexString,
bnToHex,
bufferToHex,
rlp,
} from 'ethereumjs-util'
import { encode, decode } from 'rlp'
import Common from '@ethereumjs/common'
Expand Down Expand Up @@ -484,6 +485,43 @@ export default class DefaultStateManager implements StateManager {
return returnValue
}

/**
* Verify a proof. Throws if proof is invalid, otherwise returns true
* @param proof - The Proof to prove
*/
async verifyProof(proof: Proof): Promise<boolean> {
const rootHash = rlp.decode(toBuffer(proof.accountProof[0]))
const key = keccak256(toBuffer(proof.accountProof[proof.accountProof.length - 1]))
const accountProof = proof.accountProof.map((rlpString: PrefixedHexString) =>
toBuffer(rlpString)
)

// This returns the account if the trie is OK, verify that it matches the reported account
await Trie.verifyProof(rootHash, key, accountProof)

const storageRoot = toBuffer(proof.storageHash)

/* TODO verify that value matches the account */
await Promise.all(
proof.storageProof.map(async (stProof: StorageProof) => {
const storageProof = stProof.proof.map((value: PrefixedHexString) => toBuffer(value))
const storageValue = toBuffer(stProof.value)
const storageKey = toBuffer(stProof.key)

// TODO figure out in what case verifyProof returns null (empty trie?)
const reportedValue = <Buffer>await Trie.verifyProof(storageRoot, storageKey, storageProof)

if (!reportedValue.equals(storageValue)) {
throw 'Reported trie value does not match storage'
}
})
).catch((e) => {
throw e
})

return true
}

/**
* Gets the state-root of the Merkle-Patricia trie representation
* of the state of this StateManager. Will error if there are uncommitted
Expand Down

0 comments on commit 096d130

Please sign in to comment.