2022-06-02 10:11:40 +00:00
|
|
|
import { keccak256 } from 'ethereum-cryptography/keccak'
|
2022-06-08 13:40:30 +00:00
|
|
|
import { getPublicKey, sign, utils } from 'ethereum-cryptography/secp256k1'
|
2022-06-10 15:46:38 +00:00
|
|
|
import { bytesToHex, concatBytes } from 'ethereum-cryptography/utils'
|
2022-06-02 10:11:40 +00:00
|
|
|
|
2022-06-14 12:28:08 +00:00
|
|
|
import { compressPublicKey } from './utils/compress-public-key'
|
2022-06-13 17:19:15 +00:00
|
|
|
import { generateUsername } from './utils/generate-username'
|
|
|
|
|
2022-06-02 10:11:40 +00:00
|
|
|
export class Account {
|
|
|
|
public privateKey: string
|
|
|
|
public publicKey: string
|
2022-06-03 15:44:55 +00:00
|
|
|
public chatKey: string
|
2022-06-13 17:19:15 +00:00
|
|
|
public username: string
|
2022-06-02 10:11:40 +00:00
|
|
|
|
|
|
|
constructor() {
|
|
|
|
const privateKey = utils.randomPrivateKey()
|
|
|
|
const publicKey = getPublicKey(privateKey)
|
|
|
|
|
|
|
|
this.privateKey = bytesToHex(privateKey)
|
2022-06-10 15:46:38 +00:00
|
|
|
this.publicKey = bytesToHex(publicKey)
|
2022-06-14 12:28:08 +00:00
|
|
|
this.chatKey = '0x' + compressPublicKey(this.publicKey)
|
2022-06-13 17:19:15 +00:00
|
|
|
this.username = generateUsername('0x' + this.publicKey)
|
2022-06-02 10:11:40 +00:00
|
|
|
}
|
|
|
|
|
2022-06-07 14:35:01 +00:00
|
|
|
// sig must be a 65-byte compact ECDSA signature containing the recovery id as the last element.
|
|
|
|
sign = async (payload: Uint8Array) => {
|
2022-06-03 15:44:55 +00:00
|
|
|
const hash = keccak256(payload)
|
2022-06-07 14:35:01 +00:00
|
|
|
const [signature, recoverId] = await sign(hash, this.privateKey, {
|
|
|
|
recovered: true,
|
|
|
|
der: false,
|
|
|
|
})
|
|
|
|
|
|
|
|
return concatBytes(signature, new Uint8Array([recoverId]))
|
|
|
|
}
|
2022-06-02 10:11:40 +00:00
|
|
|
}
|