-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathkeygen.js
83 lines (78 loc) · 2.76 KB
/
keygen.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
var bitcore = require('bitcore-lib');
var HDKey = require('./models/HDKey');
var config = require('./config');
var network;
var HDPrivateKey = bitcore.HDPrivateKey;
if (config.bitcoin_network == "test") {
network = bitcore.Networks.testnet;
}
else {
network = bitcore.Networks.livenet;
}
function getPrivateKey() {
return new Promise((resolve, reject) => {
HDKey.find({}, (err, keys) => {
if (err) {
console.log("Error finding keys ", err);
reject(err);
}
else if (keys.length) {
console.log("HD Key found : ", keys[0].hdpublic);
var keyobj = {
hdpublic: keys[0].hdpublic,
index: keys[0].addressindex,
id: keys[0]._id
};
resolve(keyobj);
}
else {
console.log("No keys found, creating new HD keypair");
let hdPrivateKey = new HDPrivateKey(network);
let hdPublicKey = hdPrivateKey.hdPublicKey;
var hdkey = new HDKey({
hdprivate: hdPrivateKey,
hdpublic: hdPublicKey,
addressindex: 1
});
hdkey.save().then((savedkey) => {
console.log("Saved new HD Keypair ", savedkey);
var keyobj = {
hdpublic: hdPublicKey,
index: 1,
id: savedkey._id
};
resolve(keyobj);
});
}
});
});
}
function getDerivedAddress() {
return new Promise((resolve, reject) => {
getPrivateKey().then((keyobj) => {
let hdPublicKey = keyobj.hdpublic;
let index = keyobj.index;
if (hdPublicKey) {
var derivedAddress = new bitcore.Address(new bitcore.HDPublicKey(hdPublicKey).derive(index).publicKey, network);
console.log("Generated address = ", derivedAddress);
let return_obj = {
address: derivedAddress,
index: index
};
HDKey.findByIdAndUpdate(keyobj.id, { addressindex: index + 1 }, (err, res) => {
if(err) {
console.log("Error updating address index ", err);
}
else {
console.log("Update address index to " + res.addressindex);
resolve(return_obj);
}
});
}
else {
reject("Error getting key from database");
}
});
});
}
module.exports.getDerivedAddress = getDerivedAddress;