-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
282 lines (248 loc) · 7.49 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
275
276
277
278
279
280
281
282
require("dotenv").config();
const fs = require("fs");
const { program } = require("commander");
const { BIP32Factory } = require("bip32");
const ecc = require("tiny-secp256k1");
const bip32 = BIP32Factory(ecc);
const bitcoin = require("bitcoinjs-lib");
const bip39 = require("bip39");
const axios = require("axios");
const path = `m/44'/1'/0'/0`;
// File path to store wallets
const WALLET_FILE_PATH = "./wallets.json";
// Load existing wallets from file or initialize an empty array
let wallets = [];
if (fs.existsSync(WALLET_FILE_PATH)) {
const data = fs.readFileSync(WALLET_FILE_PATH, "utf8");
wallets = JSON.parse(data);
}
// Create a new wallet (BIP39 Wallet)
function createWallet(name) {
try {
const mnemonic = bip39.generateMnemonic();
const seed = bip39.mnemonicToSeedSync(mnemonic);
const network = bitcoin.networks.testnet;
const root = bip32.fromSeed(seed, network);
const account = root.derivePath(path);
const node = account.derive(0);
const { address } = bitcoin.payments.p2pkh({
pubkey: node.publicKey,
network,
});
const wallet = {
name: name,
mnemonic: mnemonic,
address: address,
};
wallets.push(wallet);
saveWalletsToFile();
console.log("Wallet created successfully.");
console.log("Name:", name);
console.log("Mnemonic:", mnemonic);
console.log("Address:", address);
} catch (error) {
console.log("Error creating wallet:", error.message);
}
}
// Import a wallet (from BIP39 Mnemonic)
function importWallet(name, mnemonic) {
const wallet = findWalletByName(name);
if (!wallet) {
console.log("Wallet not found.");
return;
}
try {
if (!bip39.validateMnemonic(mnemonic)) {
console.log("Invalid mnemonic.");
return;
}
const seed = bip39.mnemonicToSeedSync(mnemonic);
const network = bitcoin.networks.testnet;
const root = bip32.fromSeed(seed, network);
const account = root.derivePath(path);
const node = account.derive(0);
const { address } = bitcoin.payments.p2pkh({
pubkey: node.publicKey,
network,
});
const wallet = {
name: name,
mnemonic: mnemonic,
address: address,
};
// wallets.push(wallet);
// saveWalletsToFile();
console.log("Wallet imported successfully.");
console.log("Name:", name);
console.log("Mnemonic:", mnemonic);
console.log("Address:", address);
} catch (error) {
console.log("Error importing wallet:", error.message);
}
}
// List all wallets
function listWallets() {
if (wallets.length === 0) {
console.log("No wallets found.");
return;
}
console.log("Wallets:");
wallets.forEach((wallet) => {
console.log("Name:", wallet.name);
console.log("Mnemonic:", wallet.mnemonic);
console.log("Address:", wallet.address);
console.log("------------------------------");
});
}
// Get bitcoin balance of a wallet
async function getBalance(name) {
const wallet = findWalletByName(name);
if (!wallet) {
console.log("Wallet not found.");
return;
}
try {
const response = await axios.get(
`https://api.blockcypher.com/v1/btc/test3/addrs/${wallet.address}/balance?token=${process.env.API_KEY}`
);
const data = response.data;
console.log("Address:", wallet.address);
console.log("Balance:", data.balance / 100000000, "BTC");
console.log("------------------------------");
} catch (error) {
console.log("Error:", error.response?.data?.error || error.message);
}
}
// Get list of bitcoin transactions of a wallet
async function getTransactions(name) {
const wallet = findWalletByName(name);
if (!wallet) {
console.log("Wallet not found.");
return;
}
try {
const response = await axios.get(
`https://api.blockcypher.com/v1/btc/test3/addrs/${wallet.address}/full?token=${process.env.API_KEY}`
);
const data = response.data;
console.log("Address:", wallet.address);
if (data.txs.length === 0) {
console.log("No transactions.");
return;
}
console.log("Transactions:");
data.txs.forEach((transaction) => {
console.log("Transaction ID:", transaction.hash);
console.log("Amount:", transaction.total / 100000000, "BTC");
console.log("------------------------------");
});
} catch (error) {
console.log("Error:", error.response?.data?.error || error.message);
}
}
// Generate an unused bitcoin address for a wallet
async function generateAddress(name) {
const wallet = findWalletByName(name);
if (!wallet) {
console.log("Wallet not found.");
return;
}
try {
const node = await getNextUnusedAddress(wallet);
if (!node || !node.publicKey) {
console.log("Invalid node or public key.");
return;
}
const network = bitcoin.networks.testnet;
const { address } = bitcoin.payments.p2pkh({
pubkey: node.publicKey,
network,
});
wallet.address = address;
saveWalletsToFile();
console.log("New address generated successfully.");
console.log("Address:", address);
} catch (error) {
console.log("Error generating address:", error.message);
}
}
// Find a wallet by name
function findWalletByName(name) {
return wallets.find((wallet) => wallet.name === name);
}
// Save wallets to file
function saveWalletsToFile() {
fs.writeFileSync(WALLET_FILE_PATH, JSON.stringify(wallets, null, 2));
}
// Get next unused bitcoin address for a wallet
async function getNextUnusedAddress(wallet) {
const mnemonic = wallet.mnemonic;
const seed = bip39.mnemonicToSeedSync(mnemonic);
const network = bitcoin.networks.testnet;
const root = bip32.fromSeed(seed, network);
const account = root.derivePath("m/44'/1'/0'");
let index = 0;
let unusedAddress = null;
try {
while (!unusedAddress) {
const node = account.derive(index);
try {
const { address } = bitcoin.payments.p2pkh({
pubkey: node.publicKey,
network,
});
if (!(await hasTransactions(address))) {
unusedAddress = address;
}
} catch (error) {
console.log("Error generating P2PKH address:", error);
throw error;
}
index++;
}
} catch (error) {
console.log("Error finding next unused address:", error);
throw error;
}
if (!unusedAddress) {
throw new Error("No unused address found.");
}
return account.derive(index - 1);
}
// Check if an address has any transactions
async function hasTransactions(address) {
try {
const response = await axios.get(
`https://api.blockcypher.com/v1/btc/test3/addrs/${address}/full?token=${process.env.API_KEY}`
);
const data = response.data;
return data.n_tx > 0;
} catch (error) {
console.log("Error:", error.response?.data?.error || error.message);
return false;
}
}
// Define command-line options
program.version("1.0.0").description("Bitcoin Wallet Manager");
program
.command("create <name>")
.description("Create a new wallet")
.action(createWallet);
program
.command("import <name> <mnemonic>")
.description("Import a wallet from BIP39 mnemonic")
.action(importWallet);
program.command("list").description("List all wallets").action(listWallets);
program
.command("balance <name>")
.description("Get bitcoin balance of a wallet")
.action(getBalance);
program
.command("transactions <name>")
.description("Get bitcoin transactions of a wallet")
.action(getTransactions);
program
.command("address <name>")
.description("Generate an unused bitcoin address for a wallet")
.action(generateAddress);
program.parse(process.argv);