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");
28 const NO_SHADOW = "NONE";
29 const DUFFS = 100000000;
31 let shownDefault = false;
32 let qrWidth = 2 + 33 + 2;
34 // 0.00236608 // required for signup
35 // 0.00002000 // TX fee estimate
36 // 0.00238608 // minimum recommended amount
39 let signupOnly = CrowdNode.requests.signupForApi + CrowdNode.requests.offset;
40 let acceptOnly = CrowdNode.requests.acceptTerms + CrowdNode.requests.offset;
41 let signupFees = signupOnly + acceptOnly;
42 let feeEstimate = 500;
43 let signupTotal = signupFees + 2 * feeEstimate;
46 let configdir = `.config/crowdnode`;
47 let keysDir = Path.join(HOME, `${configdir}/keys`);
48 let keysDirRel = `~/${configdir}/keys`;
49 let shadowPath = Path.join(HOME, `${configdir}/shadow`);
50 let defaultWifPath = Path.join(HOME, `${configdir}/default`);
52 function showVersion() {
53 console.info(`${pkg.name} v${pkg.version} - ${pkg.description}`);
60 console.info("Quick Start:");
61 // technically this also has [--no-reserve]
62 console.info(" crowdnode stake [addr-or-import-key | --create-new]");
65 console.info("Usage:");
66 console.info(" crowdnode help");
67 console.info(" crowdnode status [keyfile-or-addr]");
68 console.info(" crowdnode signup [keyfile-or-addr]");
69 console.info(" crowdnode accept [keyfile-or-addr]");
71 " crowdnode deposit [keyfile-or-addr] [dash-amount] [--no-reserve]",
74 " crowdnode withdrawal [keyfile-or-addr] <percent> # 1.0-100.0 (steps by 0.1)",
78 console.info("Helpful Extras:");
79 console.info(" crowdnode balance [keyfile-or-addr]"); // addr
80 console.info(" crowdnode load [keyfile-or-addr] [dash-amount]"); // addr
82 " crowdnode transfer <from-keyfile-or-addr> <to-keyfile-or-addr> [dash-amount]",
86 console.info("Key Management & Encryption:");
87 console.info(" crowdnode init");
88 console.info(" crowdnode generate [--plain-text] [./privkey.wif]");
89 console.info(" crowdnode encrypt"); // TODO allow encrypting one-by-one?
90 console.info(" crowdnode list");
91 console.info(" crowdnode use <addr>");
92 console.info(" crowdnode import <keyfile>");
93 //console.info(" crowdnode import <(dash-cli dumpprivkey <addr>)"); // TODO
94 //console.info(" crowdnode export <addr> <keyfile>"); // TODO
95 console.info(" crowdnode passphrase # set or change passphrase");
96 console.info(" crowdnode decrypt"); // TODO allow decrypting one-by-one?
97 console.info(" crowdnode delete <addr>");
100 console.info("CrowdNode HTTP RPC:");
101 console.info(" crowdnode http FundsOpen <addr>");
102 console.info(" crowdnode http VotingOpen <addr>");
103 console.info(" crowdnode http GetFunds <addr>");
104 console.info(" crowdnode http GetFundsFrom <addr> <seconds-since-epoch>");
105 console.info(" crowdnode http GetBalance <addr>");
106 console.info(" crowdnode http GetMessages <addr>");
107 console.info(" crowdnode http IsAddressInUse <addr>");
108 // TODO create signature rather than requiring it
109 console.info(" crowdnode http SetEmail ./privkey.wif <email> <signature>");
110 console.info(" crowdnode http Vote ./privkey.wif <gobject-hash> ");
111 console.info(" <Yes|No|Abstain|Delegate|DoNothing> <signature>");
113 " crowdnode http SetReferral ./privkey.wif <referral-id> <signature>",
120 async function main() {
121 /*jshint maxcomplexity:40 */
122 /*jshint maxstatements:500 */
125 // crowdnode <subcommand> [flags] <privkey> [options]
127 // crowdnode withdrawal ./Xxxxpubaddr.wif 100.0
129 let args = process.argv.slice(2);
132 let forceGenerate = removeItem(args, "--create-new");
133 let forceConfirm = removeItem(args, "--unconfirmed");
134 let plainText = removeItem(args, "--plain-text");
135 let noReserve = removeItem(args, "--no-reserve");
137 let subcommand = args.shift();
139 if (!subcommand || ["--help", "-h", "help"].includes(subcommand)) {
145 if (["--version", "-V", "version"].includes(subcommand)) {
153 // find addr by name or by file or by string
154 await Fs.mkdir(keysDir, {
158 let defaultAddr = await Fs.readFile(defaultWifPath, "utf8").catch(
159 emptyStringOnErrEnoent,
161 defaultAddr = defaultAddr.trim();
164 process.env.INSIGHT_BASE_URL || "https://insight.dash.org";
165 let insightApi = Insight.create({ baseUrl: insightBaseUrl });
166 let dashApi = Dash.create({ insightApi: insightApi });
168 if ("stake" === subcommand) {
184 if ("list" === subcommand) {
185 await listKeys({ dashApi }, args);
190 if ("init" === subcommand) {
191 await initKeystore({ defaultAddr });
196 if ("generate" === subcommand) {
197 await generateKey({ defaultKey: defaultAddr, plainText }, args);
202 if ("passphrase" === subcommand) {
203 await setPassphrase({}, args);
208 if ("import" === subcommand) {
209 await importKey(null, args);
214 if ("encrypt" === subcommand) {
215 let addr = args.shift() || "";
217 await encryptAll(null);
222 let keypath = await findWif(addr);
224 console.error(`no managed key matches '${addr}'`);
228 let key = await maybeReadKeyFileRaw(keypath);
230 throw new Error("impossible error");
232 await encryptAll([key]);
237 if ("decrypt" === subcommand) {
238 let addr = args.shift() || "";
240 await decryptAll(null);
241 await Fs.writeFile(shadowPath, NO_SHADOW, "utf8").catch(
242 emptyStringOnErrEnoent,
247 let keypath = await findWif(addr);
249 console.error(`no managed key matches '${addr}'`);
253 let key = await maybeReadKeyFileRaw(keypath);
255 throw new Error("impossible error");
257 await decryptAll([key]);
262 // use or select or default... ?
263 if ("use" === subcommand) {
264 await setDefault(null, args);
269 // helper for debugging
270 if ("transfer" === subcommand) {
271 await transferBalance(
272 { dashApi, defaultAddr, forceConfirm, insightBaseUrl, insightApi },
280 if ("http" === subcommand) {
281 rpc = args.shift() || "";
288 let [addr] = await mustGetAddr({ defaultAddr }, args);
290 await initCrowdNode(insightBaseUrl);
291 // ex: http <rpc>(<pub>, ...)
293 let hasRpc = rpc in CrowdNode.http;
295 console.error(`Unrecognized rpc command ${rpc}`);
300 //@ts-ignore - TODO use `switch` or make Record Type
301 let result = await CrowdNode.http[rpc].apply(null, args);
303 console.info(`${rpc} ${addr}:`);
304 if ("string" === typeof result) {
305 console.info(result);
307 console.info(JSON.stringify(result, null, 2));
313 if ("load" === subcommand) {
314 await loadAddr({ defaultAddr, insightBaseUrl }, args);
319 // keeping rm for backwards compat
320 if ("rm" === subcommand || "delete" === subcommand) {
321 await initCrowdNode(insightBaseUrl);
322 await removeKey({ defaultAddr, dashApi, insightBaseUrl }, args);
327 if ("balance" === subcommand) {
328 await getBalance({ dashApi, defaultAddr }, args);
333 if ("status" === subcommand) {
334 await getStatus({ dashApi, defaultAddr, insightBaseUrl }, args);
339 if ("signup" === subcommand) {
340 await sendSignup({ dashApi, defaultAddr, insightBaseUrl }, args);
345 if ("accept" === subcommand) {
346 await acceptTerms({ dashApi, defaultAddr, insightBaseUrl }, args);
351 if ("deposit" === subcommand) {
353 { dashApi, defaultAddr, insightBaseUrl, noReserve },
360 if ("withdrawal" === subcommand) {
361 await withdrawalDash({ dashApi, defaultAddr, insightBaseUrl }, args);
366 console.error(`Unrecognized subcommand ${subcommand}`);
373 * @param {Object} opts
374 * @param {any} opts.dashApi - TODO
375 * @param {String} opts.defaultAddr
376 * @param {Boolean} opts.forceGenerate
377 * @param {String} opts.insightBaseUrl
378 * @param {any} opts.insightApi
379 * @param {Boolean} opts.noReserve
380 * @param {Array<String>} args
382 async function stakeDash(
393 let err = await Fs.access(args[0]).catch(Object);
396 addr = await importKey(null, [args[0]]);
397 } else if (forceGenerate) {
398 addr = await generateKey({ defaultKey: defaultAddr }, []);
400 addr = await initKeystore({ defaultAddr });
404 let [_addr] = await mustGetAddr({ defaultAddr }, args);
408 let extra = feeEstimate;
409 console.info("Checking CrowdNode account... ");
410 await CrowdNode.init({
411 baseUrl: "https://app.crowdnode.io",
414 let hotwallet = CrowdNode.main.hotwallet;
415 let state = await getCrowdNodeStatus({ addr, hotwallet });
417 if (!state.status?.accept) {
418 if (!state.status?.signup) {
419 let signUpDeposit = signupOnly + feeEstimate;
421 ` ${TODO} SignUpForApi deposit is ${signupOnly} (+ tx fee)`,
423 extra += signUpDeposit;
425 console.info(` ${DONE} SignUpForApi complete`);
427 let acceptDeposit = acceptOnly + feeEstimate;
428 console.info(` ${TODO} AcceptTerms deposit is ${acceptOnly} (+ tx fee)`);
429 extra += acceptDeposit;
432 let desiredAmountDash = args.shift() || "0.5";
433 let effectiveDuff = toDuff(desiredAmountDash);
434 effectiveDuff += extra;
436 let balanceInfo = await dashApi.getInstantBalance(addr);
437 effectiveDuff -= balanceInfo.balanceSat;
439 if (effectiveDuff > 0) {
440 effectiveDuff = roundDuff(effectiveDuff, 3);
441 let effectiveDash = toDash(effectiveDuff);
442 await plainLoadAddr({
450 if (!state.status?.accept) {
451 if (!state.status?.signup) {
452 await sendSignup({ dashApi, defaultAddr: addr, insightBaseUrl }, []);
454 await acceptTerms({ dashApi, defaultAddr: addr, insightBaseUrl }, []);
458 { dashApi, defaultAddr: addr, insightBaseUrl, noReserve },
464 * @param {Object} opts
465 * @param {String} opts.defaultAddr
467 async function initKeystore({ defaultAddr }) {
468 // if we have no keys, make one
469 let wifnames = await listManagedKeynames();
470 if (!wifnames.length) {
471 return await generateKey({ defaultKey: defaultAddr }, []);
473 // if we have no passphrase, ask about it
474 await initPassphrase();
475 return defaultAddr || wifnames[0];
479 * @param {String} insightBaseUrl
481 async function initCrowdNode(insightBaseUrl) {
482 if (CrowdNode.main.hotwallet) {
485 process.stdout.write("Checking CrowdNode API... ");
486 await CrowdNode.init({
487 baseUrl: "https://app.crowdnode.io",
490 console.info(`(hotwallet ${CrowdNode.main.hotwallet})`);
494 * @param {String} addr - Base58Check pubKeyHash address
495 * @param {Number} duffs - 1/100000000 of a DASH
497 function showQr(addr, duffs = 0) {
498 let dashAmount = toDash(duffs);
499 let dashUri = `dash://${addr}`;
501 dashUri += `?amount=${dashAmount}`;
504 let dashQr = Qr.ascii(dashUri, { indent: 4, size: "mini" });
505 let addrPad = Math.max(0, Math.ceil((qrWidth - dashUri.length) / 2));
507 console.info(dashQr);
509 console.info(" ".repeat(addrPad) + dashUri);
513 * @param {Array<any>} arr
516 function removeItem(arr, item) {
517 let index = arr.indexOf(item);
519 return arr.splice(index, 1)[0];
525 * @param {Object} opts
526 * @param {String} opts.addr
527 * @param {String} opts.hotwallet
529 async function getCrowdNodeStatus({ addr, hotwallet }) {
541 //@ts-ignore - TODO why warnings?
542 let status = await CrowdNode.status(addr, hotwallet);
544 state.status = status;
546 if (state.status?.signup) {
549 if (state.status?.accept) {
552 if (state.status?.deposit) {
553 state.deposit = DONE;
559 * @param {Object} opts
560 * @param {String} opts.addr
561 * @param {any} opts.dashApi - TODO
563 async function checkBalance({ addr, dashApi }) {
564 // deposit if balance is over 100,000 (0.00100000)
565 console.info("Checking balance... ");
566 let balanceInfo = await dashApi.getInstantBalance(addr);
567 let balanceDASH = toDASH(balanceInfo.balanceSat);
569 let crowdNodeBalance = await CrowdNode.http.GetBalance(addr);
570 if (!crowdNodeBalance.TotalBalance) {
571 crowdNodeBalance.TotalBalance = 0;
572 crowdNodeBalance.TotalDividend = 0;
575 let crowdNodeDuffNum = toDuff(crowdNodeBalance.TotalBalance);
576 let crowdNodeDASH = toDASH(crowdNodeDuffNum);
578 let crowdNodeDivNum = toDuff(crowdNodeBalance.TotalDividend);
579 let crowdNodeDASHDiv = toDASH(crowdNodeDivNum);
581 console.info(`Key: ${balanceDASH}`);
582 console.info(`CrowdNode: ${crowdNodeDASH}`);
583 console.info(`Dividends: ${crowdNodeDASHDiv}`);
586 let balanceInfo = await insightApi.getBalance(pub);
587 if (balanceInfo.unconfirmedBalanceSat || balanceInfo.unconfirmedAppearances) {
590 `Error: This address has pending transactions. Please try again in 1-2 minutes or use --unconfirmed.`,
592 console.error(balanceInfo);
593 if ("status" !== subcommand) {
604 * @param {Object} opts
605 * @param {String} opts.defaultAddr
606 * @param {Array<String>} args
607 * @returns {Promise<[String, String]>}
609 async function mustGetAddr({ defaultAddr }, args) {
610 let name = args.shift() ?? "";
611 if (34 === name.length) {
612 // looks like addr already
613 // TODO make function for addr-lookin' check
617 let addr = await maybeReadKeyPaths(name, { wif: false });
619 if (34 === addr.length) {
622 //let pk = new Dashcore.PrivateKey(wif);
623 //let addr = pk.toAddress().toString();
627 let isNum = !isNaN(parseFloat(name));
635 console.error(`could not read '${name}' in ./ or match in ${keysDirRel}/.`);
641 addr = await mustGetDefaultWif(defaultAddr, { wif: false });
643 // TODO we don't need defaultAddr, right? because it could be old?
648 * @param {Object} opts
649 * @param {String} opts.defaultAddr
650 * @param {Array<String>} args
652 async function mustGetWif({ defaultAddr }, args) {
653 let name = args.shift() ?? "";
655 let wif = await maybeReadKeyPaths(name, { wif: true });
660 let isNum = !isNaN(parseFloat(name));
669 `'${name}' does not match a staking key in ./ or ${keysDirRel}/`,
676 wif = await mustGetDefaultWif(defaultAddr);
682 * @param {String} name
683 * @param {Object} opts
684 * @param {Boolean} opts.wif
685 * @returns {Promise<String>} - wif
687 async function maybeReadKeyPaths(name, opts) {
690 // prefix match in .../keys/
691 let wifname = await findWif(name);
696 if (false === opts.wif) {
697 return wifname.slice(0, -".wif".length);
700 let filepath = Path.join(keysDir, wifname);
701 privKey = await maybeReadKeyFile(filepath);
704 privKey = await maybeReadKeyFile(name);
711 * @param {String} defaultAddr
712 * @param {Object} [opts]
713 * @param {Boolean} opts.wif
715 async function mustGetDefaultWif(defaultAddr, opts) {
718 let keyfile = Path.join(keysDir, `${defaultAddr}.wif`);
719 let raw = await maybeReadKeyFileRaw(keyfile, opts);
720 // misnomering wif here a bit
721 defaultWif = raw?.wif || raw?.addr || "";
723 if (defaultWif && !shownDefault) {
725 console.info(`Selected default staking key ${defaultAddr}`);
730 console.error(`Error: no default staking key selected.`);
732 console.error(`Select a different address:`);
733 console.error(` crowdnode list`);
734 console.error(` crowdnode use <addr>`);
736 console.error(`Or create a new staking key:`);
737 console.error(` crowdnode generate`);
746 * @param {Object} psuedoState
747 * @param {String} psuedoState.defaultKey - addr name of default key
748 * @param {Boolean} [psuedoState.plainText] - don't encrypt
749 * @param {Array<String>} args
751 async function generateKey({ defaultKey, plainText }, args) {
752 let name = args.shift();
753 //@ts-ignore - TODO submit JSDoc PR for Dashcore
754 let pk = new Dashcore.PrivateKey();
756 let addr = pk.toAddress().toString();
757 let plainWif = pk.toWIF();
761 wif = await maybeEncrypt(plainWif);
764 let filename = `~/${configdir}/keys/${addr}.wif`;
765 let filepath = Path.join(`${keysDir}/${addr}.wif`);
770 note = `\n(for pubkey address ${addr})`;
771 let err = await Fs.access(filepath).catch(Object);
774 console.info(`'${filepath}' already exists (will not overwrite)`);
780 await Fs.writeFile(filepath, wif, "utf8");
781 if (!name && !defaultKey) {
782 await Fs.writeFile(defaultWifPath, addr, "utf8");
786 console.info(`Generated ${filename} ${note}`);
791 async function initPassphrase() {
792 let needsInit = false;
793 let shadow = await Fs.readFile(shadowPath, "utf8").catch(
794 emptyStringOnErrEnoent,
800 await cmds.getPassphrase({}, []);
805 * @param {Object} state
806 * @param {Boolean} [state._askPreviousPassphrase] - don't ask for passphrase again
807 * @param {Array<String>} args
809 async function setPassphrase({ _askPreviousPassphrase }, args) {
814 let date = getFsDateString();
816 // get the old passphrase
817 if (false !== _askPreviousPassphrase) {
818 // TODO should contain the shadow?
819 await cmds.getPassphrase({ _rotatePassphrase: true }, []);
822 // get the new passphrase
823 let newPassphrase = await promptPassphrase();
824 let curShadow = await Fs.readFile(shadowPath, "utf8").catch(
825 emptyStringOnErrEnoent,
828 let newShadow = await Cipher.shadowPassphrase(newPassphrase);
829 await Fs.writeFile(shadowPath, newShadow, "utf8");
831 let rawKeys = await readAllKeys();
832 let encAddrs = rawKeys
833 .map(function (raw) {
840 // backup all currently encrypted files
842 if (encAddrs.length) {
843 let filepath = Path.join(HOME, `${configdir}/keys.${date}.bak`);
845 console.info(`Backing up previous (encrypted) keys:`);
846 encAddrs.unshift(`SHADOW:${curShadow}`);
847 await Fs.writeFile(filepath, encAddrs.join("\n") + "\n", "utf8");
848 console.info(` ~/${configdir}/keys.${date}.bak`);
851 cmds._setPassphrase(newPassphrase);
853 await encryptAll(rawKeys, { rotateKey: true });
855 result.passphrase = newPassphrase;
856 result.changed = true;
860 async function promptPassphrase() {
863 newPassphrase = await Prompt.prompt("Enter (new) passphrase: ", {
866 newPassphrase = newPassphrase.trim();
868 let _newPassphrase = await Prompt.prompt("Enter passphrase again: ", {
871 _newPassphrase = _newPassphrase.trim();
873 let match = Cipher.secureCompare(newPassphrase, _newPassphrase);
878 console.error("passphrases do not match");
880 return newPassphrase;
886 * @param {Array<String>} args
888 async function importKey(_, args) {
889 let keypath = args.shift() || "";
890 let key = await maybeReadKeyFileRaw(keypath);
892 console.error(`no key found for '${keypath}'`);
897 let encWif = await maybeEncrypt(key.wif);
899 if (encWif.includes(":")) {
902 let date = getFsDateString();
905 Path.join(keysDir, `${key.addr}.wif`),
907 Path.join(keysDir, `${key.addr}.${date}.bak`),
910 console.info(`${icon} Imported ${keysDirRel}/${key.addr}.wif`);
917 * @param {Object} opts
918 * @param {Boolean} [opts._rotatePassphrase]
919 * @param {Boolean} [opts._force]
920 * @param {Array<String>} args
922 cmds.getPassphrase = async function ({ _rotatePassphrase, _force }, args) {
928 if (!_rotatePassphrase) {
929 let cachedphrase = cmds._getPassphrase();
936 // Three possible states:
937 // 1. no shadow file yet (ask to set one)
938 // 2. empty shadow file (initialized, but not set - don't ask to set one)
939 // 3. encrypted shadow file (initialized, requires passphrase)
940 let needsInit = false;
941 let shadow = await Fs.readFile(shadowPath, "utf8").catch(
942 emptyStringOnErrEnoent,
946 } else if (NO_SHADOW === shadow && _force) {
950 // State 1: not initialized, what does the user want?
955 no = await Prompt.prompt(
956 "Would you like to set an encryption passphrase? [Y/n]: ",
960 // Set a passphrase and create shadow file
961 if (!no || ["yes", "y"].includes(no.toLowerCase())) {
962 result = await setPassphrase({ _askPreviousPassphrase: false }, args);
963 cmds._setPassphrase(result.passphrase);
968 if (!["no", "n"].includes(no.toLowerCase())) {
972 // No passphrase, create a NONE shadow file
973 await Fs.writeFile(shadowPath, NO_SHADOW, "utf8");
978 // State 2: shadow already initialized to empty
979 // (user doesn't want a passphrase)
981 cmds._setPassphrase("");
985 // State 3: passphrase & shadow already in use
987 let prompt = `Enter passphrase: `;
988 if (_rotatePassphrase) {
989 prompt = `Enter (current) passphrase: `;
991 result.passphrase = await Prompt.prompt(prompt, {
994 result.passphrase = result.passphrase.trim();
995 if (!result.passphrase || "q" === result.passphrase) {
996 console.error("cancel: no passphrase");
1001 let match = await Cipher.checkPassphrase(result.passphrase, shadow);
1003 cmds._setPassphrase(result.passphrase);
1008 console.error("incorrect passphrase");
1011 throw new Error("SANITY FAIL: unreachable return");
1014 cmds._getPassphrase = function () {
1019 * @param {String} passphrase
1021 cmds._setPassphrase = function (passphrase) {
1022 // Look Ma! A private variable!
1023 cmds._getPassphrase = function () {
1029 * Encrypt ALL-the-things!
1030 * @param {Object} [opts]
1031 * @param {Boolean} opts.rotateKey
1032 * @param {Array<RawKey>?} rawKeys
1034 async function encryptAll(rawKeys, opts) {
1036 rawKeys = await readAllKeys();
1038 let date = getFsDateString();
1040 let passphrase = cmds._getPassphrase();
1042 let result = await cmds.getPassphrase({ _force: true }, []);
1043 if (result.changed) {
1044 // encryptAll was already called on rotation
1047 passphrase = result.passphrase;
1050 console.info(`Encrypting...`);
1052 await rawKeys.reduce(async function (promise, key) {
1055 if (key.encrypted && !opts?.rotateKey) {
1056 console.info(`🙈 ${key.addr} [already encrypted]`);
1059 let encWif = await maybeEncrypt(key.wif, { force: true });
1061 Path.join(keysDir, `${key.addr}.wif`),
1063 Path.join(keysDir, `${key.addr}.${date}.bak`),
1065 console.info(`🔑 ${key.addr}`);
1066 }, Promise.resolve());
1068 console.info(`Done 🔐`);
1073 * Decrypt ALL-the-things!
1074 * @param {Array<RawKey>?} rawKeys
1076 async function decryptAll(rawKeys) {
1078 rawKeys = await readAllKeys();
1080 let date = getFsDateString();
1083 console.info(`Decrypting...`);
1085 await rawKeys.reduce(async function (promise, key) {
1088 if (!key.encrypted) {
1089 console.info(`📖 ${key.addr} [already decrypted]`);
1093 Path.join(keysDir, `${key.addr}.wif`),
1095 Path.join(keysDir, `${key.addr}.${date}.bak`),
1097 console.info(`🔓 ${key.addr}`);
1098 }, Promise.resolve());
1100 console.info(`Done ${DONE}`);
1104 function getFsDateString() {
1105 // YYYY-MM-DD_hh-mm_ss
1106 let date = new Date()
1110 .replace(/\.\d{3}.*/, "");
1115 * @param {String} filepath
1116 * @param {String} wif
1117 * @param {String} bakpath
1119 async function safeSave(filepath, wif, bakpath) {
1120 let tmpPath = `${bakpath}.tmp`;
1121 await Fs.writeFile(tmpPath, wif, "utf8");
1122 let err = await Fs.access(filepath).catch(Object);
1124 await Fs.rename(filepath, bakpath);
1126 await Fs.rename(tmpPath, filepath);
1128 await Fs.unlink(bakpath);
1133 * @typedef {Object} RawKey
1134 * @property {String} addr
1135 * @property {Boolean} encrypted
1136 * @property {String} wif
1142 async function readAllKeys() {
1143 let wifnames = await listManagedKeynames();
1145 /** @type Array<RawKey> */
1147 await wifnames.reduce(async function (promise, wifname) {
1150 let keypath = Path.join(keysDir, wifname);
1151 let key = await maybeReadKeyFileRaw(keypath);
1156 if (`${key.addr}.wif` !== wifname) {
1158 `computed pubkey '${key.addr}' of WIF does not match filename '${keypath}'`,
1163 }, Promise.resolve());
1169 * @param {String} filepath
1170 * @param {Object} [opts]
1171 * @param {Boolean} opts.wif
1172 * @returns {Promise<String>}
1174 async function maybeReadKeyFile(filepath, opts) {
1175 let key = await maybeReadKeyFileRaw(filepath, opts);
1176 if (false === opts?.wif) {
1177 return key?.addr || "";
1179 return key?.wif || "";
1183 * @param {String} filepath
1184 * @param {Object} [opts]
1185 * @param {Boolean} opts.wif
1186 * @returns {Promise<RawKey?>}
1188 async function maybeReadKeyFileRaw(filepath, opts) {
1189 let privKey = await Fs.readFile(filepath, "utf8").catch(
1190 emptyStringOnErrEnoent,
1192 privKey = privKey.trim();
1197 let encrypted = false;
1198 if (privKey.includes(":")) {
1201 if (false !== opts?.wif) {
1202 privKey = await decrypt(privKey);
1206 console.error(err.message);
1207 console.error(`passphrase does not match for key ${filepath}`);
1211 if (false === opts?.wif) {
1213 addr: Path.basename(filepath, ".wif"),
1214 encrypted: encrypted,
1219 let pk = new Dashcore.PrivateKey(privKey);
1220 let pub = pk.toAddress().toString();
1224 encrypted: encrypted,
1230 * @param {String} encWif
1232 async function decrypt(encWif) {
1233 let passphrase = cmds._getPassphrase();
1235 let result = await cmds.getPassphrase({}, []);
1236 passphrase = result.passphrase;
1237 // we don't return just in case they're setting a passphrase to
1238 // decrypt a previously encrypted file (i.e. for recovery from elsewhere)
1240 let key128 = await Cipher.deriveKey(passphrase);
1241 let cipher = Cipher.create(key128);
1243 return cipher.decrypt(encWif);
1246 // tuple example {Promise<[String, Boolean]>}
1248 * @param {Object} [opts]
1249 * @param {Boolean} [opts.force]
1250 * @param {String} plainWif
1252 async function maybeEncrypt(plainWif, opts) {
1253 let passphrase = cmds._getPassphrase();
1255 let result = await cmds.getPassphrase({}, []);
1256 passphrase = result.passphrase;
1260 throw new Error(`no passphrase with which to encrypt file`);
1265 let key128 = await Cipher.deriveKey(passphrase);
1266 let cipher = Cipher.create(key128);
1267 return cipher.encrypt(plainWif);
1272 * @param {Array<String>} args
1274 async function setDefault(_, args) {
1275 let addr = args.shift() || "";
1277 let keyname = await findWif(addr);
1279 console.error(`no key matches '${addr}'`);
1284 let filepath = Path.join(keysDir, keyname);
1285 let wif = await maybeReadKeyFile(filepath);
1286 let pk = new Dashcore.PrivateKey(wif);
1287 let pub = pk.toAddress().toString();
1289 console.info("set", defaultWifPath, pub);
1290 await Fs.writeFile(defaultWifPath, pub, "utf8");
1293 // TODO option to specify config dir
1296 * @param {Object} opts
1297 * @param {any} opts.dashApi - TODO
1298 * @param {Array<String>} args
1300 async function listKeys({ dashApi }, args) {
1301 let wifnames = await listManagedKeynames();
1304 * @type Array<{ node: String, error: Error }>
1308 console.info(`🔑Holdings 🪧 Stakings 💸Earnings`);
1310 console.info(`Staking keys: (in ${keysDirRel}/)`);
1312 if (!wifnames.length) {
1313 console.info(` (none)`);
1315 await wifnames.reduce(async function (promise, wifname) {
1318 let wifpath = Path.join(keysDir, wifname);
1319 let addr = await maybeReadKeyFile(wifpath, { wif: false }).catch(function (
1322 warns.push({ node: wifname, error: err });
1330 let pk = new Dashcore.PrivateKey(wif);
1331 let pub = pk.toAddress().toString();
1332 if (`${pub}.wif` !== wifname) {
1337 `computed pubkey '${pub}' of WIF does not match filename '${wifname}'`,
1344 process.stdout.write(`${addr}: `);
1346 let balanceInfo = await dashApi.getInstantBalance(addr);
1347 let balanceDASH = toDASH(balanceInfo.balanceSat);
1349 let crowdNodeBalance = await CrowdNode.http.GetBalance(addr);
1350 if (!crowdNodeBalance.TotalBalance) {
1351 crowdNodeBalance.TotalBalance = 0;
1352 crowdNodeBalance.TotalDividend = 0;
1354 let crowdNodeDuffNum = toDuff(crowdNodeBalance.TotalBalance);
1355 let crowdNodeDASH = toDASH(crowdNodeDuffNum);
1357 let crowdNodeDivNum = toDuff(crowdNodeBalance.TotalDividend);
1358 let crowdNodeDivDASH = toDASH(crowdNodeDivNum);
1359 process.stdout.write(
1360 `${balanceDASH}🔑 ${crowdNodeDASH}🪧 ${crowdNodeDivDASH}💸`,
1364 }, Promise.resolve());
1368 console.warn(`Warnings:`);
1369 warns.forEach(function (warn) {
1370 console.warn(`${warn.node}: ${warn.error.message}`);
1377 * @param {String} name - ex: Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.wif.enc
1379 function isNamedLikeKey(name) {
1380 // TODO distinguish with .enc extension?
1381 let hasGoodLength = 34 + 4 === name.length || 34 + 4 + 4 === name.length;
1382 let knownExt = name.endsWith(".wif") || name.endsWith(".wif.enc");
1383 let isTmp = name.startsWith(".") || name.startsWith("_");
1384 return hasGoodLength && knownExt && !isTmp;
1388 * @param {Object} opts
1389 * @param {any} opts.dashApi - TODO
1390 * @param {String} opts.defaultAddr
1391 * @param {String} opts.insightBaseUrl
1392 * @param {Array<String>} args
1394 async function removeKey({ dashApi, defaultAddr, insightBaseUrl }, args) {
1395 let [addr, name] = await mustGetAddr({ defaultAddr }, args);
1396 let balanceInfo = await dashApi.getInstantBalance(addr);
1398 let balanceDash = toDash(balanceInfo.balanceSat);
1399 if (balanceInfo.balanceSat) {
1401 console.error(`Error: ${addr}`);
1403 ` still has a balance of ${balanceInfo.balanceSat} (Đ${balanceDash})`,
1405 console.error(` (transfer to another address before deleting)`);
1411 await initCrowdNode(insightBaseUrl);
1412 let crowdNodeBalance = await CrowdNode.http.GetBalance(addr);
1413 if (!crowdNodeBalance) {
1414 // may be janky if not registered
1415 crowdNodeBalance = {};
1417 if (!crowdNodeBalance.TotalBalance) {
1418 crowdNodeBalance.TotalBalance = 0;
1420 let crowdNodeDash = toDash(crowdNodeBalance.TotalBalance);
1421 if (crowdNodeBalance.TotalBalance) {
1423 console.error(`Error: ${addr}`);
1425 ` still staking ${crowdNodeBalance.TotalBalance} (Đ${crowdNodeDash}) on CrowdNode`,
1428 ` (withdrawal 100.0 and transfer to another address before deleting)`,
1435 let wifname = await findWif(addr);
1436 let filepath = Path.join(keysDir, wifname);
1437 let wif = await maybeReadKeyPaths(name, { wif: true });
1439 await Fs.unlink(filepath).catch(function (err) {
1440 console.error(`could not remove ${filepath}: ${err.message}`);
1444 let wifnames = await listManagedKeynames();
1446 console.info(`No balances found. Removing ${filepath}.`);
1448 console.info(`Backup (just in case):`);
1449 console.info(` ${wif}`);
1451 if (!wifnames.length) {
1452 console.info(`No keys left.`);
1455 let newAddr = wifnames[0];
1456 console.info(`Selected ${newAddr} as new default staking key.`);
1457 await Fs.writeFile(defaultWifPath, addr.replace(".wif", ""), "utf8");
1463 * @param {String} pre
1465 async function findWif(pre) {
1470 let names = await listManagedKeynames();
1471 names = names.filter(function (name) {
1472 return name.startsWith(pre);
1475 if (!names.length) {
1479 if (names.length > 1) {
1480 console.error(`'${pre}' is ambiguous:`, names.join(", "));
1488 async function listManagedKeynames() {
1489 let nodes = await Fs.readdir(keysDir);
1491 return nodes.filter(isNamedLikeKey);
1495 * @param {Object} opts
1496 * @param {String} opts.defaultAddr
1497 * @param {String} opts.insightBaseUrl
1498 * @param {Array<String>} args
1500 async function loadAddr({ defaultAddr, insightBaseUrl }, args) {
1501 let [addr] = await mustGetAddr({ defaultAddr }, args);
1503 let desiredAmountDash = parseFloat(args.shift() || "0");
1504 let desiredAmountDuff = Math.round(desiredAmountDash * DUFFS);
1506 let effectiveDuff = desiredAmountDuff;
1507 let effectiveDash = "";
1508 if (!effectiveDuff) {
1509 effectiveDuff = CrowdNode.stakeMinimum + signupTotal + feeEstimate;
1510 effectiveDuff = roundDuff(effectiveDuff, 3);
1511 effectiveDash = toDash(effectiveDuff);
1514 await plainLoadAddr({ addr, effectiveDash, effectiveDuff, insightBaseUrl });
1520 * 1000 to Round to the nearest mDash
1521 * ex: 0.50238108 => 0.50300000
1522 * @param {Number} effectiveDuff
1523 * @param {Number} numDigits
1525 function roundDuff(effectiveDuff, numDigits) {
1526 let n = Math.pow(10, numDigits);
1527 let effectiveDash = toDash(effectiveDuff);
1528 effectiveDuff = toDuff(
1529 (Math.ceil(parseFloat(effectiveDash) * n) / n).toString(),
1531 return effectiveDuff;
1535 * @param {Object} opts
1536 * @param {String} opts.addr
1537 * @param {String} opts.effectiveDash
1538 * @param {Number} opts.effectiveDuff
1539 * @param {String} opts.insightBaseUrl
1541 async function plainLoadAddr({
1548 showQr(addr, effectiveDuff);
1551 `Use the QR Code above to load ${effectiveDuff} (Đ${effectiveDash}) onto your staking key.`,
1554 console.info(`(waiting...)`);
1556 let payment = await Ws.waitForVout(insightBaseUrl, addr, 0);
1557 console.info(`Received ${payment.satoshis}`);
1561 * @param {Object} opts
1562 * @param {String} opts.defaultAddr
1563 * @param {any} opts.dashApi - TODO
1564 * @param {Array<String>} args
1566 async function getBalance({ dashApi, defaultAddr }, args) {
1567 let [addr] = await mustGetAddr({ defaultAddr }, args);
1568 await checkBalance({ addr, dashApi });
1569 //let balanceInfo = await checkBalance({ addr, dashApi });
1570 //console.info(balanceInfo);
1575 * @param {Object} opts
1576 * @param {any} opts.dashApi - TODO
1577 * @param {String} opts.defaultAddr
1578 * @param {Boolean} opts.forceConfirm
1579 * @param {String} opts.insightBaseUrl
1580 * @param {any} opts.insightApi
1581 * @param {Array<String>} args
1583 // ex: node ./bin/crowdnode.js transfer ./priv.wif 'pub' 0.01
1584 async function transferBalance(
1585 { dashApi, defaultAddr, forceConfirm, insightBaseUrl, insightApi },
1588 let wif = await mustGetWif({ defaultAddr }, args);
1590 let keyname = args.shift() || "";
1591 let newAddr = await wifFileToAddr(keyname);
1592 let dashAmount = parseFloat(args.shift() || "0");
1593 let duffAmount = Math.round(dashAmount * DUFFS);
1596 tx = await dashApi.createPayment(wif, newAddr, duffAmount);
1598 tx = await dashApi.createBalanceTransfer(wif, newAddr);
1601 let dashAmountStr = toDash(duffAmount);
1603 `Transferring ${duffAmount} (Đ${dashAmountStr}) to ${newAddr}...`,
1606 console.info(`Transferring balance to ${newAddr}...`);
1608 await insightApi.instantSend(tx);
1609 console.info(`Queued...`);
1610 setTimeout(function () {
1611 // TODO take a cleaner approach
1612 // (waitForVout needs a reasonable timeout)
1613 console.error(`Error: Transfer did not complete.`);
1615 console.error(`(using --unconfirmed may lead to rejected double spends)`);
1619 await Ws.waitForVout(insightBaseUrl, newAddr, 0);
1620 console.info(`Accepted!`);
1625 * @param {Object} opts
1626 * @param {any} opts.dashApi - TODO
1627 * @param {String} opts.defaultAddr
1628 * @param {String} opts.insightBaseUrl
1629 * @param {Array<String>} args
1631 async function getStatus({ dashApi, defaultAddr, insightBaseUrl }, args) {
1632 let [addr] = await mustGetAddr({ defaultAddr }, args);
1633 await initCrowdNode(insightBaseUrl);
1634 let hotwallet = CrowdNode.main.hotwallet;
1635 let state = await getCrowdNodeStatus({ addr, hotwallet });
1638 console.info(`API Actions Complete for ${addr}:`);
1639 console.info(` ${state.signup} SignUpForApi`);
1640 console.info(` ${state.accept} AcceptTerms`);
1641 console.info(` ${state.deposit} DepositReceived`);
1643 let crowdNodeBalance = await CrowdNode.http.GetBalance(addr);
1644 // may be unregistered / undefined
1647 * '@odata.context': 'https://app.crowdnode.io/odata/$metadata#Edm.String',
1648 * value: 'Address not found.'
1651 if (!crowdNodeBalance.TotalBalance) {
1652 crowdNodeBalance.TotalBalance = 0;
1654 let crowdNodeDuff = toDuff(crowdNodeBalance.TotalBalance);
1656 `CrowdNode Stake: ${crowdNodeDuff} (Đ${crowdNodeBalance.TotalBalance})`,
1663 * @param {Object} opts
1664 * @param {any} opts.dashApi - TODO
1665 * @param {String} opts.defaultAddr
1666 * @param {String} opts.insightBaseUrl
1667 * @param {Array<String>} args
1669 async function sendSignup({ dashApi, defaultAddr, insightBaseUrl }, args) {
1670 let [addr, name] = await mustGetAddr({ defaultAddr }, args);
1671 await initCrowdNode(insightBaseUrl);
1672 let hotwallet = CrowdNode.main.hotwallet;
1673 let state = await getCrowdNodeStatus({ addr, hotwallet });
1674 let balanceInfo = await checkBalance({ addr, dashApi });
1676 if (state.status?.signup) {
1677 console.info(`${addr} is already signed up. Here's the account status:`);
1678 console.info(` ${state.signup} SignUpForApi`);
1679 console.info(` ${state.accept} AcceptTerms`);
1680 console.info(` ${state.deposit} DepositReceived`);
1684 let hasEnough = balanceInfo.balanceSat > signupOnly + feeEstimate;
1686 await collectSignupFees(insightBaseUrl, addr);
1689 let wif = await maybeReadKeyPaths(name, { wif: true });
1691 console.info("Requesting account...");
1692 await CrowdNode.signup(wif, hotwallet);
1693 state.signup = DONE;
1694 console.info(` ${state.signup} SignUpForApi`);
1699 * @param {Object} opts
1700 * @param {any} opts.dashApi - TODO
1701 * @param {String} opts.defaultAddr
1702 * @param {String} opts.insightBaseUrl
1703 * @param {Array<String>} args
1705 async function acceptTerms({ dashApi, defaultAddr, insightBaseUrl }, args) {
1706 let [addr, name] = await mustGetAddr({ defaultAddr }, args);
1708 await initCrowdNode(insightBaseUrl);
1709 let hotwallet = CrowdNode.main.hotwallet;
1710 let state = await getCrowdNodeStatus({ addr, hotwallet });
1711 let balanceInfo = await dashApi.getInstantBalance(addr);
1713 if (!state.status?.signup) {
1714 console.info(`${addr} is not signed up yet. Here's the account status:`);
1715 console.info(` ${state.signup} SignUpForApi`);
1716 console.info(` ${state.accept} AcceptTerms`);
1721 if (state.status?.accept) {
1722 console.info(`${addr} is already signed up. Here's the account status:`);
1723 console.info(` ${state.signup} SignUpForApi`);
1724 console.info(` ${state.accept} AcceptTerms`);
1725 console.info(` ${state.deposit} DepositReceived`);
1728 let hasEnough = balanceInfo.balanceSat > acceptOnly + feeEstimate;
1730 await collectSignupFees(insightBaseUrl, addr);
1733 let wif = await maybeReadKeyPaths(name, { wif: true });
1735 console.info("Accepting terms...");
1736 await CrowdNode.accept(wif, hotwallet);
1737 state.accept = DONE;
1738 console.info(` ${state.accept} AcceptTerms`);
1743 * @param {Object} opts
1744 * @param {any} opts.dashApi - TODO
1745 * @param {String} opts.defaultAddr
1746 * @param {String} opts.insightBaseUrl
1747 * @param {Boolean} opts.noReserve
1748 * @param {Array<String>} args
1750 async function depositDash(
1751 { dashApi, defaultAddr, insightBaseUrl, noReserve },
1754 let [addr, name] = await mustGetAddr({ defaultAddr }, args);
1755 await initCrowdNode(insightBaseUrl);
1756 let hotwallet = CrowdNode.main.hotwallet;
1757 let state = await getCrowdNodeStatus({ addr, hotwallet });
1758 let balanceInfo = await dashApi.getInstantBalance(addr);
1760 if (!state.status?.accept) {
1761 console.error(`no account for address ${addr}`);
1766 // this would allow for at least 2 withdrawals costing (21000 + 1000)
1767 let reserve = 50000;
1768 let reserveDash = toDash(reserve);
1771 `reserving ${reserve} (Đ${reserveDash}) for withdrawals (--no-reserve to disable)`,
1777 // TODO if unconfirmed, check utxos instead
1779 // deposit what the user asks, or all that we have,
1780 // or all that the user deposits - but at least 2x the reserve
1781 let desiredAmountDash = parseFloat(args.shift() || "0");
1782 let desiredAmountDuff = Math.round(desiredAmountDash * DUFFS);
1783 let effectiveAmount = desiredAmountDuff;
1784 if (!effectiveAmount) {
1785 effectiveAmount = balanceInfo.balanceSat - reserve;
1787 let needed = Math.max(reserve * 2, effectiveAmount + reserve);
1789 if (balanceInfo.balanceSat < needed) {
1791 if (desiredAmountDuff) {
1792 ask = desiredAmountDuff + reserve + -balanceInfo.balanceSat;
1794 await collectDeposit(insightBaseUrl, addr, ask);
1795 balanceInfo = await dashApi.getInstantBalance(addr);
1796 if (balanceInfo.balanceSat < needed) {
1797 let balanceDash = toDash(balanceInfo.balanceSat);
1799 `Balance is still too small: ${balanceInfo.balanceSat} (Đ${balanceDash})`,
1805 if (!desiredAmountDuff) {
1806 effectiveAmount = balanceInfo.balanceSat - reserve;
1809 let effectiveDash = toDash(effectiveAmount);
1811 `Initiating deposit of ${effectiveAmount} (Đ${effectiveDash})...`,
1814 let wif = await maybeReadKeyPaths(name, { wif: true });
1816 await CrowdNode.deposit(wif, hotwallet, effectiveAmount);
1817 state.deposit = DONE;
1818 console.info(` ${state.deposit} DepositReceived`);
1823 * @param {Object} opts
1824 * @param {any} opts.dashApi - TODO
1825 * @param {String} opts.defaultAddr
1826 * @param {String} opts.insightBaseUrl
1827 * @param {Array<String>} args
1829 async function withdrawalDash({ dashApi, defaultAddr, insightBaseUrl }, args) {
1830 let [addr] = await mustGetAddr({ defaultAddr }, args);
1831 await initCrowdNode(insightBaseUrl);
1832 let hotwallet = CrowdNode.main.hotwallet;
1833 let state = await getCrowdNodeStatus({ addr, hotwallet });
1835 if (!state.status?.accept) {
1836 console.error(`no account for address ${addr}`);
1841 let percentStr = args.shift() || "100.0";
1842 // pass: .1 0.1, 1, 1.0, 10, 10.0, 100, 100.0
1843 // fail: 1000, 10.00
1844 if (!/^1?\d?\d?(\.\d)?$/.test(percentStr)) {
1845 console.error("Error: withdrawal percent must be between 0.1 and 100.0");
1848 let percent = parseFloat(percentStr);
1850 let permil = Math.round(percent * 10);
1851 if (permil <= 0 || permil > 1000) {
1852 console.error("Error: withdrawal percent must be between 0.1 and 100.0");
1856 let realPercentStr = (permil / 10).toFixed(1);
1857 console.info(`Initiating withdrawal of ${realPercentStr}...`);
1859 let wifname = await findWif(addr);
1860 let filepath = Path.join(keysDir, wifname);
1861 let wif = await maybeReadKeyFile(filepath);
1862 let paid = await CrowdNode.withdrawal(wif, hotwallet, permil);
1863 //let paidFloat = (paid.satoshis / DUFFS).toFixed(8);
1864 //let paidInt = paid.satoshis.toString().padStart(9, "0");
1865 console.info(`API Response: ${paid.api}`);
1872 * Convert prefix, addr, keyname, or filepath to pub addr
1873 * @param {String} name
1876 async function wifFileToAddr(name) {
1877 if (34 === name.length) {
1878 // actually payment addr
1884 let wifname = await findWif(name);
1886 let filepath = Path.join(keysDir, wifname);
1887 privKey = await maybeReadKeyFile(filepath);
1890 privKey = await maybeReadKeyFile(name);
1893 throw new Error("bad file path or address");
1896 let pk = new Dashcore.PrivateKey(privKey);
1897 let pub = pk.toPublicKey().toAddress().toString();
1902 * @param {String} insightBaseUrl
1903 * @param {String} addr
1905 async function collectSignupFees(insightBaseUrl, addr) {
1909 let signupTotalDash = toDash(signupTotal);
1910 let signupMsg = `Please send >= ${signupTotal} (Đ${signupTotalDash}) to Sign Up to CrowdNode`;
1911 let msgPad = Math.ceil((qrWidth - signupMsg.length) / 2);
1912 let subMsg = "(plus whatever you'd like to deposit)";
1913 let subMsgPad = Math.ceil((qrWidth - subMsg.length) / 2);
1916 console.info(" ".repeat(msgPad) + signupMsg);
1917 console.info(" ".repeat(subMsgPad) + subMsg);
1921 console.info("(waiting...)");
1923 let payment = await Ws.waitForVout(insightBaseUrl, addr, 0);
1924 console.info(`Received ${payment.satoshis}`);
1928 * @param {String} insightBaseUrl
1929 * @param {String} addr
1930 * @param {Number} duffAmount
1932 async function collectDeposit(insightBaseUrl, addr, duffAmount) {
1934 showQr(addr, duffAmount);
1936 let depositMsg = `Please send what you wish to deposit to ${addr}`;
1938 let dashAmount = toDash(duffAmount);
1939 depositMsg = `Please deposit ${duffAmount} (Đ${dashAmount}) to ${addr}`;
1942 let msgPad = Math.ceil((qrWidth - depositMsg.length) / 2);
1943 msgPad = Math.max(0, msgPad);
1946 console.info(" ".repeat(msgPad) + depositMsg);
1950 console.info("(waiting...)");
1952 let payment = await Ws.waitForVout(insightBaseUrl, addr, 0);
1953 console.info(`Received ${payment.satoshis}`);
1957 * @param {Error & { code: String }} err
1960 function emptyStringOnErrEnoent(err) {
1961 if ("ENOENT" !== err.code) {
1968 * @param {Number} duffs - ex: 00000000
1970 function toDash(duffs) {
1971 return (duffs / DUFFS).toFixed(8);
1975 * @param {Number} duffs - ex: 00000000
1977 function toDASH(duffs) {
1978 let dash = (duffs / DUFFS).toFixed(8);
1979 return `Đ${dash}`.padStart(13, " ");
1983 * @param {String} dash - ex: 0.00000000
1985 function toDuff(dash) {
1986 return Math.round(parseFloat(dash) * DUFFS);
1991 main().catch(function (err) {
1992 console.error("Fail:");
1993 console.error(err.stack || err);