4.2.4 • Published 2 years ago

merkle-patricia-tree v4.2.4

Weekly downloads
103,498
License
MPL-2.0
Repository
github
Last release
2 years ago

merkle-patricia-tree

NPM Package GitHub Issues Actions Status Code Coverage Discord

This is an implementation of the modified merkle patricia tree as specified in the Ethereum Yellow Paper:

The modified Merkle Patricia tree (trie) provides a persistent data structure to map between arbitrary-length binary data (byte arrays). It is defined in terms of a mutable data structure to map between 256-bit binary fragments and arbitrary-length binary data. The core of the trie, and its sole requirement in terms of the protocol specification is to provide a single 32-byte value that identifies a given set of key-value pairs.

The only backing store supported is LevelDB through the levelup module.

INSTALL

npm install merkle-patricia-tree

USAGE

There are 3 variants of the tree implemented in this library, namely: BaseTrie, CheckpointTrie and SecureTrie. CheckpointTrie adds checkpointing functionality to the BaseTrie with the methods checkpoint, commit and revert. SecureTrie extends CheckpointTrie and is the most suitable variant for Ethereum applications. It stores values under the keccak256 hash of their keys.

By default, trie nodes are not deleted from the underlying DB to not corrupt older trie states (as of v4.2.0). If you are only interested in the latest state of a trie, you can switch to a delete behavior (e.g. if you want to save disk space) by using the deleteFromDB constructor option (see related release notes in the changelog for more details).

Initialization and Basic Usage

import level from 'level'
import { BaseTrie as Trie } from 'merkle-patricia-tree'

const db = level('./testdb')
const trie = new Trie(db)

async function test() {
  await trie.put(Buffer.from('test'), Buffer.from('one'))
  const value = await trie.get(Buffer.from('test'))
  console.log(value.toString()) // 'one'
}

test()

Proofs

Merkle Proofs

The createProof and verifyProof functions allow you to verify that a certain value does or does not exist within a Merkle-Patricia trie with a given root.

Proof of existence

The below code demonstrates how to construct and then verify a proof that proves that the key test that corresponds to the value one does exist in the given trie, so a proof of existence.

const trie = new Trie()

async function test() {
  await trie.put(Buffer.from('test'), Buffer.from('one'))
  const proof = await Trie.createProof(trie, Buffer.from('test'))
  const value = await Trie.verifyProof(trie.root, Buffer.from('test'), proof)
  console.log(value.toString()) // 'one'
}

test()

Proof of non-existence

The below code demonstrates how to construct and then verify a proof that proves that the key test3 does not exist in the given trie, so a proof of non-existence.

const trie = new Trie()

async function test() {
  await trie.put(Buffer.from('test'), Buffer.from('one'))
  await trie.put(Buffer.from('test2'), Buffer.from('two'))
  const proof = await Trie.createProof(trie, Buffer.from('test3'))
  const value = await Trie.verifyProof(trie.root, Buffer.from('test3'), proof)
  console.log(value.toString()) // null
}

test()

Invalid proofs

Note, if verifyProof detects an invalid proof, it throws an error. While contrived, the below example demonstrates the error condition that would result if a prover tampers with the data in a merkle proof.

const trie = new Trie()

async function test() {
  await trie.put(Buffer.from('test'), Buffer.from('one'))
  await trie.put(Buffer.from('test2'), Buffer.from('two'))
  const proof = await Trie.createProof(trie, Buffer.from('test2'))
  proof[1].reverse()
  try {
    const value = await Trie.verifyProof(trie.root, Buffer.from('test2'), proof)
    console.log(value.toString()) // results in error
  } catch (err) {
    console.log(err) // Missing node in DB
  }
}

test()

Range Proofs

The Trie.verifyRangeProof() function can be used to check whether the given leaf nodes and edge proof can prove the given trie leaves range is matched with the specific root (useful e.g. for snapsync).

Read stream on Geth DB

import level from 'level'
import { SecureTrie as Trie } from 'merkle-patricia-tree'

const db = level('YOUR_PATH_TO_THE_GETH_CHAIN_DB')
// Set stateRoot to block #222
const stateRoot = '0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544'
// Convert the state root to a Buffer (strip the 0x prefix)
const stateRootBuffer = Buffer.from(stateRoot.slice(2), 'hex')
// Initialize trie
const trie = new Trie(db, stateRootBuffer)

trie
  .createReadStream()
  .on('data', console.log)
  .on('end', () => {
    console.log('End.')
  })

Read Account State including Storage from Geth DB

import level from 'level'
import { Account, BN, bufferToHex, rlp } from 'ethereumjs-util'
import { SecureTrie as Trie } from 'merkle-patricia-tree'

const stateRoot = 'STATE_ROOT_OF_A_BLOCK'

const db = level('YOUR_PATH_TO_THE_GETH_CHAINDATA_FOLDER')
const trie = new Trie(db, stateRoot)

const address = 'AN_ETHEREUM_ACCOUNT_ADDRESS'

async function test() {
  const data = await trie.get(address)
  const acc = Account.fromAccountData(data)

  console.log('-------State-------')
  console.log(`nonce: ${acc.nonce}`)
  console.log(`balance in wei: ${acc.balance}`)
  console.log(`storageRoot: ${bufferToHex(acc.stateRoot)}`)
  console.log(`codeHash: ${bufferToHex(acc.codeHash)}`)

  const storageTrie = trie.copy()
  storageTrie.root = acc.stateRoot

  console.log('------Storage------')
  const stream = storageTrie.createReadStream()
  stream
    .on('data', (data) => {
      console.log(`key: ${bufferToHex(data.key)}`)
      console.log(`Value: ${bufferToHex(rlp.decode(data.value))}`)
    })
    .on('end', () => {
      console.log('Finished reading storage.')
    })
}

test()

Additional examples with detailed explanations are available here.

API

Documentation

TESTING

npm test

BENCHMARKS

There are two simple benchmarks in the benchmarks folder:

  • random.ts runs random PUT operations on the tree.
  • checkpointing.ts runs checkpoints and commits between PUT operations.

A third benchmark using mainnet data to simulate real load is also under consideration.

Benchmarks can be run with:

npm run benchmarks

To run a profiler on the random.ts benchmark and generate a flamegraph with 0x you can use:

npm run profiling

0x processes the stacks and generates a profile folder (<pid>.0x) containing flamegraph.html.

REFERENCES

EthereumJS

See our organizational documentation for an introduction to EthereumJS as well as information on current standards and best practices.

If you want to join for work or do improvements on the libraries have a look at our contribution guidelines.

LICENSE

MPL-2.0

@dojimanetwork/dojimajshezhouyuanrenchain@vocdoni/storage-proof-eth-js@vocdoni/storage-proof-eth@vocdoni/storage-proofs@minden-matic/maticjs@dexbank/dex-bank-lib@alayanetwork/ganache-core@cryptoeconomicslab/chamber-childchain@cryptoeconomicslab/chamber-operator@cryptoeconomicslab/plasma-chamber@cyclenetwork/cyclejs@davidqhr/ganache-core@dexon-foundation/ethereumjs-vm@dexon-foundation/ganache-core@biut-block/biutjs-database@biut-block/biutjs-datahandler@bowdo/ethereumjs-vm@bowdo/hardhat-celo@blossm/merkle-tree@bonsaiswap-lib/lib@bonsaiswapv3/core@bonsaiswapv3/deploy@borealisswap/borealis-swap-lib@gislik/ganache-cores-unitxs-js-ipld-ethereumverifiable-eth-rpcvitaefugiattestethweb3x-evmweb3x-evm-esweb3-proofswanache-corewanchainjs-blocksmart-syncsmart-sync-modifiedsol-unitsuntlaboriosamsuscipitiustosusybraid-coresotosophonjs-blocksophonjs-vmrp-ethereumjs-vmrubic-app-maticjstest-chaintest-hardhat-node18simplechainjs-vm@chakra-swap/core@chomtana/bas-relayhub-sdk@celo/ethereujs-vm@igniswap/igni-swap-lib@dolomite-exchange/hardhat@dm3-org/dm3-lib-storage@dragonfoundry/maticjs@aragon/web3-proofs@enkrypt.io/ethereumjs-vm@eth-optimism/ethereumjs-vm@eth-optimism/ganache-core@eth-optimism/hardhat-state-dumps@eth-optimism/rollup-contracts@everything-registry/sub-chunk-2156@gzeoneth/hardhat@gxchain2-ethereumjs/block@gxchain2-ethereumjs/vm@gxchain2/block@gxchain2/core@hop-exchange/contracts@aiwozhe/hardhat@afria/afria-libraries@0xhyperchain/vm@0yi0/ethereumjs-vm@innoswap/core@instadapp/iga-node@instadapp/interop-node@dvote/storage-proofs@dzejkop/hardhat@eliteswap/v2-core@gooddollar/bridge-app@gm-matic/maticjs@layerzerolabs/lz-proof-utility@layerzerolabs/proof-evm@juicemx/ganache-core@komenci/kit@kodinghandle/bullswap-lib@litedexdev/litedex-core-swap@maticnetwork/maticjs@maticnetwork/plasma@nextsmartchain/nextjs@materia-dex/materia-contracts-proxy@mongox/mxjs-datahandler@infinitebrahmanuniverse/nolb-mer@phated/hardhat@nodeberry/solidity-payment-processor@nomiclabs/ethereumjs-vm@nomiclabs/buidler@olympfin/olymp-swap-libextractoor@zigen/ethereumjs-vm
4.2.4

2 years ago

4.2.3

2 years ago

4.2.2

2 years ago

4.2.1

3 years ago

4.2.0

3 years ago

4.1.0

3 years ago

4.0.0

4 years ago

3.0.0

5 years ago

2.3.2

6 years ago

2.3.1

6 years ago

2.3.0

6 years ago

2.2.0

7 years ago

2.1.2

8 years ago

2.1.1

8 years ago

2.1.0

8 years ago

2.0.3

9 years ago

2.0.2

9 years ago

2.0.1

9 years ago

2.0.0

9 years ago

1.1.4

9 years ago

1.2.0

9 years ago

1.1.3

9 years ago

1.1.2

9 years ago

1.1.1

9 years ago

1.1.0

9 years ago

1.0.1

9 years ago

1.0.0

9 years ago

0.1.26

9 years ago

0.1.25

9 years ago

0.1.24

9 years ago

0.1.23

9 years ago

0.1.22

9 years ago

0.1.21

9 years ago

0.1.20

9 years ago

0.1.2-p

9 years ago

0.1.19

9 years ago

0.1.17

9 years ago

0.1.16

9 years ago

0.1.15

9 years ago

0.1.14

9 years ago

0.1.13

9 years ago

0.1.12

9 years ago

0.1.11

9 years ago

0.1.10

9 years ago

0.1.9

9 years ago

0.1.8

9 years ago

0.1.7

10 years ago

0.1.6

10 years ago

0.1.5

10 years ago

0.1.4

10 years ago

0.1.3

10 years ago

0.1.2

10 years ago

0.1.1

10 years ago

0.1.0

10 years ago

0.0.9

10 years ago

0.0.8

10 years ago

0.0.7

10 years ago

0.0.6

10 years ago

0.0.5

10 years ago

0.0.4

10 years ago

0.0.3

10 years ago

0.0.2

10 years ago

0.0.1

10 years ago