8000 refactor!: pack secret args by oritwoen · Pull Request #322 · agntn/keys · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/content/1.guide/2.keys.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ That's `0xd1E64E5480bFaf733Ba7D48712DEcb8227797a4e`. The file comes from geth's

A wrong password throws `KeystorePasswordError`. A key that doesn't match the stored `address` throws too. `Crypto` with a capital C, the way ethers writes it, reads fine. `inspect` gives the KDF, its costs and the stored address without any password.

`encrypt(key, password)` goes the other way. By default it uses geth's cost, scrypt with `n: 262144`, `r: 8` and `p: 1`. That's about a second. Pass `kdf: { kdf: "pbkdf2", c: 262144 }` for PBKDF2. The password goes in as UTF-8, exactly as typed, like geth. ethers runs NFKC over it first. Plain text is the same either way, a ligature is not.
`encrypt(key, { password })` goes the other way. By default it uses geth's cost, scrypt with `n: 262144`, `r: 8` and `p: 1`. That's about a second. Pass `kdf: { kdf: "pbkdf2", c: 262144 }` for PBKDF2. The password goes in as UTF-8, exactly as typed, like geth. ethers runs NFKC over it first. Plain text is the same either way, a ligature is not.

Version 1 and 2 files and the presale wallet don't open here. An old scrypt file with `r: 1` and `n` of 65536 or more doesn't either. `@agntn/hashes` keeps scrypt inside RFC 7914 and refuses it.

Expand Down
12 changes: 2 additions & 10 deletions docs/content/1.guide/6.custom.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,22 +63,14 @@ export class MyChain extends AbstractBlockchain {
}

override signMessage(message: string | Uint8Array, options: SignMessageOptions<KeyOptions>): string {
const { privateKey, ...keyOptions } = options;
return genericSignMessage(message, privateKey, {
curve: "secp256k1",
...keyOptions,
});
return genericSignMessage(message, { curve: "secp256k1", ...options });
}

override verifyMessage(
message: string | Uint8Array,
options: VerifyMessageOptions<KeyOptions>,
): boolean {
const { signature, publicKey, ...keyOptions } = options;
return genericVerifyMessage(message, signature, publicKey, {
curve: "secp256k1",
...keyOptions,
});
return genericVerifyMessage(message, { curve: "secp256k1", ...options });
}
}

Expand Down
2 changes: 1 addition & 1 deletion docs/content/2.blockchains/bitcoin.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ const [first] = extractSignatures(rawTx, { index: 0, spent });
const [second] = extractSignatures(rawTx, { index: 1, spent });
// both: { type: "ecdsa", r: "d47ce4c0...", s, z, hashType: 1, publicKey: "04dbd0c6..." }

recoverReusedNonce(first, second); // { privateKey, nonce, publicKey: "03dbd0c6..." }
recoverReusedNonce([first, second]); // { privateKey, nonce, publicKey: "03dbd0c6..." }
```

`spent` is what each input spends. Grab the script and the value from any explorer. Legacy, SegWit v0 and Taproot key path all work, with every hash type. That 2012 transaction even has DER from before BIP66, and it reads fine. Taproot wants every spent output, unless it signs with `ANYONECANPAY`. Script paths and `OP_CODESEPARATOR` get refused, not guessed.
Expand Down
16 changes: 7 additions & 9 deletions src/blockchains/cosmos.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,14 +177,13 @@ export class Cosmos extends AbstractBlockchain {
*/
override signMessage(message: string | Uint8Array, options: SignMessageOptions): string {
assertSignOptions(options);
const { privateKey, ...signingOptions } = options;
assertNoRecoveryByte(
signingOptions,
options,
"Cosmos signs ADR-036 as 64 bytes of r||s, with no recovery byte",
);
const signer = this.getAddress(generateKeyPublic(privateKey));
return signMessage(signDoc(signer, message), privateKey, {
...signingOptions,
const signer = this.getAddress(generateKeyPublic(options.privateKey));
return signMessage(signDoc(signer, message), {
...options,
curve: "secp256k1",
hash: true,
});
Expand All @@ -198,11 +197,10 @@ export class Cosmos extends AbstractBlockchain {
*/
override verifyMessage(message: string | Uint8Array, options: VerifyMessageOptions): boolean {
assertVerifyOptions(options);
const { signature, publicKey, ...signingOptions } = options;
if (hasRecoveryByte(signature)) return false;
if (hasRecoveryByte(options.signature)) return false;
try {
return verifyMessage(signDoc(this.getAddress(publicKey), message), signature, publicKey, {
...signingOptions,
return verifyMessage(signDoc(this.getAddress(options.publicKey), message), {
...options,
curve: "secp256k1",
hash: true,
});
Expand Down
7 changes: 5 additions & 2 deletions src/blockchains/decred.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,10 @@ export class Decred extends AbstractBlockchain {
assertSignOptions(options);
const { privateKey, ...signingOptions } = options;
if (readRecoveredFlag(signingOptions)) {
return signCompact(hashMessage(message), privateKey, signingOptions.compressed !== false);
return signCompact(hashMessage(message), {
privateKey,
compressed: signingOptions.compressed !== false,
});
}
return secp256k1
.sign(hashMessage(message), decodeKeyPrivate(privateKey), { prehash: false })
Expand All @@ -136,7 +139,7 @@ export class Decred extends AbstractBlockchain {
return false;
}
if (isCompactSignature(signature)) {
return verifyCompact(hashMessage(message), signature, keyPublic);
return verifyCompact(hashMessage(message), { signature, publicKey: keyPublic });
}
try {
return secp256k1.verify(
Expand Down
18 changes: 8 additions & 10 deletions src/blockchains/sui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,13 @@ export class Sui extends AbstractDualCurveBlockchain {
options: SignMessageOptions<KeyOptions>,
): string {
assertSignOptions(options);
const { privateKey, ...keyOptions } = options;
assertNoRecoveryByte(
keyOptions,
options,
"Sui serializes a signature as flag||signature||publicKey, with no recovery byte",
);
return signMessage(hashPersonalMessage(message), privateKey, {
...keyOptions,
curve: this.resolveCurve(keyOptions),
return signMessage(hashPersonalMessage(message), {
...options,
curve: this.resolveCurve(options),
hash: true,
});
}
Expand All @@ -170,13 +169,12 @@ export class Sui extends AbstractDualCurveBlockchain {
options: VerifyMessageOptions<KeyOptions>,
): boolean {
assertVerifyOptions(options);
const { signature, publicKey, ...keyOptions } = options;
if (hasRecoveryByte(signature)) {
if (hasRecoveryByte(options.signature)) {
return false;
}
return verifyMessage(hashPersonalMessage(message), signature, publicKey, {
...keyOptions,
curve: this.resolveCurve(keyOptions),
return verifyMessage(hashPersonalMessage(message), {
...options,
curve: this.resolveCurve(options),
hash: true,
});
}
Expand Down
10 changes: 4 additions & 6 deletions src/blockchains/tron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,8 @@ export class Tron extends AbstractBlockchain {
options: SignMessageOptions<RecoverableSigningOptions>,
): string {
assertSignOptions(options);
const { privateKey, ...signingOptions } = options;
return signMessage(hashWithPreamble(message, MESSAGE_PREAMBLE), privateKey, {
...signingOptions,
return signMessage(hashWithPreamble(message, MESSAGE_PREAMBLE), {
...options,
curve: "secp256k1",
hash: false,
});
Expand All @@ -73,9 +72,8 @@ export class Tron extends AbstractBlockchain {
options: VerifyMessageOptions<RecoverableSigningOptions>,
): boolean {
assertVerifyOptions(options);
const { signature, publicKey, ...signingOptions } = options;
return verifyMessage(hashWithPreamble(message, MESSAGE_PREAMBLE), signature, publicKey, {
...signingOptions,
return verifyMessage(hashWithPreamble(message, MESSAGE_PREAMBLE), {
...options,
curve: "secp256k1",
hash: false,
});
Expand Down
6 changes: 4 additions & 2 deletions src/tool-operations/secp256k1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,10 @@ export function recoverSecp256k1Nonce(
shape: "SEC1 or x-only hex",
});
const recovered = recoverReusedNonce(
{ type, ...(first ?? { r: "", s: "", z: "" }) },
{ type, ...(second ?? { r: "", s: "", z: "" }) },
[
{ type, ...(first ?? { r: "", s: "", z: "" }) },
{ type, ...(second ?? { r: "", s: "", z: "" }) },
],
publicKey === undefined ? {} : { publicKey },
);
const lines = [
Expand Down
46 changes: 14 additions & 32 deletions src/utils/bip38/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ecb } from "@agntn/ciphers/aes";
import { create, sha256, type ScryptOptions } from "@agntn/hashes";
import { scrypt, sha256 } from "@agntn/hashes";
import { secp256k1 } from "@noble/curves/secp256k1.js";
import { equalBytes } from "@noble/curves/utils.js";
import { generateAddressLegacy } from "../address.ts";
Expand Down Expand Up @@ -56,6 +56,12 @@ const EC_MULTIPLY_PREFIX = 0x43;
const COMPRESSED = 0x20;
const LOT_SEQUENCE = 0x04;

/** What an EC multiply key opens with: passphrase bytes, and whether a lot and sequence ride in. */
interface EcMultiplySecret {
readonly passphrase: Uint8Array;
readonly hasLotSequence: boolean;
}

/**
* First four bytes of the double SHA-256 of an address string, as BIP38 stores it.
* @param address - Address text, hashed as ASCII
Expand Down Expand Up @@ -173,26 +179,6 @@ function readOwnerEntropy(ownerEntropy: Uint8Array, hasLotSequence: boolean) {
};
}

/**
* scrypt with the costs BIP38 fixes for each step.
* @param password - Passphrase or passpoint bytes
* @param salt - Salt bytes
* @param cost - N, r and p
* @param keyLength - Output length in bytes
* @returns {Uint8Array} The derived bytes
*/
function scrypt(
password: Uint8Array,
salt: Uint8Array,
cost: { readonly N: number; readonly r: number; readonly p: number },
keyLength: number,
): Uint8Array {
const options: ScryptOptions = { salt, ...cost, keyLength, encoding: "binary" };
const { digest } = create("scrypt").hash(password, options);
if (!(digest instanceof Uint8Array)) throw new TypeError("scrypt returned text, not bytes");
return digest;
}

/**
* XOR of two byte arrays, as long as the first.
* @param left - First bytes
Expand All @@ -210,32 +196,28 @@ function xor(left: Uint8Array, right: Uint8Array): Uint8Array {
* @returns {Uint8Array} 32 key bytes
*/
function decryptNonEc(payload: Uint8Array, passphrase: Uint8Array): Uint8Array {
const derived = scrypt(passphrase, payload.slice(3, 7), { N: 16_384, r: 8, p: 8 }, 64);
const derived = scrypt(passphrase, payload.slice(3, 7), 16_384, 8, 8, 64);
const halves = ecb(payload.slice(7, 39), derived.slice(32), "decrypt");
return xor(halves, derived.slice(0, 32));
}

/**
* EC multiply key: the passfactor times `factorb`, the double SHA-256 of the hidden seed.
* @param payload - The 39 byte payload
* @param passphrase - NFC passphrase as UTF-8
* @param hasLotSequence - Flag bit 0x04
* @param secret - NFC passphrase as UTF-8, and flag bit 0x04 as `hasLotSequence`
* @returns {Uint8Array} 32 key bytes
*/
function decryptEcMultiply(
payload: Uint8Array,
passphrase: Uint8Array,
hasLotSequence: boolean,
): Uint8Array {
function decryptEcMultiply(payload: Uint8Array, secret: EcMultiplySecret): Uint8Array {
const { passphrase, hasLotSequence } = secret;
const ownerEntropy = payload.slice(7, 15);
const ownerSalt = hasLotSequence ? ownerEntropy.slice(0, 4) : ownerEntropy;
const prefactor = scrypt(passphrase, ownerSalt, { N: 16_384, r: 8, p: 8 }, 32);
const prefactor = scrypt(passphrase, ownerSalt, 16_384, 8, 8, 32);
const passfactor = hasLotSequence
? sha256(sha256(concatBytes(prefactor, ownerEntropy)))
: prefactor;
if (!secp256k1.utils.isValidSecretKey(passfactor)) throw new BIP38PassphraseError();
const passpoint = secp256k1.getPublicKey(passfactor, true);
const derived = scrypt(passpoint, payload.slice(3, 15), { N: 1024, r: 1, p: 1 }, 64);
const derived = scrypt(passpoint, payload.slice(3, 15), 1024, 1, 1, 64);
const key = derived.slice(32);
const part2 = xor(ecb(payload.slice(23, 39), key, "decrypt"), derived.slice(16, 32));
const part1 = xor(
Expand Down Expand Up @@ -265,7 +247,7 @@ export function decrypt(encrypted: string, passphrase: string): DecryptedBIP38 {
const privateKey =
mode === "non-ec"
? decryptNonEc(payload, password)
: decryptEcMultiply(payload, password, hasLotSequence);
: decryptEcMultiply(payload, { passphrase: password, hasLotSequence });
if (!secp256k1.utils.isValidSecretKey(privateKey)) throw new BIP38PassphraseError();
const publicKey = secp256k1.getPublicKey(privateKey, compressed).toHex();
const address = generateAddressLegacy(publicKey, { bytesVersion: 0x00 });
Expand Down
18 changes: 9 additions & 9 deletions src/utils/bitcoin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,31 +202,31 @@ export abstract class AbstractBitcoinMessageBlockchain extends AbstractBlockchai
*/
override signMessage(message: string | Uint8Array, options: SignMessageOptions): string {
assertSignOptions(options);
const { privateKey, ...signingOptions } = options;
const { privateKey } = options;
const hash = this.hashWithMessagePreamble(message);
if (readRecoveredFlag(signingOptions)) {
return signCompact(hash, privateKey, signingOptions.compressed !== false);
if (readRecoveredFlag(options)) {
return signCompact(hash, { privateKey, compressed: options.compressed !== false });
}
return genericSignMessage(hash, privateKey, {
...signingOptions,
return genericSignMessage(hash, {
...options,
curve: "secp256k1",
hash: false,
});
}

override verifyMessage(message: string | Uint8Array, options: VerifyMessageOptions): boolean {
assertVerifyOptions(options);
const { signature, publicKey, ...signingOptions } = options;
const { signature } = options;
if (hasRecoveryByte(signature)) {
return false;
}
const hash = this.hashWithMessagePreamble(message);
if (isCompactSignature(signature)) {
return verifyCompact(hash, signature, publicKey);
return verifyCompact(hash, options);
}
try {
return genericVerifyMessage(hash, signature, publicKey, {
...signingOptions,
return genericVerifyMessage(hash, {
...options,
curve: "secp256k1",
hash: false,
});
Expand Down
47 changes: 11 additions & 36 deletions src/utils/brainwallet/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
import {
Sha256Hasher,
Sha512Hasher,
create,
keccak256,
pbkdf2,
sha256,
type ScryptOptions,
} from "@agntn/hashes";
import { Sha256Hasher, Sha512Hasher, keccak256, pbkdf2, scrypt, sha256 } from "@agntn/hashes";
import { concatBytes } from "../bytes.ts";

/** Key derivation a salted brainwallet runs the passphrase through, with its cost parameters. */
Expand Down Expand Up @@ -70,38 +62,20 @@ function digestRounds(password: Uint8Array, options: PlainBrainwalletOptions): U
/**
* Runs the KDF the recipe names over the passphrase bytes.
* @param password - Passphrase as UTF-8 bytes
* @param salt - Salt bytes
* @param options - KDF, cost parameters and output length
* @param options - KDF, cost parameters and output length, the salt already as bytes
* @returns {Uint8Array} The KDF output
*/
function stretch(password: Uint8Array, salt: Uint8Array, options: BrainwalletOptions): Uint8Array {
function stretch(
password: Uint8Array,
options: BrainwalletOptions & { readonly salt: Uint8Array },
): Uint8Array {
const { salt } = options;
const keyLength = options.keyLength ?? 32;
if (options.kdf === "pbkdf2") {
const hasher = options.digest === "sha512" ? Sha512Hasher : Sha256Hasher;
return pbkdf2(() => new hasher(), password, salt, options.iterations, keyLength);
}
return scrypt(password, salt, options, keyLength);
}

/**
* Runs scrypt over the passphrase bytes.
* @param password - Passphrase bytes
* @param salt - Salt bytes
* @param cost - N, r and p
* @param keyLength - Output length in bytes
* @returns {Uint8Array} The scrypt output
*/
function scrypt(
password: Uint8Array,
salt: Uint8Array,
cost: { readonly N: number; readonly r: number; readonly p: number },
keyLength: number,
): Uint8Array {
const { N, r, p } = cost;
const options: ScryptOptions = { salt, N, r, p, keyLength, encoding: "binary" };
const { digest } = create("scrypt").hash(password, options);
if (!(digest instanceof Uint8Array)) throw new TypeError("scrypt returned text, not bytes");
return digest;
return scrypt(password, salt, options.N, options.r, options.p, keyLength);
}

/**
Expand All @@ -112,7 +86,8 @@ function scrypt(
*/
function warp(password: Uint8Array, salt: Uint8Array): Uint8Array {
const tagged = (bytes: Uint8Array, tag: number) => concatBytes(bytes, Uint8Array.of(tag));
const s1 = scrypt(tagged(password, 1), tagged(salt, 1), WARP_SCRYPT, 32);
const { N, r, p } = WARP_SCRYPT;
const s1 = scrypt(tagged(password, 1), tagged(salt, 1), N, r, p, 32);
const s2 = pbkdf2(
() => new Sha256Hasher(),
tagged(password, 2),
Expand Down Expand Up @@ -144,6 +119,6 @@ export function derive(passphrase: string, options: BrainwalletRecipe): Uint8Arr
}
const salt = typeof options.salt === "string" ? encoder.encode(options.salt) : options.salt;
if (options.kdf === "warpwallet") return warp(encoder.encode(passphrase), salt);
const stretched = stretch(encoder.encode(passphrase), salt, options);
const stretched = stretch(encoder.encode(passphrase), { ...options, salt });
return sha256(options.hashed === "hex" ? encoder.encode(stretched.toHex()) : stretched);
}
Loading
Loading
0