-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathbip47.ts
338 lines (276 loc) · 10.4 KB
/
bip47.ts
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import BIP32Factory, { BIP32API, BIP32Interface } from 'bip32';
import * as bitcoin from 'bitcoinjs-lib';
import * as crypto from './crypto';
import { xor } from './xor';
import {
BIP47API,
BIP47Interface,
NetworkCoin,
PublicKeyOutpoint,
TinySecp256k1Interface,
} from './interfaces';
import { mainnetData } from './networks';
import getUtils from './utils';
const bs58check = require('bs58check');
export function BIP47Factory(ecc: TinySecp256k1Interface): BIP47API {
// TODO: implement a test assertion function for ecc
const bip32: BIP32API = BIP32Factory(ecc);
const G: Buffer = Buffer.from(
'0279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798',
'hex',
);
const {
getPublicPaymentCodeNodeFromBase58,
getRootPaymentCodeNodeFromSeedHex,
getRootPaymentCodeNodeFromBIP39Seed,
uintArrayToBuffer,
getSharedSecret,
toInternalByteOrder,
} = getUtils(ecc, bip32);
class BIP47 implements BIP47Interface {
network: NetworkCoin;
RootPaymentCodeNode: BIP32Interface;
constructor(network: NetworkCoin, RootPaymentCodeNode: BIP32Interface) {
this.network = network;
this.RootPaymentCodeNode = RootPaymentCodeNode;
}
getPaymentWallet(aliceNode: BIP32Interface, index: number): BIP32Interface {
if (!this.network || !this.RootPaymentCodeNode)
throw new Error('Root Payment code node or network not set');
const bobNode: BIP32Interface = this.RootPaymentCodeNode.derive(index);
if (bobNode.privateKey === undefined)
throw new Error('Missing private key to generate payment wallets');
const firstAliceNode: BIP32Interface = aliceNode.derive(0);
const s: Buffer = getSharedSecret(
firstAliceNode.publicKey,
bobNode.privateKey,
);
const prvKeyUint8: Uint8Array | null = ecc.privateAdd(
bobNode.privateKey,
s,
);
if (prvKeyUint8 === null)
throw new Error('Could not calculate private key');
const prvKey: Buffer = uintArrayToBuffer(prvKeyUint8);
return bip32.fromPrivateKey(
prvKey,
bobNode.chainCode,
this.network.network,
);
}
getReceiveWallet(bobNode: BIP32Interface, index: number): BIP32Interface {
if (!this.network || !this.RootPaymentCodeNode)
throw new Error('Root Payment code node or network not set');
const aliceNode = this.RootPaymentCodeNode.derive(0);
bobNode = bobNode.derive(index);
if (aliceNode.privateKey === undefined)
throw new Error('Missing private key to generate receive wallets');
const s = getSharedSecret(bobNode.publicKey, aliceNode.privateKey);
const sG = ecc.pointMultiply(G, s, true);
if (sG === null) throw new Error('Could not calculate private key');
const pubKeyUint8 = ecc.pointAdd(bobNode.publicKey, sG);
if (pubKeyUint8 === null) throw new Error('Could not sum pub keys');
const pubKey = uintArrayToBuffer(pubKeyUint8);
return bip32.fromPublicKey(
pubKey,
bobNode.chainCode,
this.network.network,
);
}
getPaymentCodeNode(): BIP32Interface {
return this.RootPaymentCodeNode as BIP32Interface;
}
getPaymentAddress(
bobsRootPaymentCodeNode: BIP32Interface,
index: number,
): string {
if (!this.network || !this.RootPaymentCodeNode)
throw new Error('Root Payment code or network not set');
const firstAlicePaymentCodeNode: BIP32Interface =
this.RootPaymentCodeNode.derive(0);
const bobPaymentCodeNode: BIP32Interface =
bobsRootPaymentCodeNode.derive(index);
if (firstAlicePaymentCodeNode.privateKey === undefined)
throw new Error('Missing private key to generate payment address');
const a: Buffer = firstAlicePaymentCodeNode.privateKey;
const B: Buffer = bobPaymentCodeNode.publicKey;
const s = getSharedSecret(B, a);
const sGUint: Uint8Array | null = ecc.pointMultiply(G, s, true);
if (sGUint === null) throw new Error('Could not compute sG');
const sG: Buffer = uintArrayToBuffer(sGUint);
const BPrimeUint: Uint8Array | null = ecc.pointAdd(B, sG, true);
if (BPrimeUint === null) throw new Error('Could not calculate pubkey');
const BPrime: Buffer = uintArrayToBuffer(BPrimeUint);
if (!ecc.isPoint(BPrime)) throw new Error('Calculate Pubkey is invalid');
const node: BIP32Interface = bip32.fromPublicKey(
BPrime,
bobPaymentCodeNode.chainCode,
this.network.network,
);
return this.getAddressFromNode(node);
}
getSerializedPaymentCode(): string {
return bs58check.encode(
Buffer.concat([Buffer.from([71]), this.getBinaryPaymentCode()]),
);
}
getBinaryPaymentCode(): Buffer {
if (!this.network || !this.RootPaymentCodeNode)
throw new Error('Root Payment code or network not set');
const node = this.RootPaymentCodeNode;
const paymentCodeSerializedBuffer: Buffer = Buffer.alloc(80);
paymentCodeSerializedBuffer[0] = 0x01; // version
paymentCodeSerializedBuffer[1] = 0x00; // must be zero
paymentCodeSerializedBuffer[2] = node.publicKey[0]; // sign 2 or 3
paymentCodeSerializedBuffer.fill(node.publicKey.slice(1), 3, 35); // pubkey
paymentCodeSerializedBuffer.fill(node.chainCode, 35, 67); // chain code
return paymentCodeSerializedBuffer;
}
getNotificationNode(): BIP32Interface {
if (!this.network || !this.RootPaymentCodeNode)
throw new Error('Root Payment code or network not set');
return this.RootPaymentCodeNode.derive(0);
}
getNotificationNodeFromPaymentCode(paymentCode: string): BIP32Interface {
if (!this.network || !this.RootPaymentCodeNode)
throw new Error('Root Payment code or network not set');
return getPublicPaymentCodeNodeFromBase58(paymentCode, this.network);
}
getNotificationAddressFromPaymentCode(paymentCode: string): string {
return this.getAddressFromNode(
this.getNotificationNodeFromPaymentCode(paymentCode),
);
}
getNotificationAddress(): string {
return this.getAddressFromNode(this.getNotificationNode());
}
getAddressFromNode(node: BIP32Interface, network = this.network): string {
return bitcoin.payments.p2pkh({
pubkey: node.publicKey,
network: network?.network,
}).address!;
}
getBlindedPaymentCode(
bobBIP47: BIP47,
privateKey: string | Buffer,
outpoint: string | Buffer,
): string {
if (!this.network || !this.RootPaymentCodeNode)
throw new Error('Root Payment code or network not set');
if (typeof privateKey === 'string')
privateKey = Buffer.from(privateKey, 'hex');
if (typeof outpoint === 'string') outpoint = Buffer.from(outpoint, 'hex');
const a: Buffer = privateKey;
const B: Buffer = bobBIP47.getNotificationNode().publicKey;
const S: Buffer = uintArrayToBuffer(ecc.pointMultiply(B, a) as Buffer);
const x: Buffer = uintArrayToBuffer(S.slice(1, 33));
const o: Buffer = outpoint;
const s = crypto.hmacSHA512(o, x);
const binaryPaymentCode: Buffer = this.getBinaryPaymentCode();
binaryPaymentCode.fill(
xor(s.slice(0, 32), binaryPaymentCode.slice(3, 35)),
3,
35,
);
binaryPaymentCode.fill(
xor(s.slice(32, 64), binaryPaymentCode.slice(35, 67)),
35,
67,
);
return binaryPaymentCode.toString('hex');
}
getFirstExposedPubKeyAndOutpoint(
tx: bitcoin.Transaction,
): PublicKeyOutpoint {
const first: bitcoin.TxInput = tx.ins[0];
const hash: Buffer = first.hash;
const index: number = first.index;
const indexHex = this.getInternalByteOrderHex(index);
const outpoint = Buffer.from(hash.toString('hex') + indexHex, 'hex');
let pubKey: Buffer | null = null;
if (first.witness.length) pubKey = first.witness[1];
else if (bitcoin.script.toASM(first.script).split(' ').length === 2)
pubKey = Buffer.from(
bitcoin.script.toASM(first.script).split(' ')[1],
'hex',
);
else throw new Error('Unknown Transaction type');
return {
outpoint,
pubKey,
};
}
private getInternalByteOrderHex(index: number) {
const tmpIndex = index.toString(16).padStart(8, '0');
const indexBuffer = toInternalByteOrder(Buffer.from(tmpIndex, 'hex'));
const indexHex = indexBuffer.toString('hex');
return indexHex;
}
getPaymentCodeFromRawNotificationTransaction(
rawHexNotificationData: string,
) {
const tx: bitcoin.Transaction = bitcoin.Transaction.fromHex(
rawHexNotificationData,
);
// tslint:disable-next-line:prefer-const
let { pubKey, outpoint } = this.getFirstExposedPubKeyAndOutpoint(tx);
const A: Buffer = pubKey;
const b: Buffer = this.getNotificationNode().privateKey as Buffer;
const S: Buffer = uintArrayToBuffer(ecc.pointMultiply(A, b) as Buffer);
const x: Buffer = uintArrayToBuffer(S.slice(1, 33));
const s = crypto.hmacSHA512(outpoint, x);
const opReturnOutput = tx.outs.find((o) =>
o.script.toString('hex').startsWith('6a4c50'),
);
if (!opReturnOutput)
throw new Error('No OP_RETURN output in notification');
const binaryPaymentCode: Buffer = opReturnOutput.script.slice(3);
binaryPaymentCode.fill(
xor(s.slice(0, 32), binaryPaymentCode.slice(3, 35)),
3,
35,
);
binaryPaymentCode.fill(
xor(s.slice(32, 64), binaryPaymentCode.slice(35, 67)),
35,
67,
);
return bs58check.encode(
Buffer.concat([Buffer.from([71]), binaryPaymentCode]),
);
}
}
function fromPaymentCode(
paymentCode: string,
network: NetworkCoin = mainnetData,
): BIP47Interface {
return new BIP47(
network,
getPublicPaymentCodeNodeFromBase58(paymentCode, network),
);
}
function fromBip39Seed(
bip39Seed: string,
network: NetworkCoin = mainnetData,
password?: string,
): BIP47Interface {
return new BIP47(
network,
getRootPaymentCodeNodeFromBIP39Seed(bip39Seed, network, password),
);
}
function fromSeedHex(
seedHex: string | Buffer,
network: NetworkCoin = mainnetData,
): BIP47Interface {
return new BIP47(
network,
getRootPaymentCodeNodeFromSeedHex(seedHex, network),
);
}
return {
fromSeedHex,
fromBip39Seed,
fromPaymentCode,
};
}