3 /*jshint maxcomplexity:25 */
5 require("dotenv").config({ path: ".env" });
6 require("dotenv").config({ path: ".env.secret" });
8 let HOME = process.env.HOME || "";
11 let pkg = require("../package.json");
13 let Fs = require("fs").promises;
14 let Path = require("path");
16 let Cipher = require("./_cipher.js");
17 let CrowdNode = require("../lib/crowdnode.js");
18 let Dash = require("../lib/dash.js");
19 let Insight = require("../lib/insight.js");
20 let Prompt = require("./_prompt.js");
21 let Qr = require("../lib/qr.js");
22 let Ws = require("../lib/ws.js");
24 let Dashcore = require("@dashevo/dashcore-lib");
26 const DUFFS = 100000000;
27 let qrWidth = 2 + 67 + 2;
29 // 0.00236608 // required for signup
30 // 0.00002000 // TX fee estimate
31 // 0.00238608 // minimum recommended amount
34 let signupOnly = CrowdNode.requests.signupForApi + CrowdNode.requests.offset;
35 let acceptOnly = CrowdNode.requests.acceptTerms + CrowdNode.requests.offset;
36 let signupFees = signupOnly + acceptOnly;
37 let feeEstimate = 500;
38 let signupTotal = signupFees + 2 * feeEstimate;
41 let configdir = `.config/crowdnode`;
42 let keysDir = Path.join(HOME, `${configdir}/keys`);
43 let keysDirRel = `~/${configdir}/keys`;
44 let shadowPath = Path.join(HOME, `${configdir}/shadow`);
45 let defaultWifPath = Path.join(HOME, `${configdir}/default`);
47 function showVersion() {
48 console.info(`${pkg.name} v${pkg.version} - ${pkg.description}`);
55 console.info("Usage:");
56 console.info(" crowdnode help");
57 console.info(" crowdnode status [keyfile-or-addr]");
58 console.info(" crowdnode signup [keyfile-or-addr]");
59 console.info(" crowdnode accept [keyfile-or-addr]");
61 " crowdnode deposit [keyfile-or-addr] [dash-amount] [--no-reserve]",
64 " crowdnode withdrawal [keyfile-or-addr] <percent> # 1.0-100.0 (steps by 0.1)",
68 console.info("Helpful Extras:");
69 console.info(" crowdnode balance [keyfile-or-addr]"); // addr
70 console.info(" crowdnode load [keyfile-or-addr] [dash-amount]"); // addr
72 " crowdnode transfer <from-keyfile-or-addr> <to-keyfile-or-addr> [dash-amount]",
76 console.info("Key Management & Encryption:");
77 console.info(" crowdnode generate [--plain-text] [./privkey.wif]");
78 console.info(" crowdnode encrypt"); // TODO allow encrypting one-by-one?
79 console.info(" crowdnode list");
80 console.info(" crowdnode use <addr>");
81 console.info(" crowdnode import <keyfile>");
82 //console.info(" crowdnode import <(dash-cli dumpprivkey <addr>)"); // TODO
83 //console.info(" crowdnode export <addr> <keyfile>"); // TODO
84 console.info(" crowdnode passphrase # set or change passphrase");
85 console.info(" crowdnode decrypt"); // TODO allow decrypting one-by-one?
86 console.info(" crowdnode delete <addr>");
89 console.info("CrowdNode HTTP RPC:");
90 console.info(" crowdnode http FundsOpen <addr>");
91 console.info(" crowdnode http VotingOpen <addr>");
92 console.info(" crowdnode http GetFunds <addr>");
93 console.info(" crowdnode http GetFundsFrom <addr> <seconds-since-epoch>");
94 console.info(" crowdnode http GetBalance <addr>");
95 console.info(" crowdnode http GetMessages <addr>");
96 console.info(" crowdnode http IsAddressInUse <addr>");
97 // TODO create signature rather than requiring it
98 console.info(" crowdnode http SetEmail ./privkey.wif <email> <signature>");
99 console.info(" crowdnode http Vote ./privkey.wif <gobject-hash> ");
100 console.info(" <Yes|No|Abstain|Delegate|DoNothing> <signature>");
102 " crowdnode http SetReferral ./privkey.wif <referral-id> <signature>",
109 async function main() {
110 /*jshint maxcomplexity:40 */
111 /*jshint maxstatements:500 */
114 // crowdnode <subcommand> [flags] <privkey> [options]
116 // crowdnode withdrawal ./Xxxxpubaddr.wif 100.0
118 let args = process.argv.slice(2);
121 let forceConfirm = removeItem(args, "--unconfirmed");
122 let plainText = removeItem(args, "--plain-text");
123 let noReserve = removeItem(args, "--no-reserve");
125 let subcommand = args.shift();
127 if (!subcommand || ["--help", "-h", "help"].includes(subcommand)) {
133 if (["--version", "-V", "version"].includes(subcommand)) {
141 // find addr by name or by file or by string
142 await Fs.mkdir(keysDir, {
146 let defaultAddr = await Fs.readFile(defaultWifPath, "utf8").catch(
147 emptyStringOnErrEnoent,
149 defaultAddr = defaultAddr.trim();
152 process.env.INSIGHT_BASE_URL || "https://insight.dash.org";
153 let insightApi = Insight.create({ baseUrl: insightBaseUrl });
154 let dashApi = Dash.create({ insightApi: insightApi });
156 if ("list" === subcommand) {
157 await listKeys({ dashApi }, args);
161 if ("generate" === subcommand) {
162 await generateKey({ defaultKey: defaultAddr, plainText }, args);
166 if ("passphrase" === subcommand) {
167 await setPassphrase({}, args);
171 if ("import" === subcommand) {
172 importKey(null, args);
176 if ("encrypt" === subcommand) {
177 let addr = args.shift() || "";
183 let keypath = await findWif(addr);
185 console.error(`no managed key matches '${addr}'`);
189 let key = await maybeReadKeyFileRaw(keypath);
191 throw new Error("impossible error");
197 if ("decrypt" === subcommand) {
198 let addr = args.shift() || "";
203 let keypath = await findWif(addr);
205 console.error(`no managed key matches '${addr}'`);
209 let key = await maybeReadKeyFileRaw(keypath);
211 throw new Error("impossible error");
217 // use or select or default... ?
218 if ("use" === subcommand) {
219 await setDefault(null, args);
223 // helper for debugging
224 if ("transfer" === subcommand) {
225 await transferBalance(
226 { dashApi, defaultAddr, forceConfirm, insightBaseUrl, insightApi },
233 if ("http" === subcommand) {
234 rpc = args.shift() || "";
241 let [addr] = await mustGetAddr({ defaultAddr }, args);
243 await initCrowdNode(insightBaseUrl);
244 // ex: http <rpc>(<pub>, ...)
246 let hasRpc = rpc in CrowdNode.http;
248 console.error(`Unrecognized rpc command ${rpc}`);
253 //@ts-ignore - TODO use `switch` or make Record Type
254 let result = await CrowdNode.http[rpc].apply(null, args);
256 console.info(`${rpc} ${addr}:`);
257 if ("string" === typeof result) {
258 console.info(result);
260 console.info(JSON.stringify(result, null, 2));
265 if ("load" === subcommand) {
266 await loadAddr({ defaultAddr, insightBaseUrl }, args);
270 // keeping rm for backwards compat
271 if ("rm" === subcommand || "delete" === subcommand) {
272 await initCrowdNode(insightBaseUrl);
273 await removeKey({ defaultAddr, dashApi, insightBaseUrl }, args);
277 if ("balance" === subcommand) {
278 await getBalance({ dashApi, defaultAddr }, args);
283 if ("status" === subcommand) {
284 await getStatus({ dashApi, defaultAddr, insightBaseUrl }, args);
288 if ("signup" === subcommand) {
289 await sendSignup({ dashApi, defaultAddr, insightBaseUrl }, args);
293 if ("accept" === subcommand) {
294 await acceptTerms({ dashApi, defaultAddr, insightBaseUrl }, args);
298 if ("deposit" === subcommand) {
300 { dashApi, defaultAddr, insightBaseUrl, noReserve },
306 if ("withdrawal" === subcommand) {
307 await withdrawalDash({ dashApi, defaultAddr, insightBaseUrl }, args);
311 console.error(`Unrecognized subcommand ${subcommand}`);
318 * @param {String} insightBaseUrl
320 async function initCrowdNode(insightBaseUrl) {
321 process.stdout.write("Checking CrowdNode API... ");
322 await CrowdNode.init({
323 baseUrl: "https://app.crowdnode.io",
326 console.info(`(hotwallet ${CrowdNode.main.hotwallet})`);
330 * @param {String} addr - Base58Check pubKeyHash address
331 * @param {Number} duffs - 1/100000000 of a DASH
333 function showQr(addr, duffs = 0) {
334 let dashUri = `dash://${addr}`;
336 dashUri += `?amount=${duffs}`;
339 let dashQr = Qr.ascii(dashUri, { indent: 4 });
340 let addrPad = Math.ceil((qrWidth - dashUri.length) / 2);
342 console.info(dashQr);
344 console.info(" ".repeat(addrPad) + dashUri);
348 * @param {Array<any>} arr
351 function removeItem(arr, item) {
352 let index = arr.indexOf(item);
354 return arr.splice(index, 1)[0];
360 * @param {Object} opts
361 * @param {String} opts.addr
362 * @param {String} opts.hotwallet
364 async function getCrowdNodeStatus({ addr, hotwallet }) {
376 //@ts-ignore - TODO why warnings?
377 state.status = await CrowdNode.status(addr, hotwallet);
378 if (state.status?.signup) {
381 if (state.status?.accept) {
384 if (state.status?.deposit) {
391 * @param {Object} opts
392 * @param {String} opts.addr
393 * @param {any} opts.dashApi - TODO
395 async function checkBalance({ addr, dashApi }) {
396 // deposit if balance is over 100,000 (0.00100000)
397 process.stdout.write("Checking balance... ");
398 let balanceInfo = await dashApi.getInstantBalance(addr);
399 let balanceDash = toDash(balanceInfo.balanceSat);
400 console.info(`${balanceInfo.balanceSat} (Đ${balanceDash})`);
402 let balanceInfo = await insightApi.getBalance(pub);
403 if (balanceInfo.unconfirmedBalanceSat || balanceInfo.unconfirmedAppearances) {
406 `Error: This address has pending transactions. Please try again in 1-2 minutes or use --unconfirmed.`,
408 console.error(balanceInfo);
409 if ("status" !== subcommand) {
420 * @param {Object} opts
421 * @param {String} opts.defaultAddr
422 * @param {Array<String>} args
423 * @returns {Promise<[String, String]>}
425 async function mustGetAddr({ defaultAddr }, args) {
426 let name = args.shift() ?? "";
427 if (34 === name.length) {
428 // looks like addr already
429 // TODO make function for addr-lookin' check
433 let addr = await maybeReadKeyPaths(name, { wif: false });
435 if (34 === addr.length) {
438 //let pk = new Dashcore.PrivateKey(wif);
439 //let addr = pk.toAddress().toString();
443 let isNum = !isNaN(parseFloat(name));
451 console.error(`could not read '${name}' in ./ or match in ${keysDirRel}/.`);
457 addr = await mustGetDefaultWif(defaultAddr, { wif: false });
459 // TODO we don't need defaultAddr, right? because it could be old?
464 * @param {Object} opts
465 * @param {String} opts.defaultAddr
466 * @param {Array<String>} args
468 async function mustGetWif({ defaultAddr }, args) {
469 let name = args.shift() ?? "";
471 let wif = await maybeReadKeyPaths(name, { wif: true });
476 let isNum = !isNaN(parseFloat(name));
485 `'${name}' does not match a staking key in ./ or ${keysDirRel}/`,
492 wif = await mustGetDefaultWif(defaultAddr);
498 * @param {String} name
499 * @param {Object} opts
500 * @param {Boolean} opts.wif
501 * @returns {Promise<String>} - wif
503 async function maybeReadKeyPaths(name, opts) {
506 // prefix match in .../keys/
507 let wifname = await findWif(name);
512 if (false === opts.wif) {
513 return wifname.slice(0, -".wif".length);
516 let filepath = Path.join(keysDir, wifname);
517 privKey = await maybeReadKeyFile(filepath);
520 privKey = await maybeReadKeyFile(name);
527 * @param {String} defaultAddr
528 * @param {Object} [opts]
529 * @param {Boolean} opts.wif
531 async function mustGetDefaultWif(defaultAddr, opts) {
534 let keyfile = Path.join(keysDir, `${defaultAddr}.wif`);
535 let raw = await maybeReadKeyFileRaw(keyfile, opts);
536 // misnomering wif here a bit
537 defaultWif = raw?.wif || raw?.addr || "";
540 console.info(`selected default staking key ${defaultAddr}`);
545 console.error(`Error: no default staking key selected.`);
547 console.error(`Select a different address:`);
548 console.error(` crowdnode list`);
549 console.error(` crowdnode use <addr>`);
551 console.error(`Or create a new staking key:`);
552 console.error(` crowdnode generate`);
561 * @param {Object} psuedoState
562 * @param {String} psuedoState.defaultKey - addr name of default key
563 * @param {Boolean} psuedoState.plainText - don't encrypt
564 * @param {Array<String>} args
566 async function generateKey({ defaultKey, plainText }, args) {
567 let name = args.shift();
568 //@ts-ignore - TODO submit JSDoc PR for Dashcore
569 let pk = new Dashcore.PrivateKey();
571 let addr = pk.toAddress().toString();
572 let plainWif = pk.toWIF();
576 wif = await maybeEncrypt(plainWif);
579 let filename = `~/${configdir}/keys/${addr}.wif`;
580 let filepath = Path.join(`${keysDir}/${addr}.wif`);
585 note = `\n(for pubkey address ${addr})`;
586 let err = await Fs.access(filepath).catch(Object);
588 console.info(`'${filepath}' already exists (will not overwrite)`);
594 await Fs.writeFile(filepath, wif, "utf8");
595 if (!name && !defaultKey) {
596 await Fs.writeFile(defaultWifPath, addr, "utf8");
600 console.info(`Generated ${filename} ${note}`);
607 * @param {Object} state
608 * @param {Boolean} [state._askPreviousPassphrase] - don't ask for passphrase again
609 * @param {Array<String>} args
611 async function setPassphrase({ _askPreviousPassphrase }, args) {
612 let date = getFsDateString();
614 // get the old passphrase
615 if (false !== _askPreviousPassphrase) {
616 await cmds.getPassphrase(null, []);
619 // get the new passphrase
622 newPassphrase = await Prompt.prompt("Enter (new) passphrase: ", {
625 newPassphrase = newPassphrase.trim();
627 let _newPassphrase = await Prompt.prompt("Enter passphrase again: ", {
630 _newPassphrase = _newPassphrase.trim();
632 let match = Cipher.secureCompare(newPassphrase, _newPassphrase);
637 console.error("passphrases do not match");
639 let curShadow = await Fs.readFile(shadowPath, "utf8").catch(
640 emptyStringOnErrEnoent,
643 let newShadow = await Cipher.shadowPassphrase(newPassphrase);
644 await Fs.writeFile(shadowPath, newShadow, "utf8");
646 let rawKeys = await readAllKeys();
647 let encAddrs = rawKeys
648 .map(function (raw) {
655 // backup all currently encrypted files
657 if (encAddrs.length) {
658 let filepath = Path.join(HOME, `${configdir}/keys.${date}.bak`);
660 console.info(`Backing up previous (encrypted) keys:`);
661 encAddrs.unshift(curShadow);
662 await Fs.writeFile(filepath, encAddrs.join("\n") + "\n", "utf8");
663 console.info(` ~/${configdir}/keys.${date}.bak`);
666 cmds._setPassphrase(newPassphrase);
668 await encryptAll(rawKeys, { rotateKey: true });
670 return newPassphrase;
676 * @param {Array<String>} args
678 async function importKey(_, args) {
679 let keypath = args.shift() || "";
680 let key = await maybeReadKeyFileRaw(keypath);
682 console.error(`no key found for '${keypath}'`);
687 let encWif = await maybeEncrypt(key.wif);
689 if (encWif.includes(":")) {
692 let date = getFsDateString();
695 Path.join(keysDir, `${key.addr}.wif`),
697 Path.join(keysDir, `${key.addr}.${date}.bak`),
700 console.info(`${icon} Imported ${keysDirRel}/${key.addr}.wif`);
705 * Encrypt ALL-the-things!
706 * @param {Object} [opts]
707 * @param {Boolean} opts.rotateKey
708 * @param {Array<RawKey>?} rawKeys
710 async function encryptAll(rawKeys, opts) {
712 rawKeys = await readAllKeys();
714 let date = getFsDateString();
716 console.info(`Encrypting...`);
718 await rawKeys.reduce(async function (promise, key) {
721 if (key.encrypted && !opts?.rotateKey) {
722 console.info(`🙈 ${key.addr} [already encrypted]`);
725 let encWif = await maybeEncrypt(key.wif);
727 Path.join(keysDir, `${key.addr}.wif`),
729 Path.join(keysDir, `${key.addr}.${date}.bak`),
731 console.info(`🔑 ${key.addr}`);
732 }, Promise.resolve());
734 console.info(`Done 🔐`);
739 * Decrypt ALL-the-things!
740 * @param {Array<RawKey>?} rawKeys
742 async function decryptAll(rawKeys) {
744 rawKeys = await readAllKeys();
746 let date = getFsDateString();
749 console.info(`Decrypting...`);
751 await rawKeys.reduce(async function (promise, key) {
754 if (!key.encrypted) {
755 console.info(`📖 ${key.addr} [already decrypted]`);
759 Path.join(keysDir, `${key.addr}.wif`),
761 Path.join(keysDir, `${key.addr}.${date}.bak`),
763 console.info(`🔓 ${key.addr}`);
764 }, Promise.resolve());
766 console.info(`Done ✅`);
770 function getFsDateString() {
771 // YYYY-MM-DD_hh-mm_ss
772 let date = new Date()
776 .replace(/\.\d{3}.*/, "");
781 * @param {String} filepath
782 * @param {String} wif
783 * @param {String} bakpath
785 async function safeSave(filepath, wif, bakpath) {
786 let tmpPath = `${bakpath}.tmp`;
787 await Fs.writeFile(tmpPath, wif, "utf8");
788 let err = await Fs.access(filepath).catch(Object);
790 await Fs.rename(filepath, bakpath);
792 await Fs.rename(tmpPath, filepath);
794 await Fs.unlink(bakpath);
799 * @param {Null} psuedoState
800 * @param {Array<String>} args
802 cmds.getPassphrase = async function (psuedoState, args) {
803 // Three possible states:
804 // 1. no shadow file yet (ask to set one)
805 // 2. empty shadow file (initialized, but not set - don't ask to set one)
806 // 3. encrypted shadow file (initialized, requires passphrase)
807 let needsInit = false;
808 let shadow = await Fs.readFile(shadowPath, "utf8").catch(function (err) {
809 if ("ENOENT" === err.code) {
816 // State 1: not initialized, what does the user want?
819 let no = await Prompt.prompt(
820 "Would you like to set an encryption passphrase? [Y/n]: ",
823 // Set a passphrase and create shadow file
824 if (!no || ["yes", "y"].includes(no.toLowerCase())) {
825 let passphrase = await setPassphrase(
826 { _askPreviousPassphrase: false },
829 cmds._setPassphrase(passphrase);
834 if (!["no", "n"].includes(no.toLowerCase())) {
838 // No passphrase, create empty shadow file
839 await Fs.writeFile(shadowPath, "", "utf8");
844 // State 2: shadow already initialized to empty
845 // (user doesn't want a passphrase)
847 cmds._setPassphrase("");
851 // State 3: passphrase & shadow already in use
853 let passphrase = await Prompt.prompt("Enter (current) passphrase: ", {
856 passphrase = passphrase.trim();
857 if (!passphrase || "q" === passphrase) {
858 console.error("cancel: no passphrase");
863 let match = await Cipher.checkPassphrase(passphrase, shadow);
865 cmds._setPassphrase(passphrase);
870 console.error("incorrect passphrase");
873 throw new Error("SANITY FAIL: unreachable return");
876 cmds._getPassphrase = function () {
881 * @param {String} passphrase
883 cmds._setPassphrase = function (passphrase) {
884 // Look Ma! A private variable!
885 cmds._getPassphrase = function () {
891 * @typedef {Object} RawKey
892 * @property {String} addr
893 * @property {Boolean} encrypted
894 * @property {String} wif
900 async function readAllKeys() {
901 let wifnames = await listManagedKeynames();
903 /** @type Array<RawKey> */
905 await wifnames.reduce(async function (promise, wifname) {
908 let keypath = Path.join(keysDir, wifname);
909 let key = await maybeReadKeyFileRaw(keypath);
914 if (`${key.addr}.wif` !== wifname) {
916 `computed pubkey '${key.addr}' of WIF does not match filename '${keypath}'`,
921 }, Promise.resolve());
927 * @param {String} filepath
928 * @param {Object} [opts]
929 * @param {Boolean} opts.wif
930 * @returns {Promise<String>}
932 async function maybeReadKeyFile(filepath, opts) {
933 let key = await maybeReadKeyFileRaw(filepath, opts);
934 if (false === opts?.wif) {
935 return key?.addr || "";
937 return key?.wif || "";
941 * @param {String} filepath
942 * @param {Object} [opts]
943 * @param {Boolean} opts.wif
944 * @returns {Promise<RawKey?>}
946 async function maybeReadKeyFileRaw(filepath, opts) {
947 let privKey = await Fs.readFile(filepath, "utf8").catch(
948 emptyStringOnErrEnoent,
950 privKey = privKey.trim();
955 let encrypted = false;
956 if (privKey.includes(":")) {
959 if (false !== opts?.wif) {
960 privKey = await decrypt(privKey);
964 console.error(err.message);
965 console.error(`passphrase does not match for key ${filepath}`);
969 if (false === opts?.wif) {
971 addr: Path.basename(filepath, ".wif"),
972 encrypted: encrypted,
977 let pk = new Dashcore.PrivateKey(privKey);
978 let pub = pk.toAddress().toString();
982 encrypted: encrypted,
988 * @param {String} encWif
990 async function decrypt(encWif) {
991 let passphrase = cmds._getPassphrase();
993 passphrase = await cmds.getPassphrase(null, []);
995 let key128 = await Cipher.deriveKey(passphrase);
996 let cipher = Cipher.create(key128);
998 return cipher.decrypt(encWif);
1002 * @param {String} plainWif
1004 async function maybeEncrypt(plainWif) {
1005 let passphrase = cmds._getPassphrase();
1007 passphrase = await cmds.getPassphrase(null, []);
1013 let key128 = await Cipher.deriveKey(passphrase);
1014 let cipher = Cipher.create(key128);
1015 return cipher.encrypt(plainWif);
1020 * @param {Array<String>} args
1022 async function setDefault(_, args) {
1023 let addr = args.shift() || "";
1025 let keyname = await findWif(addr);
1027 console.error(`no key matches '${addr}'`);
1032 let filepath = Path.join(keysDir, keyname);
1033 let wif = await maybeReadKeyFile(filepath);
1034 let pk = new Dashcore.PrivateKey(wif);
1035 let pub = pk.toAddress().toString();
1037 console.info("set", defaultWifPath, pub);
1038 await Fs.writeFile(defaultWifPath, pub, "utf8");
1041 // TODO option to specify config dir
1044 * @param {Object} opts
1045 * @param {any} opts.dashApi - TODO
1046 * @param {Array<String>} args
1048 async function listKeys({ dashApi }, args) {
1049 let wifnames = await listManagedKeynames();
1052 * @type Array<{ node: String, error: Error }>
1056 console.info(`Staking keys: (in ${keysDirRel}/)`);
1058 if (!wifnames.length) {
1059 console.info(` (none)`);
1061 await wifnames.reduce(async function (promise, wifname) {
1064 let wifpath = Path.join(keysDir, wifname);
1065 let addr = await maybeReadKeyFile(wifpath, { wif: false }).catch(function (
1068 warns.push({ node: wifname, error: err });
1076 let pk = new Dashcore.PrivateKey(wif);
1077 let pub = pk.toAddress().toString();
1078 if (`${pub}.wif` !== wifname) {
1083 `computed pubkey '${pub}' of WIF does not match filename '${wifname}'`,
1090 process.stdout.write(` 🪙 ${addr}: `);
1091 let balanceInfo = await dashApi.getInstantBalance(addr);
1092 let balanceDash = toDash(balanceInfo.balanceSat);
1093 console.info(`${balanceInfo.balanceSat} (Đ${balanceDash})`);
1094 }, Promise.resolve());
1098 console.warn(`Warnings:`);
1099 warns.forEach(function (warn) {
1100 console.warn(`${warn.node}: ${warn.error.message}`);
1107 * @param {String} name - ex: Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.wif.enc
1109 function isNamedLikeKey(name) {
1110 // TODO distinguish with .enc extension?
1111 let hasGoodLength = 34 + 4 === name.length || 34 + 4 + 4 === name.length;
1112 let knownExt = name.endsWith(".wif") || name.endsWith(".wif.enc");
1113 let isTmp = name.startsWith(".") || name.startsWith("_");
1114 return hasGoodLength && knownExt && !isTmp;
1118 * @param {Object} opts
1119 * @param {any} opts.dashApi - TODO
1120 * @param {String} opts.defaultAddr
1121 * @param {String} opts.insightBaseUrl
1122 * @param {Array<String>} args
1124 async function removeKey({ dashApi, defaultAddr, insightBaseUrl }, args) {
1125 let [addr, name] = await mustGetAddr({ defaultAddr }, args);
1126 let balanceInfo = await dashApi.getInstantBalance(addr);
1128 let balanceDash = toDash(balanceInfo.balanceSat);
1129 if (balanceInfo.balanceSat) {
1131 console.error(`Error: ${addr}`);
1133 ` still has a balance of ${balanceInfo.balanceSat} (Đ${balanceDash})`,
1135 console.error(` (transfer to another address before deleting)`);
1141 await initCrowdNode(insightBaseUrl);
1142 let crowdNodeBalance = await CrowdNode.http.GetBalance(addr);
1143 if (!crowdNodeBalance) {
1144 // may be janky if not registered
1145 crowdNodeBalance = {};
1147 if (!crowdNodeBalance.TotalBalance) {
1148 //console.log('DEBUG', crowdNodeBalance);
1149 crowdNodeBalance.TotalBalance = 0;
1151 let crowdNodeDash = toDash(crowdNodeBalance.TotalBalance);
1152 if (crowdNodeBalance.TotalBalance) {
1154 console.error(`Error: ${addr}`);
1156 ` still staking ${crowdNodeBalance.TotalBalance} (Đ${crowdNodeDash}) on CrowdNode`,
1159 ` (withdrawal 100.0 and transfer to another address before deleting)`,
1166 let wifname = await findWif(addr);
1167 let filepath = Path.join(keysDir, wifname);
1168 let wif = await maybeReadKeyPaths(name, { wif: true });
1170 await Fs.unlink(filepath).catch(function (err) {
1171 console.error(`could not remove ${filepath}: ${err.message}`);
1175 let wifnames = await listManagedKeynames();
1177 console.info(`No balances found. Removing ${filepath}.`);
1179 console.info(`Backup (just in case):`);
1180 console.info(` ${wif}`);
1182 if (!wifnames.length) {
1183 console.info(`No keys left.`);
1186 let newAddr = wifnames[0];
1187 console.info(`Selected ${newAddr} as new default staking key.`);
1188 await Fs.writeFile(defaultWifPath, addr.replace(".wif", ""), "utf8");
1194 * @param {String} pre
1196 async function findWif(pre) {
1201 let names = await listManagedKeynames();
1202 names = names.filter(function (name) {
1203 return name.startsWith(pre);
1206 if (!names.length) {
1210 if (names.length > 1) {
1211 console.error(`'${pre}' is ambiguous:`, names.join(", "));
1219 async function listManagedKeynames() {
1220 let nodes = await Fs.readdir(keysDir);
1222 return nodes.filter(isNamedLikeKey);
1226 * @param {Object} opts
1227 * @param {String} opts.defaultAddr
1228 * @param {String} opts.insightBaseUrl
1229 * @param {Array<String>} args
1231 async function loadAddr({ defaultAddr, insightBaseUrl }, args) {
1232 let [addr] = await mustGetAddr({ defaultAddr }, args);
1234 let desiredAmountDash = parseFloat(args.shift() || "0");
1235 let desiredAmountDuff = Math.round(desiredAmountDash * DUFFS);
1236 let effectiveDuff = desiredAmountDuff;
1237 let effectiveDash = "";
1238 if (!effectiveDuff) {
1239 effectiveDuff = CrowdNode.stakeMinimum + signupTotal + feeEstimate;
1240 effectiveDash = toDash(effectiveDuff);
1241 // Round to the nearest mDash
1242 // ex: 0.50238108 => 0.50300000
1243 effectiveDuff = toDuff(
1244 (Math.ceil(parseFloat(effectiveDash) * 1000) / 1000).toString(),
1246 effectiveDash = toDash(effectiveDuff);
1250 showQr(addr, effectiveDuff);
1253 `Use the QR Code above to load ${effectiveDuff} (Đ${effectiveDash}) onto your staking key.`,
1256 console.info(`(waiting...)`);
1258 let payment = await Ws.waitForVout(insightBaseUrl, addr, 0);
1259 console.info(`Received ${payment.satoshis}`);
1264 * @param {Object} opts
1265 * @param {String} opts.defaultAddr
1266 * @param {any} opts.dashApi - TODO
1267 * @param {Array<String>} args
1269 async function getBalance({ dashApi, defaultAddr }, args) {
1270 let [addr] = await mustGetAddr({ defaultAddr }, args);
1271 let balanceInfo = await checkBalance({ addr, dashApi });
1272 console.info(balanceInfo);
1278 * @param {Object} opts
1279 * @param {any} opts.dashApi - TODO
1280 * @param {String} opts.defaultAddr
1281 * @param {Boolean} opts.forceConfirm
1282 * @param {String} opts.insightBaseUrl
1283 * @param {any} opts.insightApi
1284 * @param {Array<String>} args
1286 // ex: node ./bin/crowdnode.js transfer ./priv.wif 'pub' 0.01
1287 async function transferBalance(
1288 { dashApi, defaultAddr, forceConfirm, insightBaseUrl, insightApi },
1291 let wif = await mustGetWif({ defaultAddr }, args);
1293 let keyname = args.shift() || "";
1294 let newAddr = await wifFileToAddr(keyname);
1295 let dashAmount = parseFloat(args.shift() || "0");
1296 let duffAmount = Math.round(dashAmount * DUFFS);
1299 tx = await dashApi.createPayment(wif, newAddr, duffAmount);
1301 tx = await dashApi.createBalanceTransfer(wif, newAddr);
1304 let dashAmountStr = toDash(duffAmount);
1306 `Transferring ${duffAmount} (Đ${dashAmountStr}) to ${newAddr}...`,
1309 console.info(`Transferring balance to ${newAddr}...`);
1311 await insightApi.instantSend(tx);
1312 console.info(`Queued...`);
1313 setTimeout(function () {
1314 // TODO take a cleaner approach
1315 // (waitForVout needs a reasonable timeout)
1316 console.error(`Error: Transfer did not complete.`);
1318 console.error(`(using --unconfirmed may lead to rejected double spends)`);
1322 await Ws.waitForVout(insightBaseUrl, newAddr, 0);
1323 console.info(`Accepted!`);
1329 * @param {Object} opts
1330 * @param {any} opts.dashApi - TODO
1331 * @param {String} opts.defaultAddr
1332 * @param {String} opts.insightBaseUrl
1333 * @param {Array<String>} args
1335 async function getStatus({ dashApi, defaultAddr, insightBaseUrl }, args) {
1336 let [addr] = await mustGetAddr({ defaultAddr }, args);
1337 await initCrowdNode(insightBaseUrl);
1338 let hotwallet = CrowdNode.main.hotwallet;
1339 let state = await getCrowdNodeStatus({ addr, hotwallet });
1342 console.info(`API Actions Complete for ${addr}:`);
1343 console.info(` ${state.signup} SignUpForApi`);
1344 console.info(` ${state.accept} AcceptTerms`);
1345 console.info(` ${state.deposit} DepositReceived`);
1347 let crowdNodeBalance = await CrowdNode.http.GetBalance(addr);
1348 // may be unregistered / undefined
1351 * '@odata.context': 'https://app.crowdnode.io/odata/$metadata#Edm.String',
1352 * value: 'Address not found.'
1355 if (!crowdNodeBalance.TotalBalance) {
1356 crowdNodeBalance.TotalBalance = 0;
1358 let crowdNodeDash = toDash(crowdNodeBalance.TotalBalance);
1360 `CrowdNode Stake: ${crowdNodeBalance.TotalBalance} (Đ${crowdNodeDash})`,
1368 * @param {Object} opts
1369 * @param {any} opts.dashApi - TODO
1370 * @param {String} opts.defaultAddr
1371 * @param {String} opts.insightBaseUrl
1372 * @param {Array<String>} args
1374 async function sendSignup({ dashApi, defaultAddr, insightBaseUrl }, args) {
1375 let [addr, name] = await mustGetAddr({ defaultAddr }, args);
1376 await initCrowdNode(insightBaseUrl);
1377 let hotwallet = CrowdNode.main.hotwallet;
1378 let state = await getCrowdNodeStatus({ addr, hotwallet });
1379 let balanceInfo = await checkBalance({ addr, dashApi });
1381 if (state.status?.signup) {
1382 console.info(`${addr} is already signed up. Here's the account status:`);
1383 console.info(` ${state.signup} SignUpForApi`);
1384 console.info(` ${state.accept} AcceptTerms`);
1385 console.info(` ${state.deposit} DepositReceived`);
1390 let hasEnough = balanceInfo.balanceSat > signupOnly + feeEstimate;
1392 await collectSignupFees(insightBaseUrl, addr);
1395 let wif = await maybeReadKeyPaths(name, { wif: true });
1397 console.info("Requesting account...");
1398 await CrowdNode.signup(wif, hotwallet);
1400 console.info(` ${state.signup} SignUpForApi`);
1401 console.info(` ${state.accept} AcceptTerms`);
1407 * @param {Object} opts
1408 * @param {any} opts.dashApi - TODO
1409 * @param {String} opts.defaultAddr
1410 * @param {String} opts.insightBaseUrl
1411 * @param {Array<String>} args
1413 async function acceptTerms({ dashApi, defaultAddr, insightBaseUrl }, args) {
1414 let [addr, name] = await mustGetAddr({ defaultAddr }, args);
1416 await initCrowdNode(insightBaseUrl);
1417 let hotwallet = CrowdNode.main.hotwallet;
1418 let state = await getCrowdNodeStatus({ addr, hotwallet });
1419 let balanceInfo = await dashApi.getInstantBalance(addr);
1421 if (!state.status?.signup) {
1422 console.info(`${addr} is not signed up yet. Here's the account status:`);
1423 console.info(` ${state.signup} SignUpForApi`);
1424 console.info(` ${state.accept} AcceptTerms`);
1429 if (state.status?.accept) {
1430 console.info(`${addr} is already signed up. Here's the account status:`);
1431 console.info(` ${state.signup} SignUpForApi`);
1432 console.info(` ${state.accept} AcceptTerms`);
1433 console.info(` ${state.deposit} DepositReceived`);
1437 let hasEnough = balanceInfo.balanceSat > acceptOnly + feeEstimate;
1439 await collectSignupFees(insightBaseUrl, addr);
1442 let wif = await maybeReadKeyPaths(name, { wif: true });
1444 console.info("Accepting terms...");
1445 await CrowdNode.accept(wif, hotwallet);
1447 console.info(` ${state.signup} SignUpForApi`);
1448 console.info(` ${state.accept} AcceptTerms`);
1449 console.info(` ${state.deposit} DepositReceived`);
1455 * @param {Object} opts
1456 * @param {any} opts.dashApi - TODO
1457 * @param {String} opts.defaultAddr
1458 * @param {String} opts.insightBaseUrl
1459 * @param {Boolean} opts.noReserve
1460 * @param {Array<String>} args
1462 async function depositDash(
1463 { dashApi, defaultAddr, insightBaseUrl, noReserve },
1466 let [addr, name] = await mustGetAddr({ defaultAddr }, args);
1467 await initCrowdNode(insightBaseUrl);
1468 let hotwallet = CrowdNode.main.hotwallet;
1469 let state = await getCrowdNodeStatus({ addr, hotwallet });
1470 let balanceInfo = await dashApi.getInstantBalance(addr);
1472 if (!state.status?.accept) {
1473 console.error(`no account for address ${addr}`);
1478 // this would allow for at least 2 withdrawals costing (21000 + 1000)
1479 let reserve = 50000;
1480 let reserveDash = toDash(reserve);
1483 `reserving ${reserve} (Đ${reserveDash}) for withdrawals (--no-reserve to disable)`,
1489 // TODO if unconfirmed, check utxos instead
1491 // deposit what the user asks, or all that we have,
1492 // or all that the user deposits - but at least 2x the reserve
1493 let desiredAmountDash = parseFloat(args.shift() || "0");
1494 let desiredAmountDuff = Math.round(desiredAmountDash * DUFFS);
1495 let effectiveAmount = desiredAmountDuff;
1496 if (!effectiveAmount) {
1497 effectiveAmount = balanceInfo.balanceSat - reserve;
1499 let needed = Math.max(reserve * 2, effectiveAmount + reserve);
1501 if (balanceInfo.balanceSat < needed) {
1503 if (desiredAmountDuff) {
1504 ask = desiredAmountDuff + reserve + -balanceInfo.balanceSat;
1506 await collectDeposit(insightBaseUrl, addr, ask);
1507 balanceInfo = await dashApi.getInstantBalance(addr);
1508 if (balanceInfo.balanceSat < needed) {
1509 let balanceDash = toDash(balanceInfo.balanceSat);
1511 `Balance is still too small: ${balanceInfo.balanceSat} (Đ${balanceDash})`,
1517 if (!desiredAmountDuff) {
1518 effectiveAmount = balanceInfo.balanceSat - reserve;
1521 let effectiveDash = toDash(effectiveAmount);
1523 `Initiating deposit of ${effectiveAmount} (Đ${effectiveDash})...`,
1526 let wif = await maybeReadKeyPaths(name, { wif: true });
1528 await CrowdNode.deposit(wif, hotwallet, effectiveAmount);
1529 state.deposit = "✅";
1530 console.info(` ${state.deposit} DepositReceived`);
1536 * @param {Object} opts
1537 * @param {any} opts.dashApi - TODO
1538 * @param {String} opts.defaultAddr
1539 * @param {String} opts.insightBaseUrl
1540 * @param {Array<String>} args
1542 async function withdrawalDash({ dashApi, defaultAddr, insightBaseUrl }, args) {
1543 let [addr] = await mustGetAddr({ defaultAddr }, args);
1544 await initCrowdNode(insightBaseUrl);
1545 let hotwallet = CrowdNode.main.hotwallet;
1546 let state = await getCrowdNodeStatus({ addr, hotwallet });
1548 if (!state.status?.accept) {
1549 console.error(`no account for address ${addr}`);
1554 let percentStr = args.shift() || "100.0";
1555 // pass: .1 0.1, 1, 1.0, 10, 10.0, 100, 100.0
1556 // fail: 1000, 10.00
1557 if (!/^1?\d?\d?(\.\d)?$/.test(percentStr)) {
1558 console.error("Error: withdrawal percent must be between 0.1 and 100.0");
1561 let percent = parseFloat(percentStr);
1563 let permil = Math.round(percent * 10);
1564 if (permil <= 0 || permil > 1000) {
1565 console.error("Error: withdrawal percent must be between 0.1 and 100.0");
1569 let realPercentStr = (permil / 10).toFixed(1);
1570 console.info(`Initiating withdrawal of ${realPercentStr}...`);
1572 let wifname = await findWif(addr);
1573 let filepath = Path.join(keysDir, wifname);
1574 let wif = await maybeReadKeyFile(filepath);
1575 let paid = await CrowdNode.withdrawal(wif, hotwallet, permil);
1576 //let paidFloat = (paid.satoshis / DUFFS).toFixed(8);
1577 //let paidInt = paid.satoshis.toString().padStart(9, "0");
1578 console.info(`API Response: ${paid.api}`);
1586 * Convert prefix, addr, keyname, or filepath to pub addr
1587 * @param {String} name
1590 async function wifFileToAddr(name) {
1591 if (34 === name.length) {
1592 // actually payment addr
1598 let wifname = await findWif(name);
1600 let filepath = Path.join(keysDir, wifname);
1601 privKey = await maybeReadKeyFile(filepath);
1604 privKey = await maybeReadKeyFile(name);
1607 throw new Error("bad file path or address");
1610 let pk = new Dashcore.PrivateKey(privKey);
1611 let pub = pk.toPublicKey().toAddress().toString();
1616 * @param {String} insightBaseUrl
1617 * @param {String} addr
1619 async function collectSignupFees(insightBaseUrl, addr) {
1623 let signupTotalDash = toDash(signupTotal);
1624 let signupMsg = `Please send >= ${signupTotal} (Đ${signupTotalDash}) to Sign Up to CrowdNode`;
1625 let msgPad = Math.ceil((qrWidth - signupMsg.length) / 2);
1626 let subMsg = "(plus whatever you'd like to deposit)";
1627 let subMsgPad = Math.ceil((qrWidth - subMsg.length) / 2);
1630 console.info(" ".repeat(msgPad) + signupMsg);
1631 console.info(" ".repeat(subMsgPad) + subMsg);
1635 console.info("(waiting...)");
1637 let payment = await Ws.waitForVout(insightBaseUrl, addr, 0);
1638 console.info(`Received ${payment.satoshis}`);
1642 * @param {String} insightBaseUrl
1643 * @param {String} addr
1644 * @param {Number} duffAmount
1646 async function collectDeposit(insightBaseUrl, addr, duffAmount) {
1648 showQr(addr, duffAmount);
1650 let depositMsg = `Please send what you wish to deposit to ${addr}`;
1652 let dashAmount = toDash(duffAmount);
1653 depositMsg = `Please deposit ${duffAmount} (Đ${dashAmount}) to ${addr}`;
1656 let msgPad = Math.ceil((qrWidth - depositMsg.length) / 2);
1657 msgPad = Math.max(0, msgPad);
1660 console.info(" ".repeat(msgPad) + depositMsg);
1664 console.info("(waiting...)");
1666 let payment = await Ws.waitForVout(insightBaseUrl, addr, 0);
1667 console.info(`Received ${payment.satoshis}`);
1671 * @param {Error & { code: String }} err
1674 function emptyStringOnErrEnoent(err) {
1675 if ("ENOENT" !== err.code) {
1682 * @param {Number} duffs - ex: 00000000
1684 function toDash(duffs) {
1685 return (duffs / DUFFS).toFixed(8);
1689 * @param {String} dash - ex: 0.00000000
1691 function toDuff(dash) {
1692 return Math.round(parseFloat(dash) * DUFFS);
1697 main().catch(function (err) {
1698 console.error("Fail:");
1699 console.error(err.stack || err);