All files / src/transactions keys.ts

84.78% Statements 78/92
65.38% Branches 17/26
94.11% Functions 16/17
84.26% Lines 75/89

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 20512x   12x   53x   12x                       12x         12x             12x 268x           12x           15x 15x   15x 15x     12x 8x     12x 193x     12x 139x 139x     12x 106x 106x 106x 97x           97x   106x     12x 43x 43x 43x     12x 104x 104x 104x 104x     12x 2x   2x     12x 8x   8x 8x                   12x 162x   162x 148x           148x 14x 14x           162x     12x 1x     12x       53x                     53x 53x 53x   53x     53x 53x 53x     12x                 12x 15x 15x     15x 15x 15x 15x 15x                               12x 72x     12x 1x    
import { PubKeyEncoding } from './common/constants';
 
import { leftPadHexToLength } from './common/utils';
 
import { getPublicKey as nobleGetPublicKey, utils, Point, Signature, sign } from '@noble/secp256k1';
 
import { MessageSignature, createMessageSignature } from './authorization';
 
import {
  BufferArray,
  BufferReader,
  bytesToHex,
  hexToBigInt,
  hexToBytes,
  intToHex,
  concatByteArrays,
  intToHexString,
  hexStringToInt,
} from 'micro-stacks/common';
import {
  COMPRESSED_PUBKEY_LENGTH_BYTES,
  StacksMessageType,
  UNCOMPRESSED_PUBKEY_LENGTH_BYTES,
} from 'micro-stacks/clarity';
 
export interface StacksPublicKey {
  readonly type: StacksMessageType.PublicKey;
  readonly data: Uint8Array;
}
 
export function createStacksPublicKey(key: string): StacksPublicKey {
  return {
    type: StacksMessageType.PublicKey,
    data: hexToBytes(key),
  };
}
 
export function publicKeyFromSignature(
  message: string,
  messageSignature: MessageSignature,
  pubKeyEncoding = PubKeyEncoding.Compressed,
  mode = 'vrs' as 'vrs' | 'rsv'
): string {
  const parsedSignature = parseRecoverableSignature(messageSignature.data, mode);
  const signature = new Signature(hexToBigInt(parsedSignature.r), hexToBigInt(parsedSignature.s));
  const point = Point.fromSignature(message, signature, parsedSignature.recoveryParam);
  const isCompressed = pubKeyEncoding === PubKeyEncoding.Compressed;
  return point.toHex(isCompressed);
}
 
export function publicKeyFromBuffer(data: Uint8Array): StacksPublicKey {
  return { type: StacksMessageType.PublicKey, data };
}
 
export function publicKeyToString(key: StacksPublicKey): string {
  return bytesToHex(key.data);
}
 
export function isCompressed(key: StacksPublicKey): boolean {
  const hex = publicKeyToString(key);
  return !hex.startsWith('04');
}
 
export function isPrivateKeyCompressed(key: string | Uint8Array) {
  const data = typeof key === 'string' ? hexToBytes(key) : key;
  let compressed = false;
  if (data.length === 33) {
    Iif (data[data.length - 1] !== 1) {
      throw new Error(
        'Improperly formatted private-key. 33 byte length usually ' +
          'indicates compressed key, but last byte must be == 0x01'
      );
    }
    compressed = true;
  }
  return compressed;
}
 
export function serializePublicKey(key: StacksPublicKey): Uint8Array {
  const bufferArray: BufferArray = new BufferArray();
  bufferArray.push(key.data);
  return bufferArray.concatBuffer();
}
 
export function pubKeyfromPrivKey(privateKey: string | Uint8Array): StacksPublicKey {
  const privKey = createStacksPrivateKey(privateKey);
  const isCompressed = isPrivateKeyCompressed(privateKey);
  const pubKey = nobleGetPublicKey(privKey.data.slice(0, 32), isCompressed || privKey.compressed);
  return createStacksPublicKey(bytesToHex(pubKey));
}
 
export function compressPublicKey(publicKey: string | Uint8Array): StacksPublicKey {
  const hex = typeof publicKey === 'string' ? publicKey : bytesToHex(publicKey);
  const compressed = Point.fromHex(hex).toHex(true);
  return createStacksPublicKey(compressed);
}
 
export function deserializePublicKey(bufferReader: BufferReader): StacksPublicKey {
  const fieldId = bufferReader.readUInt8();
  const keyLength =
    fieldId !== 4 ? COMPRESSED_PUBKEY_LENGTH_BYTES : UNCOMPRESSED_PUBKEY_LENGTH_BYTES;
  return publicKeyFromBuffer(
    concatByteArrays([Uint8Array.from([fieldId]), bufferReader.readBuffer(keyLength)])
  );
}
 
export interface StacksPrivateKey {
  data: Uint8Array;
  compressed: boolean;
}
 
export function createStacksPrivateKey(key: string | Uint8Array): StacksPrivateKey {
  const data = typeof key === 'string' ? hexToBytes(key) : key;
  let compressed: boolean;
  if (data.length === 33) {
    Iif (data[data.length - 1] !== 1) {
      throw new Error(
        'Improperly formatted private-key. 33 byte length usually ' +
          'indicates compressed key, but last byte must be == 0x01'
      );
    }
    compressed = true;
  } else if (data.length === 32) {
    compressed = false;
  } else E{
    throw new Error(
      `Improperly formatted private-key hex string: length should be 32 or 33 bytes, provided with length ${data.length}`
    );
  }
  return { data, compressed };
}
 
export function makeRandomPrivKey(): StacksPrivateKey {
  return createStacksPrivateKey(utils.randomPrivateKey());
}
 
export async function signWithKey(
  privateKey: StacksPrivateKey,
  input: string
): Promise<MessageSignature> {
  const [rawSignature, recoveryParam] = await sign(input, privateKey.data.slice(0, 32), {
    canonical: true,
    recovered: true,
    // https://github.com/paulmillr/noble-secp256k1#signmsghash-privatekey
    // additional entropy k' for deterministic signature, follows section 3.6 of RFC6979. When true, it would automatically be filled with 32 bytes of cryptographically secure entropy
    // TODO: how can we make this default true?
    // extraEntropy: false,
  });
 
  const signature = Signature.fromHex(rawSignature);
 
  const coordinateValueBytes = 32;
  const r = leftPadHexToLength(intToHex(signature.r), coordinateValueBytes * 2);
  const s = leftPadHexToLength(intToHex(signature.s), coordinateValueBytes * 2);
 
  Iif (recoveryParam === undefined || recoveryParam === null) {
    throw new Error('"signature.recoveryParam" is not set');
  }
  const recoveryParamHex = intToHexString(recoveryParam, 1);
  const recoverableSignatureString = recoveryParamHex + r + s;
  return createMessageSignature(recoverableSignatureString);
}
 
export function getSignatureRecoveryParam(signature: string) {
  const coordinateValueBytes = 32;
  Iif (signature.length < coordinateValueBytes * 2 * 2 + 1) {
    throw new Error('Invalid signature');
  }
  const recoveryParamHex = signature.substr(0, 2);
  return hexStringToInt(recoveryParamHex);
}
 
export function parseRecoverableSignature(signature: string, mode = 'vrs' as 'vrs' | 'rsv') {
  const coordinateValueBytes = 32;
  Iif (signature.length < coordinateValueBytes * 2 * 2 + 1) {
    throw new Error('Invalid signature');
  }
  if (mode === 'vrs') {
    const recoveryParamHex = signature.substr(0, 2);
    const r = signature.substr(2, coordinateValueBytes * 2);
    const s = signature.substr(2 + coordinateValueBytes * 2, coordinateValueBytes * 2);
    return {
      recoveryParam: hexStringToInt(recoveryParamHex),
      r,
      s,
    };
  }
  const r = signature.substr(0, coordinateValueBytes * 2);
  const s = signature.substr(coordinateValueBytes * 2, coordinateValueBytes * 2);
  const recoveryParamHex = signature.substr(coordinateValueBytes * 2 * 2, 2);
  return {
    r,
    s,
    recoveryParam: hexStringToInt(recoveryParamHex),
  };
}
 
export function getPublicKeyFromStacksPrivateKey(privateKey: StacksPrivateKey): StacksPublicKey {
  return pubKeyfromPrivKey(privateKey.data);
}
 
export function privateKeyToString(privateKey: StacksPrivateKey): string {
  return bytesToHex(privateKey.data);
}