-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathupdatePrivateKey.js
209 lines (176 loc) · 5.84 KB
/
updatePrivateKey.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
const {
Client,
PrivateKey,
AccountUpdateTransaction,
AccountId,
Mnemonic,
} = require('@hashgraph/sdk');
const fs = require('fs');
require('dotenv').config();
const exit = require('node:process');
const readlineSync = require('readline-sync');
function getArg(arg) {
const customIndex = process.argv.indexOf(`-${arg}`);
let customValue;
if (customIndex > -1) {
// Retrieve the value after --custom
customValue = process.argv[customIndex + 1];
}
return customValue;
}
function getArgFlag(arg) {
const customIndex = process.argv.indexOf(`-${arg}`);
if (customIndex > -1) {
return true;
}
return false;
}
async function main() {
const help = getArgFlag('h');
if (help) {
console.log('Usage: node updatePrivateKey.js [-acc <account>] [-pk <private key>] [-ecdsa] [-save [<file-name>]] [-test]');
console.log(' -acc <account> supply account to reset on commandline');
console.log(' **If not supplied will look for UPDATE_ACCT in .env **');
console.log(' -pk <private key> supply private key to reset on commandline');
console.log(' **If not supplied will look for OLD_KEY in .env **');
console.log(' -ecdsa use set new *edcsa* key (ED25519 by default)');
console.log(' -save use -save to save the *NEW* PK to file');
console.log(' **Supresses console output**');
console.log(' -save <filename> to specify the file to save to');
console.log(' -test run script without changing key');
console.log(' **Changing keys is scary - this lets you be double sure connfig looks right**');
process.exit(0);
}
// load details from the .env file
const operatorId = AccountId.fromString(process.env.MY_ACCOUNT_ID);
const operatorKey = PrivateKey.fromString(process.env.MY_PRIVATE_KEY);
const env = process.env.ENVIRONMENT ?? null;
// check the account / PK are valid
if (!operatorId || !operatorKey) {
console.log('Environment variables MY_ACCOUNT_ID and MY_PRIVATE_KEY must be present');
exit(1);
}
else {
console.log(`Using Account ${operatorId} as payer account`);
}
let client;
if (env == 'TEST') {
client = Client.forTestnet();
console.log('- Changing PK in *TESTNET*');
}
else if (env == 'MAIN') {
client = Client.forMainnet();
console.log('- Changing PK in *MAINNET*');
}
else {
console.log('ERROR: Must specify either MAIN or TEST as environment in .env file');
return;
}
client.setOperator(operatorId, operatorKey);
if (getArgFlag('test')) console.log('**TEST MODE**');
// check if save to file requested
let save = getArgFlag('save');
// if so see if a filename was supplied
let filename = getArg('save');
// check if user wants to save the PK to file
if (!save) {
save = readlineSync.keyInYNStrict('Do you want to save your new generated keys to file?\n**HIGHLY RECOMMENDED as if lost the wallet is inaccessible**');
}
let acctToChange;
if (getArgFlag('acc')) {
acctToChange = getArg('acc');
}
else {
acctToChange = process.env.UPDATE_ACCT;
}
let pkString;
if (getArgFlag('pk')) {
pkString = getArg('pk');
}
else {
pkString = process.env.OLD_KEY;
}
const oldKey = PrivateKey.fromString(pkString);
console.log('Generating new keys...');
// Generate New key
const mnemonic = await Mnemonic.generate();
let newKey;
if (getArgFlag('ecdsa')) {
// Generate new ECDSA key
console.log('Generating new ECDSA key...');
newKey = await mnemonic.toEcdsaPrivateKey();
}
else {
console.log('Generating new ED25519 key...');
newKey = await mnemonic.toEd25519PrivateKey();
}
// Save the new key to file
const outputString = 'Account:\n'
+ acctToChange
+ '\nMnemonic:\n'
+ mnemonic.toString()
+ '\nNew Private Key:\n'
+ newKey.toString()
+ '\nNew Public Key:\n'
+ newKey.publicKey;
if (save) {
// write to the filename specified
try {
// if no filename supllied use default
if (!filename) {
const startTime = new Date();
const timestamp = startTime.toISOString().split('.')[0].replaceAll(':', '-');
filename = `./${acctToChange}-PK-${timestamp}.txt`;
}
fs.writeFileSync(filename, outputString, { flag: 'w' }, function(err) {
if (err) {
console.log('ERROR occured - printing to console:\n', outputString);
return console.error(err);
}
// read it back in to be sure it worked.
fs.readFile(filename, 'utf-8', function(err) {
if (err) {
console.log('Reading file failed -- printing to console to ensure PK not lost');
console.log(outputString);
}
console.log('PK File created', filename);
});
});
}
catch (err) {
// If we fail to write it then spit out the values to command line so not lost
console.log('Error writing file -- bailing', err);
console.log(outputString);
exit(1);
}
}
else {
console.log(outputString);
}
if (!getArgFlag('test')) {
const proceed = readlineSync.keyInYNStrict('Do you want to proceed with changing the key on the account? (Last chance to cancel!)');
if (!proceed) {
console.log('Aborting...');
exit(1);
}
console.log('Updating account', acctToChange, 'with new Key...');
// Create the transaction to update the key on the account
const transaction = new AccountUpdateTransaction()
.setAccountId(acctToChange)
.setKey(newKey)
.freezeWith(client);
// Sign the transaction with the old key and new key
const signTx = await (await transaction.sign(oldKey)).sign(newKey);
// execute the signed transaction
const txResponse = await signTx.execute(client);
// Request the receipt of the transaction
const receipt = await txResponse.getReceipt(client);
// Get the transaction consensus status
const transactionStatus = receipt.status;
console.log('The transaction consensus status is ' + transactionStatus.toString());
}
else {
console.log('**TEST MODE** skipping interaction with Hedera network -- **NO KEYS CHANGED**');
}
}
main();