From 103f87f0cbc4309b1ababc84b42c1f2be4c4fdc3 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Sat, 7 Nov 2026 15:43:15 +0100 Subject: [PATCH 1/7] docs: quick-start: using an existing node key (plain or encrypted, Docker or native) A new section 10 for operators who keep an identity they already have: a plain key in the native folder before the set-up, an encrypted key on a console (not under systemd), a plain key in Docker (~/.credits/keys, uid 1000, mode 600; the container makes keys only when keys/NodePublic.txt is missing), and an encrypted key in Docker, converted once with the image's own node --dumpkeys. Also the native conversion for systemd. Troubleshooting becomes section 11. Co-Authored-By: Claude Opus 5.5 --- docs/quick-start.md | 152 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 151 insertions(+), 1 deletion(-) diff --git a/docs/quick-start.md b/docs/quick-start.md index 22f5acbe5..e2a940cef 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -295,7 +295,157 @@ Docker: `docker compose pull && docker compose up -d`. Native: Never run the old and the new node at the same time with the same key or the same `db/` folder. -## 10. Troubleshooting +## 10. Using your existing node key + +Your node's identity is its key: `NodePrivate.txt` and `NodePublic.txt`. To keep an identity you +already have, give the node those two files instead of letting it make new ones. First check which +kind of `NodePrivate.txt` you have: + +```sh +wc -c NodePrivate.txt # about 88 characters: plain; about 120: encrypted with a password +``` + +A **plain** key works everywhere. A key **encrypted by the node** (`--encryptkey`, or the password +choice at its first start) makes the node ask for the password at every start, on its console. + +Before you start: + +- **Never run two nodes with the same key**, not even for a moment. Stop the old node first. +- **Keep an offline backup** (USB stick, paper) of the original files. A plain key is as exposed + as the machine it is on. +- The wallet uses a plain node key as the account `node` without a password. On mainnet it still + asks you to type `send` before every transfer. + +### Native, plain key + +Put `NodePrivate.txt` and `NodePublic.txt` in the `csnode` folder **before** you run `./setup.sh` +(`setup.bat` on Windows). The set-up finds them, offers the key as the wallet's account `node` +(answer `node`), and sets `NodePrivate.txt` to mode 600. + +### Native, encrypted key + +Same place, same set-up. At every start the node asks: + +``` +The key file seems to be encrypted +To use password for encrytion/decryption press "p", to use file press "f": p +Enter password: ******** +``` + +This works in tmux or in a Windows console window you type into. It does **not** work under +systemd or any start without a console: the node cannot ask and does not start. Either keep it +in tmux, or convert the key to plain once ([below](#convert-an-encrypted-key-to-plain)). The +wallet opens an encrypted key with `--node-key` or as the account `node`, and asks the node's +password; it needs about 1 GB of free memory for that. + +### Docker, plain key + +1. Stop the node, and save the keys the container may have made at its first start: + + ```sh + docker compose stop + sudo cp -a ~/.credits/keys ~/.credits/keys.generated-$(date +%F) + ``` + +2. Copy your two files in, owned by the container's user (uid 1000), mode 600: + + ```sh + sudo cp NodePrivate.txt NodePublic.txt ~/.credits/keys/ + sudo chown 1000:1000 ~/.credits/keys/NodePrivate.txt ~/.credits/keys/NodePublic.txt + sudo chmod 600 ~/.credits/keys/NodePrivate.txt ~/.credits/keys/NodePublic.txt + ``` + +3. Start it and check the key it runs with: + + ```sh + docker compose up -d + docker compose exec node credits-wallet account node-key + ``` + + `address` must be your `NodePublic.txt`, with `public file : ... matches`. The log must not + show `new node keys` nor ask for a password. (The node does not print its own key in the log.) + +On a **new** installation you can put the two files in `~/.credits/keys/` (with the `chown` and +`chmod` above) before the first `docker compose up -d`: the container makes new keys only when +`keys/NodePublic.txt` is missing. Always copy both files. + +### Docker, encrypted key + +The container cannot type a password, so convert the key to plain once, with the node from the +same image, then continue as for a plain key. + +1. Stop the node and save its current keys (step 1 above). +2. Put the encrypted files in a temporary folder owned by uid 1000: + + ```sh + mkdir ~/keyconv + cp /path/to/old/NodePrivate.txt /path/to/old/NodePublic.txt ~/keyconv/ + sudo chown -R 1000:1000 ~/keyconv && sudo chmod 700 ~/keyconv + ``` + +3. Decrypt it. Type `p`, Enter, then the password and Enter. The node then waits about 10 seconds + (two 5-second countdowns: press nothing) and exits with `Keys dumped to /keyconv/keys.json`. + It needs no network and touches no data. + + ```sh + docker run --rm -it --network none -v ~/keyconv:/keyconv -w /opt/credits \ + --entrypoint /opt/credits/node ghcr.io/creditscommunity/credits-node:latest \ + --config-file config.ini.template --db-path /tmp/db \ + --public-key-file /keyconv/NodePublic.txt --private-key-file /keyconv/NodePrivate.txt \ + --dumpkeys /keyconv/keys.json + ``` + + A wrong password prints `Incorrect password (or corrupted file)` and asks again. If it asks + to rewrite the public key file, your `NodePublic.txt` does not belong to this key: type `q` + to stop, or `f` to write the right one. + +4. Write the two plain files (no newline at the end, mode 600, owner 1000): + + ```sh + docker run --rm -v ~/keyconv:/keyconv --entrypoint python3 \ + ghcr.io/creditscommunity/credits-node:latest -c "import json,os; \ + k=json.load(open('/keyconv/keys.json'))['key']; os.umask(0o077); os.makedirs('/keyconv/plain', exist_ok=True); \ + open('/keyconv/plain/NodePrivate.txt','w').write(k['private']); open('/keyconv/plain/NodePublic.txt','w').write(k['public'])" + ``` + +5. Install them, then delete the decrypted copies: + + ```sh + sudo cp -p ~/keyconv/plain/NodePrivate.txt ~/keyconv/plain/NodePublic.txt ~/.credits/keys/ + sudo shred -u ~/keyconv/keys.json ~/keyconv/plain/NodePrivate.txt ~/keyconv/plain/NodePublic.txt \ + ~/keyconv/NodePrivate.txt ~/keyconv/NodePublic.txt + sudo rm -r ~/keyconv + ``` + +6. Start and check, as in step 3 for a plain key. + +### Convert an encrypted key to plain + +Native variant, for example to run the node under systemd: the same `--dumpkeys` with the +package's `node`, in the `csnode` folder with the node **stopped** and the encrypted +`NodePrivate.txt` and `NodePublic.txt` in place. + +```sh +cp NodePrivate.txt ~/NodePrivate.encrypted.bak # move it offline afterwards +./node --config-file config.ini --db-path /tmp/keyconv-db --dumpkeys keys.json +python3 -c "import json,os; k=json.load(open('keys.json'))['key']; os.umask(0o077); \ +open('NodePrivate.txt','w').write(k['private']); open('NodePublic.txt','w').write(k['public'])" +chmod 600 NodePrivate.txt +shred -u keys.json && rm -rf /tmp/keyconv-db +``` + +Type `p` and the password as above. Without `python3`: +`jq -j .key.private keys.json > NodePrivate.txt` and `jq -j .key.public keys.json > NodePublic.txt`. +The node then starts without asking anything. On Windows use `node.exe` the same way, then in +PowerShell: + +```powershell +$k = (Get-Content keys.json | ConvertFrom-Json).key +[IO.File]::WriteAllText("$PWD\NodePrivate.txt", $k.private); [IO.File]::WriteAllText("$PWD\NodePublic.txt", $k.public) +Remove-Item keys.json +``` + +## 11. Troubleshooting | Problem | What to do | |---|---| From f6c9d05d118d2d5536c5fd5839bb3b9331acfacc Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Sat, 7 Nov 2026 15:43:40 +0100 Subject: [PATCH 2/7] docs: CHANGES: #174 Co-Authored-By: Claude Opus 5.5 --- docs/CHANGES.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/CHANGES.md b/docs/CHANGES.md index 9e146632c..346f47db7 100644 --- a/docs/CHANGES.md +++ b/docs/CHANGES.md @@ -45,6 +45,7 @@ lines under the new release. | PR | Change | |---|---| | #172 | docs: `docs/quick-start.md`, a short quick-start guide (Docker and native Linux, Windows and macOS; pruned on lmdb or full on rocksdb from the snapshot, snapshot serving on; requirements, ports, first checks, the wallet, upgrading with the database kept, common problems), linked from the top of the README | +| #174 | docs: quick-start: using an existing node key, plain or encrypted, in Docker or native (a section with copy-paste steps; an encrypted key converted once to plain with the node's own `--dumpkeys`, for Docker and systemd) | | #173 | packaging: a new full node defaults to rocksdb (it starts from a snapshot) in Docker and in the guided set-up (setup.sh, setup.ps1); pruned stays on lmdb; existing installs keep their backend (the database in `db/`, the `db_backend` of `config.ini`, berkeleydb for a full `[storage]` without one; the entrypoint also detects the database of a data folder whose `config.ini` was removed); `docker-compose.yml` takes its limits from `CREDITS_CPUS` (1.5) and `CREDITS_MEMORY` (4g) in `.env` (a full node: 4 and 8g); texts aligned: a full node on rocksdb about 250 to 300 GB, backfill about 2 to 3 days, glibc 2.38 for `linux-x64` (2.31 for `-glibc2.31`) in the README, the image `ghcr.io/creditscommunity/credits-node`, the `config.pruned.ini` comment on the snapshot start; quick-start, storage.md and the Docker README updated; ci: setup-test and the Docker entrypoint test check the rocksdb default and that a full berkeleydb install is kept | ## community.17 — 2026-11-05 From 408c5399fb5efa77cb423edbd017d077a3f4ba01 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Sat, 7 Nov 2026 15:44:04 +0100 Subject: [PATCH 3/7] docs: CHANGES: #174 after #173 Co-Authored-By: Claude Opus 5.5 --- docs/CHANGES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/CHANGES.md b/docs/CHANGES.md index 346f47db7..fad632539 100644 --- a/docs/CHANGES.md +++ b/docs/CHANGES.md @@ -45,8 +45,8 @@ lines under the new release. | PR | Change | |---|---| | #172 | docs: `docs/quick-start.md`, a short quick-start guide (Docker and native Linux, Windows and macOS; pruned on lmdb or full on rocksdb from the snapshot, snapshot serving on; requirements, ports, first checks, the wallet, upgrading with the database kept, common problems), linked from the top of the README | -| #174 | docs: quick-start: using an existing node key, plain or encrypted, in Docker or native (a section with copy-paste steps; an encrypted key converted once to plain with the node's own `--dumpkeys`, for Docker and systemd) | | #173 | packaging: a new full node defaults to rocksdb (it starts from a snapshot) in Docker and in the guided set-up (setup.sh, setup.ps1); pruned stays on lmdb; existing installs keep their backend (the database in `db/`, the `db_backend` of `config.ini`, berkeleydb for a full `[storage]` without one; the entrypoint also detects the database of a data folder whose `config.ini` was removed); `docker-compose.yml` takes its limits from `CREDITS_CPUS` (1.5) and `CREDITS_MEMORY` (4g) in `.env` (a full node: 4 and 8g); texts aligned: a full node on rocksdb about 250 to 300 GB, backfill about 2 to 3 days, glibc 2.38 for `linux-x64` (2.31 for `-glibc2.31`) in the README, the image `ghcr.io/creditscommunity/credits-node`, the `config.pruned.ini` comment on the snapshot start; quick-start, storage.md and the Docker README updated; ci: setup-test and the Docker entrypoint test check the rocksdb default and that a full berkeleydb install is kept | +| #174 | docs: quick-start: using an existing node key, plain or encrypted, in Docker or native (a section with copy-paste steps; an encrypted key converted once to plain with the node's own `--dumpkeys`, for Docker and systemd) | ## community.17 — 2026-11-05 From ce6a0268fc0dfb385abe8032792b61c7000ca8a5 Mon Sep 17 00:00:00 2001 From: EnzinoBB Date: Sat, 7 Nov 2026 16:47:49 +0100 Subject: [PATCH 4/7] node: --decryptkey (and docker decrypt-key) turns a password-encrypted key into the plain key --decryptkey asks the password of the private key file the node encrypted (the same prompt and retries as a start), checks that the key matches the public key file, keeps the encrypted file as .encrypted-YYYYMMDD-HHMMSS (mode 0600, created new, never overwriting), writes the plain key in place with the atomic key-file writer of #170 and exits. A plain key is left as it is (exit 0). It reads no configuration and opens no network or database; it refuses while db/.lock is held. The file format is the plain one the node already reads; no new crypto. writeKeyFile moves to keyfilecrypt.cpp with the new cs::keyfile::toPlain; the password loop of readKeys becomes unlockWithPrompt, shared by both. Docker: `docker compose run --rm node decrypt-key` runs it on /data/keys; a normal start with an encrypted key now stops with that command instead of waiting for a password. quick-start.md section 10 and the Docker README use these steps instead of the --dumpkeys procedure. Co-Authored-By: Claude Opus 5.5 --- client/config/config.cpp | 172 ++++++++-------- client/config/config.hpp | 3 + client/config/keyfilecrypt.cpp | 247 +++++++++++++++++++++++ client/config/keyfilecrypt.hpp | 40 ++++ client/src/main.cpp | 11 + docs/quick-start.md | 86 +++----- packaging/docker/README.md | 25 +++ packaging/docker/entrypoint.sh | 20 ++ packaging/docker/test/test-entrypoint.sh | 43 +++- tests/csnode/CMakeLists.txt | 4 +- tests/csnode/keyfilecrypt_tests.cpp | 191 ++++++++++++++++++ 11 files changed, 687 insertions(+), 155 deletions(-) diff --git a/client/config/config.cpp b/client/config/config.cpp index eccd1faf2..23424c7e9 100644 --- a/client/config/config.cpp +++ b/client/config/config.cpp @@ -209,73 +209,7 @@ static inline void writeFile(const std::string name, const std::string data) { file.close(); } -// the private key file (in clear, or encrypted by the node) and the keys JSON: readable by their -// owner only (mode 0600 on POSIX whatever the umask; Windows keeps the folder's ACL), and replaced -// atomically: the data goes to NAME.tmp, is flushed to disk, then renamed over NAME (a link named -// NAME is followed, its target replaced), and the folder is flushed where the system allows it. On -// any failure NAME is left as it was and false is returned. -static bool writeKeyFile(const std::string& name, const std::string& data) { -#ifndef _WIN32 - std::string target = name; - if (char* resolved = ::realpath(name.c_str(), nullptr)) { - target = resolved; - ::free(resolved); - } - const std::string tmp = target + ".tmp"; - const int fd = ::open(tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600); - if (fd < 0) { - return false; - } - bool ok = ::fchmod(fd, 0600) == 0; - size_t done = 0; - while (ok && done < data.size()) { - const ssize_t n = ::write(fd, data.data() + done, data.size() - done); - if (n < 0 && errno == EINTR) { - continue; - } - if (n <= 0) { - ok = false; - break; - } - done += static_cast(n); - } - ok = ok && ::fsync(fd) == 0; - ok = (::close(fd) == 0) && ok; - if (!ok || ::rename(tmp.c_str(), target.c_str()) != 0) { - ::unlink(tmp.c_str()); - return false; - } - const auto slash = target.find_last_of('/'); - const std::string dir = slash == std::string::npos ? std::string(".") : (slash == 0 ? std::string("/") : target.substr(0, slash)); - const int dfd = ::open(dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); - if (dfd >= 0) { // best effort: the rename is done either way - ::fsync(dfd); - ::close(dfd); - } - return true; -#else - const std::string tmp = name + ".tmp"; - HANDLE h = ::CreateFileA(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); - if (h == INVALID_HANDLE_VALUE) { - return false; - } - bool ok = true; - size_t done = 0; - while (ok && done < data.size()) { - DWORD n = 0; - const DWORD chunk = static_cast(std::min(data.size() - done, 1u << 20)); - ok = ::WriteFile(h, data.data() + done, chunk, &n, nullptr) && n > 0; - done += n; - } - ok = ok && ::FlushFileBuffers(h); - ok = ::CloseHandle(h) && ok; - if (!ok || !::MoveFileExA(tmp.c_str(), name.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { - ::DeleteFileA(tmp.c_str()); - return false; - } - return true; -#endif -} +using cs::keyfile::writeKeyFile; void Config::dumpJSONKeys(const std::string& fName) const { auto sk = privateKey_.access(); @@ -572,6 +506,39 @@ static bool getEncryptedPrivateBytes(const cscrypto::PrivateKey& sk, std::vector return encryptWithFile(sk, skBytes); } +// the encrypted key file's password (or key file), asked until it opens the key; an empty key when +// the input ends +static cscrypto::PrivateKey unlockWithPrompt(const cscrypto::Bytes& sk) { + cscrypto::PrivateKey key; + while (!key) { + if (!std::cin.good()) { + return cscrypto::PrivateKey(); + } + if (usePassword()) { + std::cout << "Enter password: " << std::flush; + cscrypto::MemGuard pass; + if (!readPasswordFromCin(pass)) { + return cscrypto::PrivateKey(); + } + std::cout << "Trying to open file..." << std::endl; + key = cs::keyfile::decrypt(sk, pass.data(), std::strlen(pass.data())); + } + else { + std::string buf; + if (!getBufFromFile(buf)) { + return cscrypto::PrivateKey(); + } + key = cs::keyfile::decrypt(sk, buf.data(), buf.size()); + wipe(buf); + } + + if (!key) { + std::cout << "Incorrect password (or corrupted file)" << std::endl; + } + } + return key; +} + static bool findWordInDictionary(const char* word, size_t& index) { using cscrypto::mnemonic::langs::en; bool found = false; @@ -716,30 +683,9 @@ bool Config::readKeys(const std::string& pathToPk, const std::string& pathToSk, if (encFlag) { // Check the encryption flag std::cout << "The key file seems to be encrypted" << std::endl; - while (!privateKey_) { - if (!std::cin.good()) - return false; - if (usePassword()) { - std::cout << "Enter password: " << std::flush; - cscrypto::MemGuard pass; - if (!readPasswordFromCin(pass)) { - return false; - } - std::cout << "Trying to open file..." << std::endl; - privateKey_ = cs::keyfile::decrypt(sk, pass.data(), std::strlen(pass.data())); - } - else { - std::string buf; - if (!getBufFromFile(buf)) { - return false; - } - privateKey_ = cs::keyfile::decrypt(sk, buf.data(), buf.size()); - wipe(buf); - } - - if (!privateKey_) { - std::cout << "Incorrect password (or corrupted file)" << std::endl; - } + privateKey_ = unlockWithPrompt(sk); + if (!privateKey_) { + return false; } changePasswordOption(pathToSk); } @@ -879,6 +825,50 @@ bool Config::readKeys(const std::string& pathToPk, const std::string& pathToSk, return true; } +/*public*/ +int Config::decryptKeyFile(const po::variables_map& vm) { + const std::string pathToPk = getArgFromCmdLine(vm, ARG_NAME_PUBLIC_KEY_FILE, DEFAULT_PATH_TO_PUBLIC_KEY); + const std::string pathToSk = getArgFromCmdLine(vm, ARG_NAME_PRIVATE_KEY_FILE, DEFAULT_PATH_TO_PRIVATE_KEY); + const auto unlock = [&pathToSk](const cscrypto::Bytes& sk) { + std::cout << pathToSk << " is encrypted: its password turns it into the plain key" << std::endl; + return unlockWithPrompt(sk); + }; + const auto r = cs::keyfile::toPlain(pathToPk, pathToSk, unlock, cs::keyfile::timestamp()); + using cs::keyfile::ToPlain; + switch (r.status) { + case ToPlain::Done: + std::cout << pathToSk << " is now in clear (address " << r.address << "); the encrypted original is kept as " << r.backup << std::endl; + std::cout << "Keep an offline copy of the original, never run two nodes with one key, and remember that the plain key is as safe as this machine." << std::endl; + return EXIT_SUCCESS; + case ToPlain::AlreadyPlain: + std::cout << pathToSk << " is already in clear (address " << r.address << "): nothing to do" << std::endl; + return EXIT_SUCCESS; + case ToPlain::NoPrivateFile: + std::cout << "No private key file " << pathToSk << " (set it with --private-key-file)" << std::endl; + break; + case ToPlain::BadPrivateFile: + std::cout << pathToSk << " holds neither a plain key nor a key encrypted by the node: nothing changed" << std::endl; + break; + case ToPlain::NoPublicFile: + std::cout << "No public key file " << pathToPk << " next to the encrypted key (set it with --public-key-file): nothing changed" << std::endl; + break; + case ToPlain::Cancelled: + std::cout << "No password given: nothing changed" << std::endl; + break; + case ToPlain::PublicMismatch: + std::cout << "The key in " << pathToSk << " is address " << r.address << ", but " << pathToPk + << " holds another public key: nothing changed (copy NodePublic.txt and NodePrivate.txt of the same node)" << std::endl; + break; + case ToPlain::BackupFailed: + std::cout << "Could not keep a copy of the encrypted " << pathToSk << " next to it (is the folder writable?): nothing changed" << std::endl; + break; + case ToPlain::WriteFailed: + std::cout << "Could not write " << pathToSk << ": it is still encrypted, as it was (a copy is in " << r.backup << ")" << std::endl; + break; + } + return EXIT_FAILURE; +} + /*public*/ bool Config::readKeys(const po::variables_map& vm) { return readKeys(getArgFromCmdLine(vm, ARG_NAME_PUBLIC_KEY_FILE, DEFAULT_PATH_TO_PUBLIC_KEY), diff --git a/client/config/config.hpp b/client/config/config.hpp index 980858036..55c762f50 100644 --- a/client/config/config.hpp +++ b/client/config/config.hpp @@ -352,6 +352,9 @@ class Config { } bool readKeys(const po::variables_map& vm); + // --decryptkey: the key file encrypted by the node becomes the plain key file after its password + // is typed (the encrypted file is kept next to it); the exit code. No configuration is read. + static int decryptKeyFile(const po::variables_map& vm); bool enterWithSeed(); const ConveyerData& conveyerData() const { diff --git a/client/config/keyfilecrypt.cpp b/client/config/keyfilecrypt.cpp index f7903edca..a6cdab7b2 100644 --- a/client/config/keyfilecrypt.cpp +++ b/client/config/keyfilecrypt.cpp @@ -1,7 +1,24 @@ #include "keyfilecrypt.hpp" +#include #include +#include #include +#include +#include +#include +#include + +#include + +#ifdef _WIN32 +#include +#else +#include +#include +#include +#include +#endif namespace cs { namespace keyfile { @@ -78,5 +95,235 @@ cscrypto::PrivateKey decrypt(const cscrypto::Bytes& bytes, const char* passwd, s return cscrypto::PrivateKey::readFromBytes(sk); } +bool writeKeyFile(const std::string& name, const std::string& data) { +#ifndef _WIN32 + std::string target = name; + if (char* resolved = ::realpath(name.c_str(), nullptr)) { + target = resolved; + ::free(resolved); + } + const std::string tmp = target + ".tmp"; + const int fd = ::open(tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600); + if (fd < 0) { + return false; + } + bool ok = ::fchmod(fd, 0600) == 0; + size_t done = 0; + while (ok && done < data.size()) { + const ssize_t n = ::write(fd, data.data() + done, data.size() - done); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + ok = false; + break; + } + done += static_cast(n); + } + ok = ok && ::fsync(fd) == 0; + ok = (::close(fd) == 0) && ok; + if (!ok || ::rename(tmp.c_str(), target.c_str()) != 0) { + ::unlink(tmp.c_str()); + return false; + } + const auto slash = target.find_last_of('/'); + const std::string dir = slash == std::string::npos ? std::string(".") : (slash == 0 ? std::string("/") : target.substr(0, slash)); + const int dfd = ::open(dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dfd >= 0) { // best effort: the rename is done either way + ::fsync(dfd); + ::close(dfd); + } + return true; +#else + const std::string tmp = name + ".tmp"; + HANDLE h = ::CreateFileA(tmp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + return false; + } + bool ok = true; + size_t done = 0; + while (ok && done < data.size()) { + DWORD n = 0; + const DWORD chunk = static_cast(std::min(data.size() - done, 1u << 20)); + ok = ::WriteFile(h, data.data() + done, chunk, &n, nullptr) && n > 0; + done += n; + } + ok = ok && ::FlushFileBuffers(h); + ok = ::CloseHandle(h) && ok; + if (!ok || !::MoveFileExA(tmp.c_str(), name.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { + ::DeleteFileA(tmp.c_str()); + return false; + } + return true; +#endif +} + + +namespace { +// the whole file; false when it cannot be read +bool readAll(const std::string& name, std::string& out) { + std::ifstream f(name, std::ios::binary); + if (!f.is_open()) { + return false; + } + out.assign(std::istreambuf_iterator(f), std::istreambuf_iterator()); + return !f.bad(); +} + +// the first line, as the node reads its key files (std::getline), without a trailing \r or blanks +std::string firstLine(const std::string& text) { + std::string line = text.substr(0, text.find('\n')); + while (!line.empty() && (line.back() == '\r' || line.back() == ' ' || line.back() == '\t')) { + line.pop_back(); + } + return line; +} + +void wipe(std::string& s) { + if (!s.empty()) { + sodium_memzero(&s[0], s.size()); + } + s.clear(); +} + +// a new file NAME with DATA, mode 0600, flushed; false when NAME exists (exists is set) or on an error +bool createNew(const std::string& name, const std::string& data, bool& exists) { + exists = false; +#ifndef _WIN32 + const int fd = ::open(name.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, 0600); + if (fd < 0) { + exists = errno == EEXIST; + return false; + } + bool ok = ::fchmod(fd, 0600) == 0; + size_t done = 0; + while (ok && done < data.size()) { + const ssize_t n = ::write(fd, data.data() + done, data.size() - done); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + ok = false; + break; + } + done += static_cast(n); + } + ok = ok && ::fsync(fd) == 0; + ok = (::close(fd) == 0) && ok; + if (!ok) { + ::unlink(name.c_str()); + } + return ok; +#else + HANDLE h = ::CreateFileA(name.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + const DWORD err = ::GetLastError(); + exists = err == ERROR_FILE_EXISTS || err == ERROR_ALREADY_EXISTS; + return false; + } + bool ok = true; + DWORD n = 0; + ok = data.empty() || (::WriteFile(h, data.data(), static_cast(data.size()), &n, nullptr) && n == data.size()); + ok = ok && ::FlushFileBuffers(h); + ok = ::CloseHandle(h) && ok; + if (!ok) { + ::DeleteFileA(name.c_str()); + } + return ok; +#endif +} +} // namespace + +ToPlainResult toPlain(const std::string& pathToPublic, const std::string& pathToPrivate, const Unlock& unlock, const std::string& stamp) { + ToPlainResult result; + + std::string content; + if (!readAll(pathToPrivate, content)) { + result.status = ToPlain::NoPrivateFile; + return result; + } + std::string sk58 = firstLine(content); + cscrypto::Bytes bytes; + const bool decoded = DecodeBase58(sk58, bytes); + wipe(sk58); + + if (decoded && bytes.size() == cscrypto::kPrivateKeySize) { + auto key = cscrypto::PrivateKey::readFromBytes(bytes); + sodium_memzero(bytes.data(), bytes.size()); + wipe(content); + if (!key) { + result.status = ToPlain::BadPrivateFile; + return result; + } + const auto pk = cscrypto::getMatchingPublic(key); + result.address = EncodeBase58(pk.data(), pk.data() + pk.size()); + result.status = ToPlain::AlreadyPlain; + return result; + } + if (!decoded || bytes.size() != kEncryptedSize) { + result.status = ToPlain::BadPrivateFile; + return result; + } + + // before the password: a key without its public key file is refused anyway + std::string publicText; + if (!readAll(pathToPublic, publicText)) { + result.status = ToPlain::NoPublicFile; + return result; + } + const std::string publicOnFile = firstLine(publicText); + + const cscrypto::PrivateKey key = unlock(bytes); + if (!key) { + result.status = ToPlain::Cancelled; + return result; + } + const auto pk = cscrypto::getMatchingPublic(key); + result.address = EncodeBase58(pk.data(), pk.data() + pk.size()); + if (result.address != publicOnFile) { + result.status = ToPlain::PublicMismatch; + return result; + } + + // the encrypted original first, under a name not taken yet + const std::string base = pathToPrivate + ".encrypted-" + stamp; + bool kept = false; + for (int i = 1; i <= 100 && !kept; ++i) { + const std::string name = i == 1 ? base : base + "-" + std::to_string(i); + bool exists = false; + if (createNew(name, content, exists)) { + result.backup = name; + kept = true; + } + else if (!exists) { + break; + } + } + if (!kept) { + result.status = ToPlain::BackupFailed; + return result; + } + + auto sk = key.access(); + std::string plain = EncodeBase58(sk.data(), sk.data() + sk.size()); + const bool written = writeKeyFile(pathToPrivate, plain); + wipe(plain); + result.status = written ? ToPlain::Done : ToPlain::WriteFailed; + return result; +} + +std::string timestamp() { + const std::time_t now = std::time(nullptr); + std::tm tm{}; +#ifdef _WIN32 + localtime_s(&tm, &now); +#else + localtime_r(&now, &tm); +#endif + char buf[32] = {}; + std::strftime(buf, sizeof(buf), "%Y%m%d-%H%M%S", &tm); + return buf; +} + } // namespace keyfile } // namespace cs diff --git a/client/config/keyfilecrypt.hpp b/client/config/keyfilecrypt.hpp index 0efa1f949..4b72771c7 100644 --- a/client/config/keyfilecrypt.hpp +++ b/client/config/keyfilecrypt.hpp @@ -2,6 +2,8 @@ #define CLIENT_CONFIG_KEYFILECRYPT_HPP #include +#include +#include #include @@ -32,6 +34,44 @@ cscrypto::Bytes encryptWithNonce(const cscrypto::PrivateKey& key, const char* pa // an empty key on a wrong password, a changed file, another length or a failed derivation cscrypto::PrivateKey decrypt(const cscrypto::Bytes& bytes, const char* passwd, std::size_t pswdLen); +// The private key file and the keys JSON: readable by their owner only (mode 0600 on POSIX whatever +// the umask; Windows keeps the folder's ACL), and replaced atomically: the data goes to NAME.tmp, is +// flushed to disk, then renamed over NAME (a link named NAME is followed, its target replaced), and +// the folder is flushed where the system allows it. On any failure NAME is left as it was and false +// is returned. +bool writeKeyFile(const std::string& name, const std::string& data); + +// --decryptkey: the private key file encrypted by the node (88 bytes) becomes the plain key file (64 +// bytes in base58, the format the node and keygen write). The encrypted file is kept first as +// .encrypted- (mode 0600, created new: an existing file of that name is never +// replaced, -2, -3... are added), then the plain key replaces the file with writeKeyFile. The public +// key file must exist and hold the key's public key, or nothing is changed. +enum class ToPlain { + Done, // written; address and backup are set + AlreadyPlain, // nothing to do; address is set + NoPrivateFile, + BadPrivateFile, // neither a plain nor an encrypted key + NoPublicFile, + Cancelled, // unlock returned no key (the input ended) + PublicMismatch, // address is the key's, NodePublic.txt holds another one + BackupFailed, // nothing changed + WriteFailed // the backup exists, the key file is as it was +}; + +struct ToPlainResult { + ToPlain status = ToPlain::Cancelled; + std::string address; // base58 public key of the private key + std::string backup; // the copy of the encrypted file +}; + +// unlock gets the encrypted bytes and returns the key, or an empty key to give up; stamp is the +// backup's suffix (timestamp()) +using Unlock = std::function; +ToPlainResult toPlain(const std::string& pathToPublic, const std::string& pathToPrivate, const Unlock& unlock, const std::string& stamp); + +// the local time as YYYYMMDD-HHMMSS +std::string timestamp(); + } // namespace keyfile } // namespace cs diff --git a/client/src/main.cpp b/client/src/main.cpp index 408e1112d..6989d85f5 100644 --- a/client/src/main.cpp +++ b/client/src/main.cpp @@ -72,6 +72,7 @@ int main(int argc, char* argv[]) { ("private-key-file", po::value(), "path to private key file (default: \"NodePrivate.txt\")") ("dumpkeys", po::value(), "dump your public and private keys into a JSON file with the specified name (UNENCRYPTED!)") ("encryptkey", "encrypts the private key with password upon startup (if not yet encrypted)") + ("decryptkey", "turn a private key file encrypted by the node into the plain key file after asking its password, then exit; the encrypted file is kept as .encrypted- (the node must be stopped; no configuration or database is needed)") #ifdef _WIN32 (cmdline::argInstall, po::value(), @@ -188,6 +189,16 @@ int main(int argc, char* argv[]) { #endif } + // the key files only: no configuration, network or database (db/.lock tells a running node) + if (vm.count("decryptkey") > 0) { + const std::string dbPath = vm.count(cmdline::argDBPath) ? vm[cmdline::argDBPath].as() : std::string("db"); + if (dbcheck::lockedByAnotherProcess(dbPath)) { + std::cerr << "a node runs with " << dbPath << " (db/.lock is held): stop it first, then run --decryptkey again" << std::endl; + return 3; + } + return Config::decryptKeyFile(vm); + } + auto config = Config::read(vm, true); if (!config.isGood()) { diff --git a/docs/quick-start.md b/docs/quick-start.md index e2a940cef..dbfa01a25 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -334,7 +334,8 @@ Enter password: ******** This works in tmux or in a Windows console window you type into. It does **not** work under systemd or any start without a console: the node cannot ask and does not start. Either keep it -in tmux, or convert the key to plain once ([below](#convert-an-encrypted-key-to-plain)). The +in tmux, or convert the key to plain once with `./node --decryptkey` +([below](#convert-an-encrypted-key-to-plain)). The wallet opens an encrypted key with `--node-key` or as the account `node`, and asks the node's password; it needs about 1 GB of free memory for that. @@ -371,79 +372,42 @@ On a **new** installation you can put the two files in `~/.credits/keys/` (with ### Docker, encrypted key -The container cannot type a password, so convert the key to plain once, with the node from the -same image, then continue as for a plain key. +The container cannot type a password at every start: with an encrypted key it stops with +`NOT STARTING: keys/NodePrivate.txt is encrypted`. Turn the key into the plain key once, with the +node of the image (community.18 or later); it asks the old password and needs no network. -1. Stop the node and save its current keys (step 1 above). -2. Put the encrypted files in a temporary folder owned by uid 1000: +1. Stop the node and save the keys it may have made (step 1 above). +2. Copy your two files in, as in step 2 above. +3. Decrypt and start: ```sh - mkdir ~/keyconv - cp /path/to/old/NodePrivate.txt /path/to/old/NodePublic.txt ~/keyconv/ - sudo chown -R 1000:1000 ~/keyconv && sudo chmod 700 ~/keyconv - ``` - -3. Decrypt it. Type `p`, Enter, then the password and Enter. The node then waits about 10 seconds - (two 5-second countdowns: press nothing) and exits with `Keys dumped to /keyconv/keys.json`. - It needs no network and touches no data. - - ```sh - docker run --rm -it --network none -v ~/keyconv:/keyconv -w /opt/credits \ - --entrypoint /opt/credits/node ghcr.io/creditscommunity/credits-node:latest \ - --config-file config.ini.template --db-path /tmp/db \ - --public-key-file /keyconv/NodePublic.txt --private-key-file /keyconv/NodePrivate.txt \ - --dumpkeys /keyconv/keys.json - ``` - - A wrong password prints `Incorrect password (or corrupted file)` and asks again. If it asks - to rewrite the public key file, your `NodePublic.txt` does not belong to this key: type `q` - to stop, or `f` to write the right one. - -4. Write the two plain files (no newline at the end, mode 600, owner 1000): - - ```sh - docker run --rm -v ~/keyconv:/keyconv --entrypoint python3 \ - ghcr.io/creditscommunity/credits-node:latest -c "import json,os; \ - k=json.load(open('/keyconv/keys.json'))['key']; os.umask(0o077); os.makedirs('/keyconv/plain', exist_ok=True); \ - open('/keyconv/plain/NodePrivate.txt','w').write(k['private']); open('/keyconv/plain/NodePublic.txt','w').write(k['public'])" + docker compose run --rm node decrypt-key # press p, Enter, then type the old password + docker compose up -d ``` -5. Install them, then delete the decrypted copies: + It prints `keys/NodePrivate.txt is now in clear (address ); the encrypted + original is kept as keys/NodePrivate.txt.encrypted--