코드코코

[블록체인] 머클트리(merkle tree), 머클루트(merkrl root) 실습 본문

블록체인/이론

[블록체인] 머클트리(merkle tree), 머클루트(merkrl root) 실습

코드코코 2021. 12. 26. 19:18

Merkle tree

 

1. 모듈설치

$ npm i merkletreejs crypto-js

root@DESKTOP-RJ31OF5:/home/ubuntu/workspace/blockchain# npm i merkletreejs crypto-js

added 57 packages, removed 110 packages, and audited 60 packages in 15s

1 package is looking for funding
  run `npm fund` for details

found 0 vulnerabilities

 

2. test_merkleTree.js 작성

 

1. a 를 해쉬값으로 표현

// test_merkleTree.js

const SHA256 = require('crypto-js/sha256')
console.log(SHA256('a').toString())
~                                                                                                            ~

                   

2 .해쉬값을 배열로 나타내기

// test_merkleTree.js

const SHA256 = require('crypto-js/sha256')

const testSet = ['a', 'b', 'c', 'd', 'e']
const testArray = testSet.map(v => SHA256(v).toString())

console.log(testArray)

 

3. merkleTree 생성

// test_merkleTree.js

const { MerkleTree } = require('merkletreejs')

const SHA256 = require('crypto-js/sha256')

const testSet = ['a', 'b', 'c', 'd', 'e']
const testArray = testSet.map(v => SHA256(v).toString())

const testMerkleTree = new MerkleTree(testArray, SHA256)
console.log(testMerkleTree)

빨간박스 : 머클루트

4. merkle root 의 해쉬 값

// test_merkleTree.js

const { MerkleTree } = require('merkletreejs')

const SHA256 = require('crypto-js/sha256')


const testSet = ['a', 'b', 'c', 'd', 'e']
const testArray = testSet.map(v => SHA256(v).toString())

const testMerkleTree = new MerkleTree(testArray, SHA256)

//머클루트 값 
const merkleRoot = testMerkleTree.getRoot() 
console.log(merkleRoot.toString('hex'))

머클루트 해쉬 값

 

5. merkle root 검증

// test_merkleTree.js

const { MerkleTree } = require('merkletreejs')

const SHA256 = require('crypto-js/sha256')

const testSet = ['a', 'b', 'c', 'd', 'e']
const testArray = testSet.map(v => SHA256(v).toString())

const testMerkleTree = new MerkleTree(testArray, SHA256)

const merkleRoot = testMerkleTree.getRoot()

const testValue = 'a' //  a : true , u : false
const leaf = SHA256(testValue)
const proof = testMerkleTree.getProof(leaf)
console.log(proof) //검증된 값

const result = testMerkleTree.verify(proof, leaf, merkleRoot)
console.log(result) //검증 결과

 

- testValue 값이 a 인 경우

 

- testValue 값이 u 인 경우