2022-11-02 00:58:41 +00:00
|
|
|
## Nim-Codex
|
|
|
|
## Copyright (c) 2022 Status Research & Development GmbH
|
|
|
|
## Licensed under either of
|
|
|
|
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
## at your option.
|
|
|
|
## This file may not be copied, modified, or distributed except according to
|
|
|
|
## those terms.
|
|
|
|
|
|
|
|
import pkg/upraises
|
|
|
|
push: {.upraises: [].}
|
|
|
|
|
|
|
|
import pkg/questionable/results
|
2023-08-01 23:47:57 +00:00
|
|
|
import pkg/libp2p/crypto/crypto
|
2022-11-02 00:58:41 +00:00
|
|
|
|
|
|
|
import ./fileutils
|
|
|
|
import ../errors
|
2023-12-19 22:12:47 +00:00
|
|
|
import ../logutils
|
2022-11-02 00:58:41 +00:00
|
|
|
import ../rng
|
|
|
|
|
2023-08-01 23:47:57 +00:00
|
|
|
export crypto
|
|
|
|
|
2022-11-02 00:58:41 +00:00
|
|
|
type
|
|
|
|
CodexKeyError = object of CodexError
|
|
|
|
CodexKeyUnsafeError = object of CodexKeyError
|
|
|
|
|
|
|
|
proc setupKey*(path: string): ?!PrivateKey =
|
|
|
|
if not path.fileAccessible({AccessFlags.Find}):
|
|
|
|
info "Creating a private key and saving it"
|
|
|
|
let
|
|
|
|
res = ? PrivateKey.random(Rng.instance()[]).mapFailure(CodexKeyError)
|
|
|
|
bytes = ? res.getBytes().mapFailure(CodexKeyError)
|
|
|
|
|
2022-11-07 14:54:24 +00:00
|
|
|
? path.secureWriteFile(bytes).mapFailure(CodexKeyError)
|
2022-11-02 00:58:41 +00:00
|
|
|
return PrivateKey.init(bytes).mapFailure(CodexKeyError)
|
|
|
|
|
|
|
|
info "Found a network private key"
|
2022-11-07 14:54:24 +00:00
|
|
|
if not ? checkSecureFile(path).mapFailure(CodexKeyError):
|
2022-11-02 00:58:41 +00:00
|
|
|
warn "The network private key file is not safe, aborting"
|
|
|
|
return failure newException(
|
|
|
|
CodexKeyUnsafeError, "The network private key file is not safe")
|
2023-12-19 22:12:47 +00:00
|
|
|
|
2023-08-01 23:47:57 +00:00
|
|
|
let kb = ? path.readAllBytes().mapFailure(CodexKeyError)
|
|
|
|
return PrivateKey.init(kb).mapFailure(CodexKeyError)
|