/
elkrem.js
147 lines (111 loc) · 2.54 KB
/
elkrem.js
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
'use strict';
var utils = require('bcoin/lib/utils/utils');
var crypto = require('bcoin/lib/crypto/crypto');
var bcoin = require('bcoin');
var constants = bcoin.constants;
/*
* Constants
*/
var maxIndex = 281474976710654; // 2^48 - 2
var maxHeight = 47;
/**
* Elkrem Sender
*/
function ElkremSender(root) {
this.root = root;
}
ElkremSender.prototype.getIndex = function getIndex(w) {
return descend(w, maxIndex, maxHeight, this.root);
};
/**
* Elkrem Receiver
*/
function ElkremReceiver(stack) {
this.stack = stack || [];
}
ElkremReceiver.prototype.addNext = function addNext(hash) {
var node = new ElkremNode(hash);
var t = this.stack.length - 1;
var left, right;
if (t >= 0)
node.i = this.stack[t].i + 1;
if (t > 0 && this.stack[t - 1].h === this.stack[t].h) {
node.h = this.stack[t].h + 1;
left = leftHash(hash);
right = rightHash(hash);
if (!utils.equal(this.stack[t - 1].hash, left))
throw new Error('Left child does not match.');
if (!utils.equal(this.stack[t].hash, right))
throw new Error('Right child does not match.');
this.stack.pop();
this.stack.pop();
}
this.stack.push(node);
};
ElkremReceiver.prototype.getIndex = function getIndex(w) {
var i, node, out;
if (this.stack.length === 0)
throw new Error('Nil receiver');
for (i = 0; i < this.stack.length; i++) {
node = this.stack[i];
if (w <= node.i) {
out = node;
break;
}
}
if (!out) {
throw new Error('Receiver has max '
+ this.stack[this.stack.length - 1].i
+ ', less than requested ' + w);
}
return descend(w, out.i, out.h, out.hash);
};
ElkremReceiver.prototype.upTo = function upTo() {
if (this.stack.length < 1)
return 0;
return this.stack[this.stack.length - 1].i;
};
/**
* Elkrem Node
*/
function ElkremNode(hash, h, i) {
this.hash = hash || constants.ZERO_HASH;
this.h = h || 0;
this.i = i || 0;
}
/*
* Helpers
*/
function leftHash(hash) {
return crypto.hash256(hash);
}
function rightHash(hash) {
var buf = new Buffer(33);
hash.copy(buf, 0);
buf[32] = 1;
return crypto.hash256(buf);
}
function descend(w, i, h, hash) {
var pow;
while (w < i) {
pow = Math.pow(2, h);
if (w <= i - pow) {
hash = leftHash(hash);
i -= pow;
} else {
hash = rightHash(hash);
i--;
}
if (h === 0)
break;
h--;
}
if (w !== i)
throw new Error('Cannot get index ' + w + ' from ' + i);
return hash;
}
/*
* Expose
*/
exports.ElkremSender = ElkremSender;
exports.ElkremReceiver = ElkremReceiver;