-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
79 lines (69 loc) · 2.1 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import Keccak from 'keccak'
// Left and Right are optional to allow to ascend up to the root tree element
interface MerkleNode {
hash: string
left?: MerkleNode
right?: MerkleNode
}
function merkleHash(left: Buffer, right: Buffer): string {
console.log(`Creating hash`)
return Keccak('keccak512')
.update(Buffer.concat([left, right]))
.digest('hex')
.toString()
}
function buildMerkleTree(transactions: string[]): MerkleNode {
if (transactions.length === 1) {
console.log('Accessing root', transactions[0])
return { hash: transactions[0] }
}
const middle: number = Math.ceil(transactions.length / 2)
const left: MerkleNode = buildMerkleTree(transactions.slice(0, middle))
const right: MerkleNode = buildMerkleTree(transactions.slice(middle))
return {
left,
right,
hash: merkleHash(
Buffer.from(left.hash, 'hex'),
Buffer.from(right.hash, 'hex')
),
}
}
function getMerkleProof(
root: MerkleNode,
targetedTransaction: string
): string[] {
const proof: string[] = []
function traverse(node: MerkleNode | undefined): boolean {
if (!node) {
return false
}
if (!node.left && !node.right && node.hash === targetedTransaction) {
return true
}
const leftFound: boolean = traverse(node.left)
const rightFound: boolean = traverse(node.right)
if (leftFound || rightFound) {
console.log(`pushing ${leftFound} || ${rightFound}`)
proof.push(node.left ? node.right!.hash : node.left!.hash)
}
return leftFound || rightFound
}
traverse(root)
return proof
}
const transactions: string[] = [
'Transaction1',
'Transaction2',
'Transaction3',
'Transaction4',
]
const merkleTree: MerkleNode = buildMerkleTree(transactions)
console.info('=== Building Merkle Tree')
console.log('Merkle Tree:', merkleTree)
console.log('Root hash:', merkleTree.hash)
console.info('=== Searching for proof')
const targetedTransaction = transactions[1]
console.log(`Targeted transaction ${targetedTransaction}`)
const merkleProof: string[] = getMerkleProof(merkleTree, targetedTransaction)
console.log(`Merkle Proof: ${merkleProof}`)