paulmillr / noble-secp256k1

Fastest 4KB JS implementation of secp256k1 signatures and ECDH
https://paulmillr.com/noble
MIT License
757 stars 114 forks source link

feature detect to avoid self.crypto if subtle isn't available #123

Closed gre closed 2 months ago

gre commented 2 months ago

In context of React Native environment, some polyfill exists like react-native-get-random-values that implements global.crypto.getRandomValues function but do not provide a crypto.subtle implementation. ( example of lib that recommend this polyfill https://docs.ethers.org/v5/cookbook/react-native/#cookbook-reactnative )

Since @noble/secp256k1 requires an implementation of crypto.subtle to be able to do things like crypto.web.subtle.digest('SHA-256', concatBytes(...messages)) it is necessary for the feature detection to consider the extra case where crypto.web.subtle might not be available.

Without this fix, you get TypeError: Cannot read property 'digest' of undefined as soon as you start using .util.sha256 function

paulmillr commented 2 months ago

It's necessary to edit index.ts instead.

gre commented 2 months ago

I have modified index.ts instead.

when trying to run the test I get

noble-secp256k1 on  fix/subtle-in-crypto-feature-detect [!] is  v2.1.0 via 🦕 via  v18.20.2 took 2s
❯ npm test

> @noble/secp256k1@2.1.0 test
> node test/index.test.js

(node:40512) ExperimentalWarning: Importing JSON modules is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
secp256k1
├─.getPublicKey() type check: ☆
│ .getPublicKey() type check: ✓
├─.verify() should verify random signatures: ☆
│ .verify() should verify random signatures: ☓
file:///Users/grenaudeau/dev/noble-secp256k1/node_modules/fast-check/lib/esm/check/runner/utils/RunDetailsFormatter.js:123
    throw new Error(defaultReportMessage(out));

but it's also the case on the main branch. is that known? thanks

paulmillr commented 2 months ago

CI doesn't have any errors on main branch. Neither does my machine. You will need to provide reproducible way to get errors.

gre commented 2 months ago

ok, then it's probably independent of this PR changes 👍

paulmillr commented 2 months ago

please also copy it to noble-ed25519