paulmillr / noble-secp256k1

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

[doc] privateKeyTweakAdd and publicKeyTweakAdd for HD Wallets #95

Closed coolaj86 closed 1 year ago

coolaj86 commented 1 year ago

I'm just documenting this for the sake of anyone else that's updating their HD Wallet libraries: \ (see also #73)

The HD Wallet key functions are in the test files, no the main package.

  let tweakUtils = {
    /**
     * @param {Uint8Array} privateKey
     * @param {Uint8Array} tweak
     * @returns {Uint8Array} - a new (derivative) privateKey
     */
    privateAdd: function (privateKey, tweak) {
      const p = Secp256k1.utils._normalizePrivateKey(privateKey);
      const t = Secp256k1.utils._normalizePrivateKey(tweak);
      return Secp256k1.utils._bigintTo32Bytes(
        Secp256k1.utils.mod(p + t, Secp256k1.CURVE.n),
      );
    },

    /**
     * @param {Uint8Array} p
     * @param {Uint8Array} tweak
     * @param {Boolean} [isCompressed]
     * @returns {Uint8Array} - a new (derivative) publicKey
     */
    pointAddScalar: function (p, tweak, isCompressed) {
      const P = Secp256k1.Point.fromHex(p);
      const t = Secp256k1.utils._normalizePrivateKey(tweak);
      const Q = Secp256k1.Point.BASE.multiplyAndAddUnsafe(P, t, 1n);
      if (!Q) {
        throw new Error("Tweaked point at infinity");
      }
      return Q.toRawBytes(isCompressed);
    },
  };

Adapted from ./test/index.ts:

https://github.com/paulmillr/noble-secp256k1/blob/e125abdd2f42b2ad4cf5f4a1b7927d7737b7becf/test/index.ts#L466-L492

This may need to be updated again for the upcoming major refactor.

paulmillr commented 1 year ago

should be updated for v2 now

headfire94 commented 1 year ago

@paulmillr is this solved? I can't find these methods in lib

paulmillr commented 1 year ago

@headfire94 there are no plans to implement these methods because they look terrible. Users should not even think about "tweaks": instead, there are points and scalars. I consider noble api much more concise. If you want to use these methods, you can implement them for v2 in your own fork.

Also there is no need in re-implementing HD wallet over and over, there's audited http://github.com/paulmillr/scure-bip32 and that's it. You don't need another one. You may need a different lib for different curve.