-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgenerate_genesis_unit.js
279 lines (235 loc) · 8.93 KB
/
generate_genesis_unit.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/*jslint node: true */
"use strict";
var constants = require('byteballcore/constants.js');
var conf = require('./conf');
var fs = require('fs');
var objectHash = require('byteballcore/object_hash.js');
var Mnemonic = require('bitcore-mnemonic');
var ecdsaSig = require('byteballcore/signature.js');
var validation = require('byteballcore/validation.js');
conf.hub = '';
conf.deviceName = '';
function usage() {
console.error("\nusage: " + process.argv[0] + " " + process.argv[1] + " <path_to_genesis_config> <network_config_file> [-p]");
process.exit(1);
}
if(process.argv.length < 4) {
usage();
}
var genesisConfigFile = process.argv[2];
console.log("Using genesis config file: " + genesisConfigFile);
var outputNetworkConfigFile = process.argv[3];
console.log("Using output network config file: " + outputNetworkConfigFile);
var publish = false;
if(process.argv.length >= 5) {
var arg = process.argv[4];
if(arg === "-p") {
console.log("PUBLISH MODE!");
publish = true;
}
else {
console.log("Wrong argument: " + arg);
usage();
}
}
var genesisConfigData = {};
var networkConfig = {};
fs.readFile(genesisConfigFile, 'utf8', function(err, data) {
// set global data
genesisConfigData = JSON.parse(data);
console.log("Read genesis input data: %j", genesisConfigData);
if(publish === false) {
generateGenesisUnit();
}
else {
fs.readFile(outputNetworkConfigFile, 'utf8', function(err, data) {
// set global data
networkConfig = JSON.parse(data);
console.log("Read genesis input data: %j", networkConfig);
publishGenesisUnit();
});
}
});
function writeNetworkConfigFile(genesis_unit_hash) {
console.log("Writing network config file ...")
var networkConfig = {
witness_count: genesisConfigData.initial_witnesses.length,
version: genesisConfigData.version,
genesis_unit_hash: genesis_unit_hash,
genesis_unit: genesisConfigData.unit,
blackbytes_unit_hash: "<undefined>",
initial_witnesses: genesisConfigData.initial_witnesses,
initial_peers: genesisConfigData.initial_peers
};
fs.writeFile(outputNetworkConfigFile, JSON.stringify(networkConfig, null, '\t'), 'utf8', function(err) {
if (err) {
throw Error('failed to write ' + outputNetworkConfigFile + ': '+err);
}
process.exit(0);
});
}
function onError(err) {
throw Error(err);
}
function getConfEntryByAddress(address) {
for (let entry of genesisConfigData.initial_witnesses_definition) {
if(entry["address"] === address){
return entry;
}
}
return null;
}
function getDerivedKey(mnemonic_phrase, passphrase, account, is_change, address_index) {
var mnemonic = new Mnemonic(mnemonic_phrase);
var xPrivKey = mnemonic.toHDPrivateKey(passphrase);
console.log(">> about to create signature with private key: " + xPrivKey);
var path = "m/44'/0'/" + account + "'/"+is_change+"/"+address_index;
var derivedPrivateKey = xPrivKey.derive(path).privateKey;
console.log(">> derived key: " + derivedPrivateKey);
return derivedPrivateKey.bn.toBuffer({size:32}); // return as buffer
}
// signer that uses device address
var signer = {
readSigningPaths: function(conn, address, handleLengthsBySigningPaths){
handleLengthsBySigningPaths({r: constants.SIG_LENGTH});
},
readDefinition: function(conn, address, handleDefinition){
var conf_entry = getConfEntryByAddress(address);
// definition = JSON.parse(conf_entry["definition"]);
var definition = conf_entry["definition"];
handleDefinition(null, definition);
},
sign: function(objUnsignedUnit, assocPrivatePayloads, address, signing_path, handleSignature){
var buf_to_sign = objectHash.getUnitHashToSign(objUnsignedUnit);
var conf_entry = getConfEntryByAddress(address);
var derivedPrivateKey = getDerivedKey(
conf_entry["mnemonic_phrase"],
conf_entry["passphrase"],
0, 0, 0);
handleSignature(null, ecdsaSig.sign(buf_to_sign, derivedPrivateKey));
}
};
var validate = function(objJoint, onOk){
var unit = objJoint.unit.unit;
validation.validate(objJoint, {
ifUnitError: onError,
ifJointError: onError,
ifTransientError: onError,
ifNeedHashTree: function(){
onError('need hash tree for unit '+unit);
},
ifNeedParentUnits: function(){
onError('need parent units for unit '+unit);
},
ifOk: function(objValidationState, validation_unlock){
onOk();
},
ifOkUnsigned: function(bSerial){
onOk();
}
});
};
var onChangeError = function (change) {
console.log("Change: " + change.toString());
if(change > 0) {
throw Error("Investigate - change should be negative/zero but is bigger than zero: " + change);
}
generateGenesisUnit(Math.abs(change) + 1);
}
var onUnitOk = function (objJoint) {
// setup genesis unit hash to pass validation
constants.GENESIS_UNIT = objJoint.unit.unit;
validate(objJoint, function() {
console.log(">> Creation successful - hash: " + objJoint.unit.unit);
writeNetworkConfigFile(objJoint.unit.unit);
})
};
function generateGenesisUnit(change) {
var composer = require('byteballcore/composer.js');
composer.setGenesis(true);
console.log(">> composing genesis unit");
var payee_address = genesisConfigData.payout_address;
console.log(">> payout address: " + payee_address);
if(!change) {
console.log(">> NO CHANGE, first pass ...");
}
else {
console.log(">> FINAL PASS, creation cost is: " + change);
}
var arrOutputs = [
{address: genesisConfigData.initial_witnesses[0], amount: 0 } // the change
];
var remainingAmount = constants.TOTAL_WHITEBYTES;
for (let witness of genesisConfigData.initial_witnesses) {
for(var i=0; i<conf.witness_budget_count; ++i) {
arrOutputs.push({address: witness, amount: conf.witness_budget});
remainingAmount -= conf.witness_budget;
}
}
if(change) {
// if we got the change we need to subtract it from the reamining amount
// this is the cost of the genesis creation
remainingAmount -= change;
}
arrOutputs.push({address: payee_address, amount: remainingAmount});
// optional text message
var creation_message = genesisConfigData.creation_message;
var genesisUnitInput = {
paying_addresses: genesisConfigData.initial_witnesses,
outputs: arrOutputs,
signer: signer,
callbacks: {
ifNotEnoughFunds: onError,
ifError: onError,
ifChangeError: onChangeError,
ifOk: onUnitOk
},
witnesses: genesisConfigData.initial_witnesses,
messages: [{
app: "text",
payload_location: "inline",
payload_hash: objectHash.getBase64Hash(creation_message),
payload: creation_message
}]
}
console.log(">> Genesis Unit Input assembled: \n" + require('util').inspect(genesisUnitInput, {depth:null}));
// save to global config data
genesisConfigData.unit = JSON.parse(JSON.stringify(genesisUnitInput));
composer.composeJoint(genesisUnitInput);
}
function publishGenesisUnit() {
conf.hub = networkConfig.initial_peers[0];
var wss_hub = "wss://" + conf.hub;
console.log(">> Setting up hub: " + conf.hub);
var db = require('byteballcore/db.js');
var storage = require('byteballcore/storage.js');
var eventBus = require('byteballcore/event_bus.js');
eventBus.on('connected', internalPublish);
var network = require('byteballcore/network.js');
network.addPeer(wss_hub);
function internalPublish() {
console.log(">> Got connected ...");
var composer = require('byteballcore/composer.js');
composer.setGenesis(true);
var onUnitOk = function (objJoint) {
// setup genesis unit hash to pass validation
constants.GENESIS_UNIT = objJoint.unit.unit;
validate(objJoint, function() {
if (network.isConnected()) {
console.log(">> Genesis Unit validated - publishing ..." + objJoint.unit.unit);
network.broadcastJoint(objJoint);
}
})
};
var genesisUnitInput = networkConfig.genesis_unit;
console.log(">> Publishing Genesis Unit: \n" + require('util').inspect(genesisUnitInput, {depth:null}));
genesisUnitInput.signer = signer;
genesisUnitInput.callbacks = {
ifNotEnoughFunds: onError,
ifError: onError,
ifChangeError: onChangeError,
ifOk: onUnitOk
};
composer.composeJoint(genesisUnitInput);
}
}