import { encodeArrayBuffer , decodeArrayBuffer , concatArrayBuffer } from '@dimensiondev/kit' ; import type { EC_JsonWebKey , EC_Public_JsonWebKey } from './JWKType' ; import { fromBase64URL , toBase64URL } from '../convert' ; import { ECKeyIdentifier } from '../Identifier/type' ; import type { EC_CryptoKey } from '.' ; let secp256k1 ! ; const isContentScript = ( ( ) => { try { if ( location . protocol . startsWith ( 'http' ) ) return true ; } catch { } return false ; } ) ( ) ; if ( ! isContentScript ) { if ( process . env . architecture === 'app' ) { WebAssembly . instantiateStreaming = undefined ! ; WebAssembly . compileStreaming = undefined ! ; } import ( 'tiny-secp256k1' ) . then ( ( mod ) => ( secp256k1 = mod ) ) ; } /**
 * Compress x & y into a single x
 */ export function compressSecp256k1Point ( x , y ) { const xb = fromBase64URL ( x ) ; const yb = fromBase64URL ( y ) ; const point = new Uint8Array ( concatArrayBuffer ( new Uint8Array ( [ 0x04 ] ) , xb , yb ) ) ; if ( secp256k1 . isPoint ( point ) ) { return secp256k1 . pointCompress ( point , true ) ; } else { throw new TypeError ( 'Not a point on secp256k1!' ) ; } } /**
 * Decompress x into x & y
 */ export function decompressSecp256k1Point ( point ) { if ( ! secp256k1 . isPoint ( point ) ) throw new TypeError ( 'Not a point on secp256k1!' ) ; const uncompressed = secp256k1 . isPointCompressed ( point ) ? secp256k1 . pointCompress ( point , false ) : point ; const len = ( uncompressed . length - 1 ) / 2 ; const x = uncompressed . slice ( 1 , len + 1 ) ; const y = uncompressed . slice ( len + 1 ) ; return { x : toBase64URL ( x ) , y : toBase64URL ( y ) } ; } export function compressSecp256k1Key ( key ) { const arr = compressSecp256k1Point ( key . x ! , key . y ! ) ; return encodeArrayBuffer ( arr ) ; } export function decompressSecp256k1Key ( compressedPublic ) { const arr = decodeArrayBuffer ( compressedPublic ) ; const key = decompressSecp256k1Point ( new Uint8Array ( arr ) ) ; const jwk = { crv : 'K-256' , ext : true , x : key . x , y : key . y , key_ops : [ 'deriveKey' , 'deriveBits' ] , kty : 'EC' , } ; return jwk as EC_Public_JsonWebKey ; } export function isSecp256k1Point ( x ) { return secp256k1 . isPoint ( x ) ; } export function isSecp256k1PrivateKey ( d ) { return secp256k1 . isPrivate ( d ) ; } export function ECKeyIdentifierFromJsonWebKey ( key ) { const x = compressSecp256k1Key ( key ) ; return new ECKeyIdentifier ( 'secp256k1' , x ) ; } export async function ECKeyIdentifierFromCryptoKey ( key ) { const k = ( await crypto . subtle . exportKey ( 'jwk' , key ) ) as EC_JsonWebKey ; return ECKeyIdentifierFromJsonWebKey ( k ) ; }