forked from ZelCore-io/bip32-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.js
77 lines (57 loc) · 1.64 KB
/
chain.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
function DEFAULT_ADDRESS_FUNCTION (node) {
return node.getAddress()
}
function Chain (parent, k, addressFunction) {
k = k || 0
this.__parent = parent
this.addresses = []
this.addressFunction = addressFunction || DEFAULT_ADDRESS_FUNCTION
this.k = k
this.map = {}
}
Chain.prototype.__initialize = function () {
var address = this.addressFunction(this.__parent.derive(this.k))
this.map[address] = this.k
this.addresses.push(address)
}
Chain.prototype.clone = function () {
var chain = new Chain(this.__parent, this.k, this.addressFunction)
chain.addresses = this.addresses.concat()
for (var s in this.map) chain.map[s] = this.map[s]
return chain
}
Chain.prototype.derive = function (address, parent) {
var k = this.map[address]
if (k === undefined) return
parent = parent || this.__parent
return parent.derive(k)
}
Chain.prototype.find = function (address) {
return this.map[address]
}
Chain.prototype.get = function () {
if (this.addresses.length === 0) this.__initialize()
return this.addresses[this.addresses.length - 1]
}
Chain.prototype.getAll = function () {
if (this.addresses.length === 0) this.__initialize()
return this.addresses
}
Chain.prototype.getParent = function () {
return this.__parent
}
Chain.prototype.next = function () {
if (this.addresses.length === 0) this.__initialize()
var address = this.addressFunction(this.__parent.derive(this.k + 1))
this.k += 1
this.map[address] = this.k
this.addresses.push(address)
return address
}
Chain.prototype.pop = function () {
var address = this.addresses.pop()
delete this.map[address]
this.k -= 1
return address
}
module.exports = Chain