bc-web3js
Version:
A Typescript SDK for interacting with the ByteChain Blockchain.
51 lines (50 loc) • 2.07 kB
JavaScript
import * as crypto from 'crypto';
import elliptic_pkg from 'elliptic';
import base58 from 'bs58';
const { ec: EC } = elliptic_pkg;
const ec = new EC('secp256k1');
class Account {
priv_key;
pub_key;
blockchain_addr;
constructor(priv_key) {
if (priv_key) {
this.priv_key = priv_key;
this.pub_key = Account.create_pub_key(this.priv_key);
this.blockchain_addr = Account.create_blockchain_addr(this.pub_key);
}
else {
this.priv_key = ec.genKeyPair().getPrivate('hex');
this.pub_key = Account.create_pub_key(this.priv_key);
this.blockchain_addr = Account.create_blockchain_addr(this.pub_key);
}
}
static new() {
const priv_key = ec.genKeyPair().getPrivate('hex');
const pub_key = Account.create_pub_key(priv_key);
const blockchain_addr = Account.create_blockchain_addr(pub_key);
return { priv_key, pub_key, blockchain_addr };
}
// Generates the public key from a private key
static create_pub_key(priv_key) {
const key_pair = ec.keyFromPrivate(priv_key);
const pub_key = key_pair.getPublic('hex');
return pub_key;
}
// Creates a blockchain address from the public key
static create_blockchain_addr(pub_key) {
const pub_key_buffer = Buffer.from(pub_key, 'hex');
const sha256_hash = crypto.createHash('sha256').update(pub_key_buffer).digest();
const ripemd160_hash = crypto.createHash('ripemd160').update(sha256_hash).digest();
const version_byte = Buffer.from([0xBC]);
const payload = Buffer.concat([version_byte, ripemd160_hash]);
const checksum = crypto.createHash('sha256').update(crypto.createHash('sha256').update(payload).digest()).digest().slice(0, 4);
const final_payload = Buffer.concat([payload, checksum]);
const blockchain_addr = base58.encode(final_payload);
return blockchain_addr;
}
sign_tx(tx) {
return tx.sign_tx(this.priv_key);
}
}
export default Account;