forked from ch4ot1c/btcp-store-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_wallet_address.js
205 lines (190 loc) · 5.62 KB
/
get_wallet_address.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
'use strict';
// Set initial details, also set here for global scoping reasons
var baseHDPubKey = ""
var addressIndex = 0
var widgetAddress = ""
// Output error according to our processScope
var outputError = function(error) {
if (processScope == "CLI") {
console.log(
'Error: '+error+
' for merchant ID: '+merchantID+
', wallet ID: '+walletID+
', address index: '+addressIndex+
', derived xpub: '+derivedXPub
);
}
/*
if (processScope == "browser") {
process.stderr.write(
'{\n'+
' "status" : "error",\n'+
' "statusMessage" : "'+error+'"\n'+
'}'
)
}
*/
}
// Detect if calling via CLi or API
const processScope = process.argv[2] == "-browser"
? "browser"
: "CLI"
// Get merchant ID, wallet ID and derived XPub
const merchantID = process.argv[3];
const walletID = process.argv[4];
const derivedXPub = process.argv[5];
// Check we have all we need to proceed
/*
TOOD - Get this revised and finalised
if (!merchantID || merchantID < 0 ||
!walletID || walletID < 0 ||
!derivedXPub) {
// outputError('Sorry, not all arguments expected were received');
}
*/
// Get bitcore and path
const bitcore = require('bitcore-lib');// BROKEN BIP32!!!
var path = require("path");
// Get Mongoose
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird'); //finally()
// Get schemas
const Merchant = require('./models.js').Merchant;
const Product = require('./models.js').Product;
// Get our options object
var options = require('read-config')(path.join(__dirname, '/../../bitcore-node.json')).servicesConfig['store-demo'];
// Set out dummy URL and start a connection
const DUMMY_MONGO_URL = 'mongodb://localhost:27017/store-demo';
mongoose.connect(options.mongoURL || DUMMY_MONGO_URL, null).then(m => {
if (processScope == "CLI") {
console.log(
'\n'+
'\x1b[36m'+
'============================================\n'+
'=== BITCOIN PRIVATE - MERCHANT SOLUTIONS ===\n'+
'=== SCRIPT: GET WALLET ADDRESS ===\n'+
'============================================\n'+
'\n\x1b[32m=== INFO ===\n'+
'\x1b[36mGenerating your wallet address to use within the BTCP widget...\n'
)
}
// Find our merchant & wallet combo
Merchant.findOne(
{
merchant_id : merchantID,
wallet_id : walletID
}
)
.exec()
.then(m => {
// If we have an entry for this combo
if (m) {
// IF not found xpub, insert an entry
if (m.xpub == null) {
try {
baseHDPubKey = new bitcore.HDPublicKey(derivedXPub);
} catch(error) {
outputError(error);
mongoose.disconnect();
process.exit(0);
}
// Save the derived xpub
m.xpub = derivedXPub;
return m.save();
// We have an xpub, increment address_index
} else {
// Get HD pub key and address index
try {
baseHDPubKey = new bitcore.HDPublicKey(m.xpub);
} catch(error) {
outputError(error);
mongoose.disconnect();
process.exit(0);
}
addressIndex = m.address_index;
// Increment address_index ready for next time
Merchant.update(
{'xpub': m.xpub},
{$inc: {address_index: 1}},
{multi: true},
function(err, result) {
mongoose.disconnect();
process.exit(0);
})
}
// No entry found, we need to create one
} else {
try {
baseHDPubKey = new bitcore.HDPublicKey(derivedXPub);
} catch(error) {
outputError(error);
mongoose.disconnect();
process.exit(0);
}
// Add the entry and set address_index to to 1 for next time
return Merchant.create({
merchant_id: merchantID,
wallet_id: walletID,
xpub: derivedXPub,
address_index: 1
},
function(err, result) {
mongoose.disconnect();
process.exit(0);
}
);
}
})
.then(m => {
// Generate the widget address based on derived HD pub key and address index
widgetAddress = getAddress(baseHDPubKey, addressIndex);
// Then output data in an appropriate format according to processScope
outputData();
// EXAMPLE - initial dummy product 'pizza'
// return Product.create({product_id: 1, invoice_id: 2, description: 'pizza', price_satoshis: '6912345678'});
})
.then(p => {
// EXAMPLE - display us product._id to test with
// console.log(`\x1b[33mDemo Product - ${p.name} - created in mongodb. product._id: \x1b[0m${p._id}`);
// console.log('\nTry it at localhost:8001/store-demo/index.html\n');
})
.catch(e => {
console.error(e);
})
.finally(() => {
// mongoose.disconnect();
// process.exit(0);
});
})
// Function to get widget address
var getAddress = (baseHDPublicKey, index) => {
try {
return baseHDPublicKey.deriveChild("m/0/" + index).publicKey.toAddress();
} catch(error) {
outputError(error);
}
}
// Output data according to our processScope
var outputData = function() {
if (processScope == "CLI") {
console.log(
"Merchant ID : "+merchantID+"\n"+
"Wallet ID : "+walletID+"\n"+
"Address Index : "+addressIndex+"\n"+
"Widget Address : "+widgetAddress+
"\n\x1b[0m"
);
}
if (processScope == "browser") {
process.stdout.write(
'{\n'+
' "status" : "ok",\n'+
' "statusMessage" : "success",\n'+
' "merchantID" : '+merchantID+',\n'+
' "walletID" : '+walletID+',\n'+
' "addressIndex" : '+addressIndex+',\n'+
' "widgetAddress" : "'+widgetAddress+'"\n'+
'}'
)
}
}