UNPKG

tangerine-pie-key-pair

Version:
76 lines (55 loc) 1.88 kB
import * as fs from 'fs'; import { promises as fsp } from 'fs'; import { resolve } from 'path'; import * as AtekNet from '@atek-cloud/network'; import { fromBase32, toBase32 } from '@atek-cloud/network/dist/util.js'; export class KeyPair { constructor(publicKey=null, secretKey=null) { this.publicKey = publicKey; this.secretKey = secretKey; // If no arguments were provided, generate a new random key if (publicKey === null && secretKey === null) { const keyPair = AtekNet.createKeypair(); this.publicKey = keyPair.publicKey; this.secretKey = keyPair.secretKey; } } getPublicKey() { return this.publicKey; } getSecretKey() { return this.secretKey; } async readFile(path) { path = resolve(path); const json = await fsp.readFile(path, { encoding: 'utf-8' }); return this.readJSON(json); } async readFileSync(path) { path = resolve(path); const json = fs.readFile(path, { encoding: 'utf-8' }); return this.readJSON(json); } readJSON(json) { const object = JSON.parse(json); if (typeof object.publicKey === 'string') { this.publicKey = fromBase32(object.publicKey); } if (typeof object.secretKey === 'string') { this.secretKey = fromBase32(object.secretKey); } return this; } toString() { const object = { publicKey: toBase32(this.publicKey), secretKey: toBase32(this.secretKey) }; const json = JSON.stringify(object, null, 2); return json; } async writeFile(path) { const json = this.toString(); await fsp.writeFile(path, json, 'utf-8'); } }