|
| 1 | +import { Buffer } from 'buffer'; |
| 2 | +import TinySecp256k1 from './index.mjs'; |
| 3 | + |
| 4 | +class TinyEthSecp256k1 extends TinySecp256k1 { |
| 5 | + /** @typedef {import('js-sha3')} JsSha3 */ |
| 6 | + /** @typedef {import('elliptic').ec.KeyPair} KeyPair */ |
| 7 | + |
| 8 | + /** |
| 9 | + * Creates an instance of TinyEthSecp256k1. |
| 10 | + * |
| 11 | + * @param {Object} [options] - Optional parameters for the instance. |
| 12 | + * @param {string|null} [options.msgPrefix='\x19Ethereum Signed Message:\n'] - Message prefix used during message signing. |
| 13 | + * @param {string|null} [options.privateKey=null] - String representation of the private key. |
| 14 | + * @param {BufferEncoding} [options.privateKeyEncoding='hex'] - Encoding used for the privateKey string. |
| 15 | + */ |
| 16 | + constructor({ |
| 17 | + msgPrefix = '\x19Ethereum Signed Message:\n', |
| 18 | + privateKey = null, |
| 19 | + privateKeyEncoding = 'hex', |
| 20 | + } = {}) { |
| 21 | + super({ msgPrefix, privateKey, privateKeyEncoding }); |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Initializes the internal elliptic key pair using the private key. |
| 26 | + * |
| 27 | + * @returns {Promise<KeyPair>} The elliptic key pair. |
| 28 | + */ |
| 29 | + async init() { |
| 30 | + await Promise.all([this.fetchElliptic(), this.fetchJsSha3()]); |
| 31 | + const ec = this.getEc(); |
| 32 | + this.keyPair = ec.keyFromPrivate(this.privateKey); |
| 33 | + return this.keyPair; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Dynamically imports the `jsSha3` module and stores it in the instance. |
| 38 | + * Ensures the module is loaded only once (lazy singleton). |
| 39 | + * |
| 40 | + * @returns {Promise<JsSha3>} The loaded `jsSha3` module. |
| 41 | + */ |
| 42 | + async fetchJsSha3() { |
| 43 | + if (!this.jsSha3) { |
| 44 | + const jsSha3 = await import(/* webpackMode: "eager" */ 'js-sha3').catch(() => { |
| 45 | + console.warn( |
| 46 | + '[JsSha3] Warning: "js-sha3" is not installed. ' + |
| 47 | + 'JsSha3 requires "js-sha3" to function properly. ' + |
| 48 | + 'Please install it with "npm install js-sha3".', |
| 49 | + ); |
| 50 | + return null; |
| 51 | + }); |
| 52 | + if (jsSha3) { |
| 53 | + // @ts-ignore |
| 54 | + this.jsSha3 = jsSha3?.default ?? jsSha3; |
| 55 | + } |
| 56 | + } |
| 57 | + return this.getJsSha3(); |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * Returns the initialized `jsSha3` instance from the jsSha3 module. |
| 62 | + * |
| 63 | + * @returns {JsSha3} The jsSha3 instance. |
| 64 | + * @throws Will throw an error if `jsSha3` is not initialized. |
| 65 | + */ |
| 66 | + getJsSha3() { |
| 67 | + if (typeof this.jsSha3 === 'undefined' || this.jsSha3 === null) |
| 68 | + throw new Error( |
| 69 | + `Failed to initialize JsSha3: Module is ${this.jsSha3 !== null ? 'undefined' : 'null'}.\n` + |
| 70 | + 'Please make sure "js-sha3" is installed.\n' + |
| 71 | + 'You can install it by running: npm install js-sha3', |
| 72 | + ); |
| 73 | + // @ts-ignore |
| 74 | + return this.jsSha3; |
| 75 | + } |
| 76 | + |
| 77 | + /** |
| 78 | + * Returns the public key as a buffer. |
| 79 | + * @param {boolean} [compressed=false] - Ethereum não usa chaves comprimidas. |
| 80 | + * @returns {Buffer} |
| 81 | + */ |
| 82 | + #getPublicKeyBuffer(compressed = false) { |
| 83 | + return Buffer.from(this.getKeyPair().getPublic(compressed, 'array')); |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + |
| 88 | + * Apply EIP-55 checksum to a lowercase address. |
| 89 | + * @param {string} address - Hex string without 0x prefix. |
| 90 | + * @returns {string} |
| 91 | + */ |
| 92 | + #toChecksumAddress(address) { |
| 93 | + const { keccak256 } = this.getJsSha3(); |
| 94 | + const hash = keccak256(address.toLowerCase()); |
| 95 | + let checksumAddress = '0x'; |
| 96 | + for (let i = 0; i < address.length; i++) { |
| 97 | + const char = address[i]; |
| 98 | + const hashChar = parseInt(hash[i], 16); |
| 99 | + checksumAddress += hashChar >= 8 ? char.toUpperCase() : char.toLowerCase(); |
| 100 | + } |
| 101 | + |
| 102 | + return checksumAddress; |
| 103 | + } |
| 104 | + |
| 105 | + /** |
| 106 | + * Generate the Ethereum address from the public key. |
| 107 | + * |
| 108 | + * @param {Buffer} pubKey |
| 109 | + * @returns {string} |
| 110 | + */ |
| 111 | + #getAddress(pubKey) { |
| 112 | + const { keccak256 } = this.getJsSha3(); |
| 113 | + const addressBuf = Buffer.from(keccak256.arrayBuffer(pubKey)).subarray(-20); |
| 114 | + const addressHex = [...addressBuf].map((b) => b.toString(16).padStart(2, '0')).join(''); |
| 115 | + return this.#toChecksumAddress(addressHex); |
| 116 | + } |
| 117 | + |
| 118 | + /** |
| 119 | + * Returns the public key in hexadecimal. |
| 120 | + * @returns {string} |
| 121 | + */ |
| 122 | + getPublicKeyHex() { |
| 123 | + return this.getKeyPair().getPublic(false, 'hex'); |
| 124 | + } |
| 125 | + |
| 126 | + /** |
| 127 | + * Generate the Ethereum address from the public key. |
| 128 | + * @returns {string} |
| 129 | + */ |
| 130 | + getAddress() { |
| 131 | + const pubKey = this.#getPublicKeyBuffer(false).subarray(1); // remove byte 0x04 |
| 132 | + return this.#getAddress(pubKey); |
| 133 | + } |
| 134 | + |
| 135 | + /** |
| 136 | + * Sign a message using Ethereum prefix. |
| 137 | + * @param {string|Buffer} message - The message to be signed. |
| 138 | + * @param {Object} [options] - Optional signing parameters. |
| 139 | + * @param {BufferEncoding} [options.encoding='utf8'] - Encoding for input message if it is a string. |
| 140 | + * @param {string} [options.prefix] - Optional prefix (defaults to Ethereum prefix or instance default). |
| 141 | + * @returns {Buffer} The signature. |
| 142 | + */ |
| 143 | + signMessage(message, options = {}) { |
| 144 | + const { keccak256 } = this.getJsSha3(); |
| 145 | + const keyPair = this.getKeyPair(); |
| 146 | + const { prefix = this.msgPrefix, encoding = 'utf8' } = options; |
| 147 | + const msgBuffer = Buffer.isBuffer(message) ? message : Buffer.from(message, encoding); |
| 148 | + const ethMessage = Buffer.concat([Buffer.from(`${prefix}${msgBuffer.length}`), msgBuffer]); |
| 149 | + const msgHash = Buffer.from(keccak256.arrayBuffer(ethMessage)); |
| 150 | + |
| 151 | + const sig = keyPair.sign(msgHash, { canonical: true }); |
| 152 | + |
| 153 | + // Calculate recid (recovery param) |
| 154 | + const recid = sig.recoveryParam; |
| 155 | + if (recid === null) |
| 156 | + throw new Error( |
| 157 | + 'Failed to calculate recovery param (recid) from signature. Signature may be invalid or keyPair is not properly initialized.', |
| 158 | + ); |
| 159 | + |
| 160 | + const r = sig.r.toArrayLike(Buffer, 'be', 32); |
| 161 | + const s = sig.s.toArrayLike(Buffer, 'be', 32); |
| 162 | + const v = Buffer.from([recid + 27]); |
| 163 | + return Buffer.concat([r, s, v]); |
| 164 | + } |
| 165 | + |
| 166 | + /** |
| 167 | + * Recovers the address from the message and the signature. |
| 168 | + * @param {string|Buffer} message The original message. |
| 169 | + * @param {Buffer|string} signature - Signature in DER format (base64-encoded or Buffer). |
| 170 | + * @param {Object} [options] - Optional signing parameters. |
| 171 | + * @param {BufferEncoding} [options.encoding='utf8'] - Encoding for input message if it is a string. |
| 172 | + * @param {string} [options.prefix] - Optional prefix (defaults to Ethereum prefix or instance default). |
| 173 | + * @returns {string|null} |
| 174 | + */ |
| 175 | + recoverMessage(message, signature, options = {}) { |
| 176 | + const { keccak256 } = this.getJsSha3(); |
| 177 | + const { prefix = this.msgPrefix, encoding = 'utf8' } = options; |
| 178 | + const sigBuf = typeof signature === 'string' ? Buffer.from(signature, 'hex') : signature; |
| 179 | + if (sigBuf.length !== 65) return null; |
| 180 | + |
| 181 | + const r = sigBuf.subarray(0, 32); |
| 182 | + const s = sigBuf.subarray(32, 64); |
| 183 | + const vRaw = sigBuf[64]; |
| 184 | + if (vRaw !== 27 && vRaw !== 28) return null; |
| 185 | + const v = vRaw - 27; |
| 186 | + |
| 187 | + const msgBuffer = Buffer.isBuffer(message) ? message : Buffer.from(message, encoding); |
| 188 | + const ethMessage = Buffer.concat([Buffer.from(`${prefix}${msgBuffer.length}`), msgBuffer]); |
| 189 | + const msgHash = Buffer.from(keccak256.arrayBuffer(ethMessage)); |
| 190 | + |
| 191 | + const ec = this.getEc(); |
| 192 | + const pubKey = ec.recoverPubKey(msgHash, { r, s }, v); |
| 193 | + const pubBuffer = Buffer.from(pubKey.encode('array', false)).subarray(1); |
| 194 | + return this.#getAddress(pubBuffer); |
| 195 | + } |
| 196 | +} |
| 197 | + |
| 198 | +export default TinyEthSecp256k1; |
0 commit comments