How to use merkle-patricia-tree - 10 common examples

To help you get started, we’ve selected a few merkle-patricia-tree examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github maticnetwork / contracts / test / helpers / proofs.js View on Github external
export async function getTxProof(tx, block) {
  const txTrie = new Trie()
  for (let i = 0; i < block.transactions.length; i++) {
    const siblingTx = block.transactions[i]
    const path = rlp.encode(siblingTx.transactionIndex)
    const rawSignedSiblingTx = getTxBytes(siblingTx)
    await new Promise((resolve, reject) => {
      txTrie.put(path, rawSignedSiblingTx, err => {
        if (err) {
          reject(err)
        } else {
          resolve()
        }
      })
    })
  }

  // promise
github zmitton / eth-proof / verify.js View on Github external
static branchContains(path, branch){
    // console.log(path, branch)
    let complete, error, response = false
    let encodedBranch = []
    for (let i = 0; i < branch.length; i++) {
      encodedBranch.push(toHex(encode(branch[i])))
    }

    Trie.verifyProof(toHex(this.branchRootOf(branch)) , path, encodedBranch, (e,r)=>{
      error = e
      response = r
      complete = true
    })

    while(!complete){/*wait*/}

    if(error){
      throw Error(error)
    }else{
      return response
    }
  }
}
github trufflesuite / ganache-core / src / ledgers / ethereum / miner.ts View on Github external
// so the miner knows it should immediately mine another block once it is
      //  done with its current work.
      this.pending = pending;
      this.updatePricedHeap(pending);
      return;
    } else {
      this.setPricedHeap(pending);
    }
    this._isMining = true;

    const blockTransactions: Transaction[] = [];

    let blockGasLeft = this.options.gasLimit.toBigInt();
    
    let counter = 0;
    const transactionsTrie = new Trie(null, null);
    const receiptTrie = new Trie(null, null);
    const promises: Promise[] = [];
    const receipts: any[] = [];

    await this._checkpoint();

    const priced = this.priced;
    const rejectedTransactions: Transaction[] = [];
    const blockData = {
      blockTransactions,
      transactionsTrie,
      receiptTrie,
      gasUsed: 0n,
      receipts
    };
github maticnetwork / matic.js / src / helpers / proofs.js View on Github external
export async function getTxProof(tx, block) {
  const txTrie = new Trie()
  for (let i = 0; i < block.transactions.length; i++) {
    const siblingTx = block.transactions[i]
    const path = rlp.encode(siblingTx.transactionIndex)
    const rawSignedSiblingTx = getTxBytes(siblingTx)
    await new Promise((resolve, reject) => {
      txTrie.put(path, rawSignedSiblingTx, err => {
        if (err) {
          reject(err)
        } else {
          resolve()
        }
      })
    })
  }

  // promise
github trufflesuite / ganache-core / src / ledgers / ethereum / blockchain.ts View on Github external
database.on("ready", async () => {
      // TODO: get the latest block from the database
      // if we have a latest block, `root` will be that block's header.stateRoot
      // and we will skip creating the genesis block alltogether
      const root: Buffer = null;
      this.trie = new Trie(database.trie, root);
      this.blocks = new BlockManager(this, database.blocks);
      this.vm = this.createVmFromStateTrie(this.trie, options.hardfork, options.allowUnlimitedContractSize);

      const miner = new Miner(this.vm, options);
      this.transactions = new TransactionManager(this, database.transactions, options);
      this.accounts = new AccountManager(this);

      await this._initializeAccounts(options.accounts);
      let lastBlock = this._initializeGenesisBlock(options.timestamp, options.gasLimit);

      const readyNextBlock = async () => {
        const previousBlock = await lastBlock;
        const previousHeader = previousBlock.value.header;
        const previousNumber = Quantity.from(previousHeader.number).toBigInt() || 0n;
        return this.blocks.createBlock({
          number: Quantity.from(previousNumber + 1n).toBuffer(),
github trufflesuite / ganache-core / src / ledgers / ethereum / miner.ts View on Github external
//  done with its current work.
      this.pending = pending;
      this.updatePricedHeap(pending);
      return;
    } else {
      this.setPricedHeap(pending);
    }
    this._isMining = true;

    const blockTransactions: Transaction[] = [];

    let blockGasLeft = this.options.gasLimit.toBigInt();
    
    let counter = 0;
    const transactionsTrie = new Trie(null, null);
    const receiptTrie = new Trie(null, null);
    const promises: Promise[] = [];
    const receipts: any[] = [];

    await this._checkpoint();

    const priced = this.priced;
    const rejectedTransactions: Transaction[] = [];
    const blockData = {
      blockTransactions,
      transactionsTrie,
      receiptTrie,
      gasUsed: 0n,
      receipts
    };

    // Run until we run out of items, or until the inner loop stops us.
github ethereumjs / ethereumjs-vm / lib / index.ts View on Github external
'constantinople',
        'petersburg',
        'istanbul',
        'muirGlacier',
      ]

      this._common = new Common(chain, hardfork, supportedHardforks)
    }

    // Set list of opcodes based on HF
    this._opcodes = getOpcodesForHF(this._common.hardfork()!)

    if (opts.stateManager) {
      this.stateManager = opts.stateManager
    } else {
      const trie = opts.state || new Trie()
      if (opts.activatePrecompiles) {
        for (let i = 1; i <= 8; i++) {
          trie.put(new BN(i).toArrayLike(Buffer, 'be', 20), new Account().serialize())
        }
      }
      this.stateManager = new StateManager({ trie, common: this._common })
    }

    this.pStateManager = new PStateManager(this.stateManager)

    this.blockchain = opts.blockchain || new Blockchain({ common: this._common })

    this.allowUnlimitedContractSize =
      opts.allowUnlimitedContractSize === undefined ? false : opts.allowUnlimitedContractSize

    // We cache this promisified function as it's called from the main execution loop, and
github ethereumjs / ethereumjs-vm / lib / state / stateManager.ts View on Github external
constructor(opts: StateManagerOpts = {}) {
    let common = opts.common
    if (!common) {
      common = new Common('mainnet', 'petersburg')
    }
    this._common = common

    this._trie = opts.trie || new Trie()
    this._storageTries = {} // the storage trie cache
    this._cache = new Cache(this._trie)
    this._touched = new Set()
    this._touchedStack = []
    this._checkpointCount = 0
    this._originalStorageCache = new Map()
  }
github ipld / js-ipld-ethereum / util / base-trie / resolver.js View on Github external
each(trieNode.getChildren(), (childData, next) => {
    let key = nibbleToPath(childData[0])
    let value = childData[1]
    if (EthTrieNode.isRawNode(value)) {
      // inline child root
      let childNode = new EthTrieNode(value)
      paths.push({
        path: key,
        value: childNode
      })
      // inline child non-leaf subpaths
      exports.treeFromObject(multicodec, childNode, options, (err, subtree) => {
        if (err) return next(err)
        subtree.forEach((path) => {
          path.path = key + '/' + path.path
        })
        paths = paths.concat(subtree)
        next()
      })
    } else {
github ipld / js-ipld-ethereum / util / createTrieResolver.js View on Github external
trieNode.getChildren().forEach(([nibble, value]) => {
    let valueToAdd
    if (EthTrieNode.isRawNode(value)) {
    // inline child root
      const childNode = new EthTrieNode(value)

      if (childNode.type === 'leaf') {
        // Make sure the object is nested correctly
        nibble.push(...childNode.getKey())
        valueToAdd = getLeafValue(childNode, leafResolver)
      } else {
        valueToAdd = childNode
      }
    } else {
    // other nodes link by hash
      valueToAdd = cidFromHash(codec, value)
    }
    addNibbleToObject(finalNode, nibble, valueToAdd)
  })