-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·274 lines (230 loc) · 9.45 KB
/
index.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
#!/usr/bin/env node
// Import
import { ApiPromise, WsProvider } from '@polkadot/api';
import bip39 from 'bip39';
import crypto from 'crypto';
import fs from 'fs';
import Keyring from '@polkadot/keyring';
import { u8aToHex } from '@polkadot/util';
import { mnemonicToLegacySeed, hdEthereum } from '@polkadot/util-crypto';
import * as readlineSync from 'readline-sync';
let rpcUrl = 'wss://moonbeam-alpha.api.onfinality.io/public-ws'
function aesEncrypt(data, key) {
const cipher = crypto.createCipher('aes192', key);
var crypted = cipher.update(data, 'utf8', 'hex');
crypted += cipher.final('hex');
return crypted;
}
function aesDecrypt(encrypted, key) {
const decipher = crypto.createDecipher('aes192', key);
var decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
function encryptMemToFile(mnemonic, path, passwd) {
const data = aesEncrypt(mnemonic, passwd);
fs.writeFileSync(path, data);
}
// 计算私钥
function calPrivateKey(mnemonic) {
const index = 0;
const ethDerPath = "m/44'/60'/0'/0/" + index;
const privateKey = u8aToHex(
hdEthereum(mnemonicToLegacySeed(mnemonic, '', false, 64), ethDerPath).secretKey
);
return privateKey
}
// 解密助记词
function decryptMemByFile(path, passwd) {
try {
const data = fs.readFileSync(path, 'utf-8');
return aesDecrypt(data, passwd);
} catch (error) {
console.log(error)
throw Error('decryptMemError')
}
}
async function generateAccount(walletName, password, mnem = null) {
// Import Ethereum account from mnemonic
const keyringECDSA = new Keyring({ type: 'ethereum' });
const mnemonic = mnem || bip39.generateMnemonic();
encryptMemToFile(mnemonic, walletName, password);
// Define index of the derivation path and the derivation path
const index = 0;
const ethDerPath = "m/44'/60'/0'/0/" + index;
const subsDerPath = '//hard/soft';
console.log(`Mnemonic: ${mnemonic}`);
console.log(`--------------------------\n`);
// Extract Ethereum address from mnemonic
const newPairEth = keyringECDSA.addFromUri(`${mnemonic}/${ethDerPath}`);
console.log(`Ethereum Derivation Path: ${ethDerPath}`);
console.log(`Derived Ethereum Address from Mnemonic: ${newPairEth.address}`);
// Extract private key from mnemonic
const privateKey = u8aToHex(
hdEthereum(mnemonicToLegacySeed(mnemonic, '', false, 64), ethDerPath).secretKey
);
const publicKey = u8aToHex(
hdEthereum(mnemonicToLegacySeed(mnemonic, '', false, 64), ethDerPath).publicKey
);
console.log(`Derived Private Key from Mnemonic: ${privateKey}`);
console.log(`Derived Public Key from Mnemonic: ${publicKey}`);
console.log(`--------------------------\n`);
// Extract address from private key
const otherPair = await keyringECDSA.addFromUri(privateKey);
console.log(`Derived Address from Private Key: ${otherPair.address}`);
}
async function getBalanceAndNonce(addr = '0x5A26cAfE424afB8d9F478CE3cCcD2E5572483053') {
// Construct API provider
const wsProvider = new WsProvider(rpcUrl);
const api = await ApiPromise.create({ provider: wsProvider });
// Define wallet address
// const addr = '0xd0aedb77a9089f40a289247de3aab7cf7202df10';
// Retrieve the last timestamp
const now = await api.query.timestamp.now();
// Retrieve the account balance & current nonce via the system module
const { nonce, data: balance } = await api.query.system.account(addr);
// Retrieve the given account's next index/nonce, taking txs in the pool into account
const nextNonce = await api.rpc.system.accountNextIndex(addr);
console.log(`${now}: balance of ${balance.free} and a current nonce of ${nonce} and next nonce of ${nextNonce}`);
}
async function getChainStatus() {
// Construct API provider
const wsProvider = new WsProvider(rpcUrl);
const api = await ApiPromise.create({ provider: wsProvider });
// Retrieve the chain name
const chain = await api.rpc.system.chain();
// Retrieve the latest header
const lastHeader = await api.rpc.chain.getHeader();
// Log the information
console.log(`${chain}: last block #${lastHeader.number} has hash ${lastHeader.hash}`);
// Subscribe to the new headers
// await api.rpc.chain.subscribeNewHeads((lastHeader) => {
// console.log(`${chain}: last block #${lastHeader.number} has hash ${lastHeader.hash}`);
// });
}
async function transfer(privateKey, to, amount) {
const keyring = new Keyring({ type: 'ethereum' });
// Construct API provider
const wsProvider = new WsProvider(rpcUrl);
const api = await ApiPromise.create({ provider: wsProvider });
// Initialize wallet key pairs
const alice = keyring.addFromUri(privateKey);
// Form the transaction
const tx = await api.tx.balances
.transfer(to, amount)
// Retrieve the encoded calldata of the transaction
const encodedCalldata = tx.method.toHex()
console.log(encodedCalldata)
// Sign and send the transaction
const txHash = await tx
.signAndSend(alice);
// Show the transaction hash
console.log(`Submitted with hash ${txHash}`);
return
}
async function joinCandidates(privateKey, bound, candidateCount) {
const keyring = new Keyring({ type: 'ethereum' });
// Construct API provider
const wsProvider = new WsProvider(rpcUrl);
const api = await ApiPromise.create({ provider: wsProvider });
// Initialize wallet key pairs
const alice = keyring.addFromUri(privateKey);
// Form the transaction
const tx = await api.tx.parachainStaking
.joinCandidates(bound, candidateCount)
// Retrieve the encoded calldata of the transaction
const encodedCalldata = tx.method.toHex()
console.log(encodedCalldata)
// Sign and send the transaction
const txHash = await tx
.signAndSend(alice);
// Show the transaction hash
console.log(`Submitted with hash ${txHash}`);
return
}
async function setKeys(privateKey, sessionKey) {
const keyring = new Keyring({ type: 'ethereum' });
// Construct API provider
const wsProvider = new WsProvider(rpcUrl);
const api = await ApiPromise.create({ provider: wsProvider });
// Initialize wallet key pairs
const alice = keyring.addFromUri(privateKey);
// Form the transaction
const tx = await api.tx.authorMapping
.setKeys(sessionKey)
// Retrieve the encoded calldata of the transaction
const encodedCalldata = tx.method.toHex()
console.log(encodedCalldata)
// Sign and send the transaction
const txHash = await tx
.signAndSend(alice);
// Show the transaction hash
console.log(`Submitted with hash ${txHash}`);
return
}
async function main() {
let args = process.argv.splice(2);
const functionName = args[0];
args.forEach(function(arg) {
let r = arg.match(/--rpcUrl=(.+)/);
if (r && r[1]) {
rpcUrl = r[1];
}
})
if (functionName == 'generateAccount') {
const walletName = readlineSync.question('Wallet Name: ');
const password = readlineSync.question('Password: ', { hideEchoBack: true });
const mnem = readlineSync.question('Mnemonic(option): ', { hideEchoBack: true });
generateAccount(walletName, password, mnem);
} else if (functionName == 'decryptMem') {
const path = readlineSync.question('Wallet path: ');
const password = readlineSync.question('Password: ', { hideEchoBack: true });
console.log(decryptMemByFile(path, password));
} else if (functionName == 'joinCandidates') {
const path = readlineSync.question('Wallet path: ');
const password = readlineSync.question('Password: ', { hideEchoBack: true });
const bound = readlineSync.question('bound amount: ');
const candidateCount = readlineSync.question('candidate count: ');
const sourceMem = decryptMemByFile(path, password);
const privateKey = calPrivateKey(sourceMem)
joinCandidates(privateKey, bound, candidateCount);
} else if (functionName == 'setKeys') {
const path = readlineSync.question('Wallet path: ');
const password = readlineSync.question('Password: ', { hideEchoBack: true });
const sessionKey = readlineSync.question('session key: ');
const sourceMem = decryptMemByFile(path, password);
const privateKey = calPrivateKey(sourceMem)
setKeys(privateKey, sessionKey)
} else if (functionName == 'transfer') {
const to = readlineSync.question('target address: ');
const amount = readlineSync.question('amount: ');
const path = readlineSync.question('Wallet path: ');
const password = readlineSync.question('Password: ', { hideEchoBack: true });
const sourceMem = decryptMemByFile(path, password);
const privateKey = calPrivateKey(sourceMem)
transfer(privateKey, to, amount);
} else if (functionName == 'getChainStatus') {
getChainStatus();
} else if (functionName == 'getBalanceAndNonce') {
const address = readlineSync.question('Wallet address: ');
getBalanceAndNonce(address);
} else {
console.log(`
Moonbeam_Script, Easily complete moonbeam transactions.
Version: v0.2.2
Please input Function Name as first Args:
==========================================================
getChainStatus: getChainStatus
getBalanceAndNonce: getBalanceAndNonce
generateAccount: generate a new account and save to file after encrypto.
decryptMem: decryp mnemonic from encrypt file.
joinCandidates: send a parachainStaking.joinCandidates transaction.
setKeys: send a authorMapping.setKeys transaction.
transfer: transfer token to another address.
==========================================================
--rpcUrl=wss://moonbeam-alpha.api.onfinality.io/public-ws
`)
return;
}
}
main()