{"name":"merkle-patricia-tree","version":"0.1.16","description":"This is an implementation of the modified merkle patricia tree as speficed in the Ethereum's yellow paper.","main":"index.js","scripts":{"test":"./node_modules/mocha/bin/mocha --timeout 5000 --reporter spec ./test/"},"author":{"name":"mjbecze","email":"mjbecze@gmail.com"},"repository":{"type":"git","url":"https://github.com/wanderer/merkle-patricia-tree.git"},"bugs":{"url":"https://github.com/wanderer/merkle-patricia-tree/issues"},"keywords":["merkel","radix","trie","ethereum"],"license":"GPL","dependencies":{"async":">=0.8.0","crypto-js":"^3.1.2-5","levelup":"*","memdown":"^1.0.0","rlp":"*","semaphore":">=1.0.1","sha3":"~1.0.0"},"devDependencies":{"mocha":"~1.18.2","ethrereum-tests":"git+https://github.com/ethereum/tests.git#develop"},"browser":{"sha3":"./sha3.js"},"testling":{"files":"test/*.js","harness":"mocha-bdd","browsers":["chrome/22..latest","firefox/16..latest","safari/latest","opera/11.0..latest","iphone/6","ipad/6","android-browser/latest"]},"gitHead":"2eef4b4558897fd344cf8689f021bba9ade1bca1","homepage":"https://github.com/wanderer/merkle-patricia-tree","_id":"merkle-patricia-tree@0.1.16","_shasum":"f4a3bb8197ef15cb1dc8af05aad5a08bcf613a13","_from":".","_npmVersion":"1.4.14","_npmUser":{"name":"null_radix","email":"mjbecze@gmail.com"},"maintainers":[{"name":"null_radix","email":"null_radix@riseup.net"}],"dist":{"shasum":"f4a3bb8197ef15cb1dc8af05aad5a08bcf613a13","tarball":"http://registry-npm.ywwl.com/merkle-patricia-tree/download/merkle-patricia-tree-0.1.16.tgz","integrity":"sha512-kXfQ3HO5BgrjW95PklH3U708k2PCj8UUiqRzowGxFfWobepWyH2FiopMUnBwL+YL4v5kpm9jbEquZIuAs01Lfg==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIB9xN9jec3T31i6GAswu2gDjsVGjdrrlRUALjdrCkKdSAiAEN7zRYvrw2OuBB3CpjSXGJ+F2V4vaSbmKHBcwTfNUcQ=="}],"size":23802,"noattachment":false,"key":"/merkle-patricia-tree/-/merkle-patricia-tree-0.1.16.tgz"},"directories":{},"readme":"# merkle-patricia-tree\n\n[![NPM Package][trie-npm-badge]][trie-npm-link]\n[![GitHub Issues][trie-issues-badge]][trie-issues-link]\n[![Actions Status][trie-actions-badge]][trie-actions-link]\n[![Code Coverage][trie-coverage-badge]][trie-coverage-link]\n[![Discord][discord-badge]][discord-link]\n\nThis is an implementation of the modified merkle patricia tree as specified in the [Ethereum Yellow Paper](http://gavwood.com/Paper.pdf):\n\n> 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.\n\nThe only backing store supported is LevelDB through the `levelup` module.\n\n# INSTALL\n\n`npm install merkle-patricia-tree`\n\n# USAGE\n\nThere 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.\n\nBy 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).\n\n## Initialization and Basic Usage\n\n```typescript\nimport level from 'level'\nimport { BaseTrie as Trie } from 'merkle-patricia-tree'\n\nconst db = level('./testdb')\nconst trie = new Trie(db)\n\nasync function test() {\n  await trie.put(Buffer.from('test'), Buffer.from('one'))\n  const value = await trie.get(Buffer.from('test'))\n  console.log(value.toString()) // 'one'\n}\n\ntest()\n```\n\n## Proofs\n\n### Merkle Proofs\n\nThe `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.\n\n#### Proof of existence\n\nThe 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.\n\n```typescript\nconst trie = new Trie()\n\nasync function test() {\n  await trie.put(Buffer.from('test'), Buffer.from('one'))\n  const proof = await Trie.createProof(trie, Buffer.from('test'))\n  const value = await Trie.verifyProof(trie.root, Buffer.from('test'), proof)\n  console.log(value.toString()) // 'one'\n}\n\ntest()\n```\n\n#### Proof of non-existence\n\nThe 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.\n\n```typescript\nconst trie = new Trie()\n\nasync function test() {\n  await trie.put(Buffer.from('test'), Buffer.from('one'))\n  await trie.put(Buffer.from('test2'), Buffer.from('two'))\n  const proof = await Trie.createProof(trie, Buffer.from('test3'))\n  const value = await Trie.verifyProof(trie.root, Buffer.from('test3'), proof)\n  console.log(value.toString()) // null\n}\n\ntest()\n```\n\n#### Invalid proofs\n\nNote, 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.\n\n```typescript\nconst trie = new Trie()\n\nasync function test() {\n  await trie.put(Buffer.from('test'), Buffer.from('one'))\n  await trie.put(Buffer.from('test2'), Buffer.from('two'))\n  const proof = await Trie.createProof(trie, Buffer.from('test2'))\n  proof[1].reverse()\n  try {\n    const value = await Trie.verifyProof(trie.root, Buffer.from('test2'), proof)\n    console.log(value.toString()) // results in error\n  } catch (err) {\n    console.log(err) // Missing node in DB\n  }\n}\n\ntest()\n```\n\n### Range Proofs\n\nThe `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).\n\n## Read stream on Geth DB\n\n```typescript\nimport level from 'level'\nimport { SecureTrie as Trie } from 'merkle-patricia-tree'\n\nconst db = level('YOUR_PATH_TO_THE_GETH_CHAIN_DB')\n// Set stateRoot to block #222\nconst stateRoot = '0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544'\n// Convert the state root to a Buffer (strip the 0x prefix)\nconst stateRootBuffer = Buffer.from(stateRoot.slice(2), 'hex')\n// Initialize trie\nconst trie = new Trie(db, stateRootBuffer)\n\ntrie\n  .createReadStream()\n  .on('data', console.log)\n  .on('end', () => {\n    console.log('End.')\n  })\n```\n\n## Read Account State including Storage from Geth DB\n\n```typescript\nimport level from 'level'\nimport { Account, BN, bufferToHex, rlp } from 'ethereumjs-util'\nimport { SecureTrie as Trie } from 'merkle-patricia-tree'\n\nconst stateRoot = 'STATE_ROOT_OF_A_BLOCK'\n\nconst db = level('YOUR_PATH_TO_THE_GETH_CHAINDATA_FOLDER')\nconst trie = new Trie(db, stateRoot)\n\nconst address = 'AN_ETHEREUM_ACCOUNT_ADDRESS'\n\nasync function test() {\n  const data = await trie.get(address)\n  const acc = Account.fromAccountData(data)\n\n  console.log('-------State-------')\n  console.log(`nonce: ${acc.nonce}`)\n  console.log(`balance in wei: ${acc.balance}`)\n  console.log(`storageRoot: ${bufferToHex(acc.stateRoot)}`)\n  console.log(`codeHash: ${bufferToHex(acc.codeHash)}`)\n\n  const storageTrie = trie.copy()\n  storageTrie.root = acc.stateRoot\n\n  console.log('------Storage------')\n  const stream = storageTrie.createReadStream()\n  stream\n    .on('data', (data) => {\n      console.log(`key: ${bufferToHex(data.key)}`)\n      console.log(`Value: ${bufferToHex(rlp.decode(data.value))}`)\n    })\n    .on('end', () => {\n      console.log('Finished reading storage.')\n    })\n}\n\ntest()\n```\n\nAdditional examples with detailed explanations are available [here](https://github.com/gabrocheleau/merkle-patricia-trees-examples).\n\n# API\n\n[Documentation](./docs/README.md)\n\n# TESTING\n\n`npm test`\n\n# BENCHMARKS\n\nThere are two simple **benchmarks** in the `benchmarks` folder:\n\n- `random.ts` runs random `PUT` operations on the tree.\n- `checkpointing.ts` runs checkpoints and commits between `PUT` operations.\n\nA third benchmark using mainnet data to simulate real load is also under consideration.\n\nBenchmarks can be run with:\n\n```shell\nnpm run benchmarks\n```\n\nTo run a **profiler** on the `random.ts` benchmark and generate a flamegraph with [0x](https://github.com/davidmarkclements/0x) you can use:\n\n```shell\nnpm run profiling\n```\n\n0x processes the stacks and generates a profile folder (`<pid>.0x`) containing [`flamegraph.html`](https://github.com/davidmarkclements/0x/blob/master/docs/ui.md).\n\n# REFERENCES\n\n- Wiki\n  - [Ethereum Trie Specification](https://github.com/ethereum/wiki/wiki/Patricia-Tree)\n- Blog posts\n  - [Ethereum's Merkle Patricia Trees - An Interactive JavaScript Tutorial](https://rockwaterweb.com/ethereum-merkle-patricia-trees-javascript-tutorial/)\n  - [Merkling in Ethereum](https://blog.ethereum.org/2015/11/15/merkling-in-ethereum/)\n  - [Understanding the Ethereum Trie](https://easythereentropy.wordpress.com/2014/06/04/understanding-the-ethereum-trie/). Worth a read, but the Python libraries are outdated.\n- Videos\n  - [Trie and Patricia Trie Overview](https://www.youtube.com/watch?v=jXAHLqQthKw&t=26s)\n\n# EthereumJS\n\nSee our organizational [documentation](https://ethereumjs.readthedocs.io) for an introduction to `EthereumJS` as well as information on current standards and best practices.\n\nIf you want to join for work or do improvements on the libraries have a look at our [contribution guidelines](https://ethereumjs.readthedocs.io/en/latest/contributing.html).\n\n# LICENSE\n\n[MPL-2.0](<https://tldrlegal.com/license/mozilla-public-license-2.0-(mpl-2)>)\n\n[discord-badge]: https://img.shields.io/static/v1?logo=discord&label=discord&message=Join&color=blue\n[discord-link]: https://discord.gg/TNwARpR\n[trie-npm-badge]: https://img.shields.io/npm/v/merkle-patricia-tree.svg\n[trie-npm-link]: https://www.npmjs.com/package/merkle-patricia-tree\n[trie-issues-badge]: https://img.shields.io/github/issues/ethereumjs/ethereumjs-monorepo/package:%20trie?label=issues\n[trie-issues-link]: https://github.com/ethereumjs/ethereumjs-monorepo/issues?q=is%3Aopen+is%3Aissue+label%3A\"package%3A+trie\"\n[trie-actions-badge]: https://github.com/ethereumjs/ethereumjs-monorepo/workflows/Trie/badge.svg\n[trie-actions-link]: https://github.com/ethereumjs/ethereumjs-monorepo/actions?query=workflow%3A%22Trie%22\n[trie-coverage-badge]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/branch/master/graph/badge.svg?flag=trie\n[trie-coverage-link]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/tree/master/packages/trie\n","publish_time":1417962779891,"_cnpm_publish_time":1417962779891,"dist-tags":{"latest":"4.2.4"}}