Skip to content

Commit

Permalink
feat: remove hashOutpoint and update createOutput method to match BIP352
Browse files Browse the repository at this point in the history
Signed-off-by: Anmol Sharma <anmolsharma0234@gmail.com>
  • Loading branch information
theanmolsharma committed Mar 3, 2024
1 parent 04af65e commit 291c291
Show file tree
Hide file tree
Showing 7 changed files with 382 additions and 361 deletions.
20 changes: 12 additions & 8 deletions packages/core/src/outputs.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
import { Outpoint, Output, PrivateKey, RecipientAddress } from './interface.ts';
import {
calculateSumOfPrivateKeys,
hashOutpoints,
createInputHash,
createTaggedHash,
serialiseUint32,
} from './utility.ts';
import { decodeSilentPaymentAddress } from './encoding.ts';
import secp256k1 from 'secp256k1';
import createHash from 'create-hash';
import { Buffer } from 'buffer';
import { bitcoin } from 'bitcoinjs-lib/src/networks';
import { Network } from 'bitcoinjs-lib';

export const createOutputs = (
inputPrivateKeys: PrivateKey[],
outpoints: Outpoint[],
smallestOutpoint: Outpoint,
recipientAddresses: RecipientAddress[],
network: Network = bitcoin,
): Output[] => {
const sumOfPrivateKeys = calculateSumOfPrivateKeys(inputPrivateKeys);
const outpointHash = hashOutpoints(outpoints);
const inputHash = createInputHash(
Buffer.from(secp256k1.publicKeyCreate(sumOfPrivateKeys)),
smallestOutpoint,
);

const paymentGroups = new Map<
string,
Expand All @@ -43,15 +46,16 @@ export const createOutputs = (
for (const [scanKeyHex, paymentGroup] of paymentGroups.entries()) {
const scanKey = Buffer.from(scanKeyHex, 'hex');
const ecdhSecret = secp256k1.publicKeyTweakMul(
secp256k1.publicKeyTweakMul(scanKey, outpointHash, true),
secp256k1.publicKeyTweakMul(scanKey, inputHash, true),
sumOfPrivateKeys,
);

let n = 0;
for (const { spendKey, amount } of paymentGroup) {
const tweak = createHash('sha256')
.update(Buffer.concat([ecdhSecret, serialiseUint32(n)]))
.digest();
const tweak = createTaggedHash(
'BIP0352/SharedSecret',
Buffer.concat([Buffer.from(ecdhSecret), serialiseUint32(n)]),
);

const publicKey = secp256k1.publicKeyTweakAdd(
spendKey,
Expand Down
15 changes: 0 additions & 15 deletions packages/core/src/utility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,6 @@ import secp256k1 from 'secp256k1';
import createHash from 'create-hash';
import { Buffer } from 'buffer';

export const hashOutpoints = (outpoints: Outpoint[]): Buffer => {
const outpointBuffer = Buffer.concat(
outpoints
.map((outpoint) =>
Buffer.concat([
Buffer.from(outpoint.txid, 'hex').reverse(),
serialiseUint32LE(outpoint.vout),
]),
)
.sort((a, b) => a.compare(b)),
);

return createHash('sha256').update(outpointBuffer).digest();
};

export const createInputHash = (
sumOfInputPublicKeys: Buffer,
outpoint: Outpoint,
Expand Down
Loading

0 comments on commit 291c291

Please sign in to comment.