Skip to content

Commit

Permalink
Merge pull request #17 from PinoutLTD/dev
Browse files Browse the repository at this point in the history
change to Ed25519 keys
  • Loading branch information
tubleronchik authored May 1, 2024
2 parents 099e96f + c54f7e8 commit 754b1e5
Showing 1 changed file with 33 additions and 19 deletions.
52 changes: 33 additions & 19 deletions utils/configurationManager.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import fs from 'fs/promises';
import PeerId from 'peer-id';
import { createFromJSON } from '@libp2p/peer-id-factory';
import { unmarshalPrivateKey } from '@libp2p/crypto/keys';
import {
createEd25519PeerId,
createFromPrivKey,
} from '@libp2p/peer-id-factory';
import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';
import { toString as uint8ArrayToString } from 'uint8arrays/to-string';

/**
* Libp2p node configuration manager. It checks if the JSON peer id exists,
Expand All @@ -12,21 +17,6 @@ export class ConfigurationManager {
this.logger = logger;
}

/**
* Generates peer id JSON file.
*/
async #generateJSONPeerId() {
this.logger.INFO('Generating json config...');
try {
const peerId = await PeerId.create();
const jsonContent = peerId.toJSON();
await fs.writeFile(this.filePath, JSON.stringify(jsonContent, null, 2));
this.logger.INFO(`Generated Private Key and stored in: ${this.filePath}`);
} catch (error) {
this.logger.ERROR(error, '#generateJSONPeerId');
}
}

/**
* Generates peer id json file if it not exists and returns it.
*/
Expand All @@ -41,8 +31,32 @@ export class ConfigurationManager {
}
}
const fileContent = await fs.readFile(this.filePath, 'utf-8');
const jsonContent = JSON.parse(fileContent);
const peerId = await createFromJSON(jsonContent);
const { privKey } = JSON.parse(fileContent);
const peerId = await this.#restorePeerIdFromPrivKey(privKey);
return peerId;
}

/**
* Generates peer id JSON file.
*/
async #generateJSONPeerId() {
this.logger.INFO('Generating json config...');
try {
const peerId = await createEd25519PeerId();
const privKey = uint8ArrayToString(peerId.privateKey, 'base64pad');
const jsonContent = { privKey };
await fs.writeFile(this.filePath, JSON.stringify(jsonContent, null, 2));
this.logger.INFO(`Generated Private Key and stored in: ${this.filePath}`);
} catch (error) {
this.logger.ERROR(error, '#generateJSONPeerId');
}
}

// eslint-disable-next-line class-methods-use-this
async #restorePeerIdFromPrivKey(privKey) {
const privateKey = uint8ArrayFromString(privKey, 'base64');
const key = await unmarshalPrivateKey(privateKey);
const peerId = await createFromPrivKey(key);
return peerId;
}
}

0 comments on commit 754b1e5

Please sign in to comment.