1. 程式人生 > >ethereumjs/merkle-patricia-tree-1-簡介

ethereumjs/merkle-patricia-tree-1-簡介

https://github.com/ethereumjs/merkle-patricia-tree

 

SYNOPSIS概要

This is an implementation of the modified merkle patricia tree as specified in the Ethereum's yellow paper.

這是以太坊黃皮書上指定的改良後的merkle patricia樹的實現。

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.
- Ethereum's yellow paper

修改後的Merkle Patricia樹(字首樹)提供了一個持久的資料結構來對映任意長度的二進位制資料(位元組陣列)。它是根據可變資料結構定義的,以對映256位二進位制片段和任意長度的二進位制資料。字首樹的核心和協議規範方面的惟一要求是提供一個32位元組的值,該值標識給定的一組鍵-值對。

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

支援的唯一備份儲存是通過levelup模組使用的LevelDB

 

INSTALL安裝

npm install merkle-patricia-tree

USAGE使用

Initialization and Basic Usage初始化和基本使用

var Trie = require('merkle-patricia-tree'),
level = require('level'),
db = level('./testdb'),
trie = new Trie(db);

trie.put('test', 'one', function () {
  trie.get('test', function (err, value) {
    if(value) console.log(value.toString())
  });
});

 

 

Merkle Proofs Merkle證明

Trie.prove(trie, 'test', function (err, prove) {
  if (err) return cb(err)
  Trie.verifyProof(trie.root, 'test', prove, function (err, value) {
    if (err) return cb(err)
    console.log(value.toString())
    cb()
  })
})

 

 

Read stream on Geth DB 讀取Geth資料庫中的流

var level = require('level')
var Trie = require('./secure')

var stateRoot = "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544" // Block #222

var db = level('YOUR_PATH_TO_THE_GETH_CHAIN_DB')
var trie = new Trie(db, stateRoot)

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

 

 

API

看本部落格的ethereumjs/merkle-patricia-tree-2-API

 

 

TESTING

npm test

 

 在區塊鏈上使用Merkle-Patricia樹儲存了四類資料:一個是某個賬戶中的賬戶狀態的stateRoot值,其key = account.serialize(),value = account state;以及三個字首樹root儲存在區塊頭上的資料:區塊鏈中的state(即整個區塊鏈上所有賬戶的資訊,key = address ,value = account.serialize());transaction(即整個區塊鏈上所有交易的資訊);transactionReceipt(即整個區塊鏈上所有交易收據的資訊)的資訊