Skip to content

Commit

Permalink
Merge branch '94-refactor/utils-privKey' into 'dev'
Browse files Browse the repository at this point in the history
refactor readPrivateKeyFromFile to read privKey with base64pad encoding

Closes #94

See merge request ergo/rosen-bridge/rosenet!56
  • Loading branch information
vorujack committed Nov 8, 2024
2 parents 013c7fa + f05bfb2 commit 262ec86
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/stale-baboons-yawn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@rosen-bridge/rosenet-utils': minor
---

Refactor readPrivateKeyFromFile to read privKey with base64pad encoding
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,4 @@ tests/*/*.tfstate*
tests/*/terraform.tfvars

.vscode/settings.json
.idea
25 changes: 18 additions & 7 deletions packages/utils/lib/readPrivateKeyFromFile.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { generateKeyPair, marshalPrivateKey } from '@libp2p/crypto/keys';
import { readFile, writeFile } from 'fs/promises';
import { resolve } from 'path';
import {
fromString as uint8ArrayFromString,
toString as uint8ArrayToString,
} from 'uint8arrays';

/**
* read private key from a file and return its string representation, creating
Expand All @@ -10,16 +14,23 @@ import { resolve } from 'path';
const readPrivateKeyFromFile = async (path: string) => {
const fullPath = resolve(path);
try {
return await readFile(fullPath, 'utf-8');
const fileData = await readFile(fullPath, 'utf-8');
const nodeDataJson = JSON.parse(fileData);
const privKeyUint8Array = uint8ArrayFromString(
nodeDataJson.privKey,
'base64pad',
);
return Buffer.from(privKeyUint8Array).toString('hex');
} catch (error) {
const privateKey = await generateKeyPair('Ed25519');
const privateKeyString = Buffer.from(
marshalPrivateKey(privateKey),
).toString('hex');
const marshalPrivKey = marshalPrivateKey(privateKey);
const privateKeyString = uint8ArrayToString(marshalPrivKey, 'base64pad');
const nodeDataJson = {
privKey: privateKeyString,
};
await writeFile(fullPath, JSON.stringify(nodeDataJson), 'utf-8');

await writeFile(fullPath, privateKeyString, 'utf-8');

return privateKeyString;
return Buffer.from(marshalPrivKey).toString('hex');
}
};

Expand Down

0 comments on commit 262ec86

Please sign in to comment.