Repository navigation
Expand file tree
/
Copy pathsigning-serialization.ts
More file actions
528 lines (507 loc) · 16.6 KB
/
Copy pathsigning-serialization.ts
File metadata and controls
528 lines (507 loc) · 16.6 KB
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
import { hash256, sha256 as internalSha256 } from '../../../crypto/crypto.js';
import {
bigIntToCompactSize,
flattenBinArray,
numberToBinUint32LE,
valueSatoshisToBin,
} from '../../../format/format.js';
import type { CompilationContextBCH, Sha256 } from '../../../lib';
import {
encodeTokenPrefix,
encodeTransactionInputSequenceNumbersForSigning,
encodeTransactionOutpoints,
encodeTransactionOutput,
encodeTransactionOutputsForSigning,
} from '../../../message/message.js';
/**
* A.K.A. `sighash` flags
*/
export enum SigningSerializationFlag {
/**
* A.K.A. `SIGHASH_ALL`
*/
allOutputs = 0x01,
/**
* A.K.A `SIGHASH_NONE`
*/
noOutputs = 0x02,
/**
* A.K.A. `SIGHASH_SINGLE`
*/
correspondingOutput = 0x03,
/**
* A.K.A. `SIGHASH_UTXOS`
*/
utxos = 0x20,
forkId = 0x40,
/**
* A.K.A `ANYONE_CAN_PAY`/`SIGHASH_ANYONECANPAY`
*/
singleInput = 0x80,
}
/* eslint-disable no-bitwise, @typescript-eslint/prefer-literal-enum-member */
export enum SigningSerializationType {
allOutputs = SigningSerializationFlag.allOutputs |
SigningSerializationFlag.forkId,
allOutputsAllUtxos = SigningSerializationFlag.allOutputs |
SigningSerializationFlag.utxos |
SigningSerializationFlag.forkId,
allOutputsSingleInput = SigningSerializationFlag.allOutputs |
SigningSerializationFlag.singleInput |
SigningSerializationFlag.forkId,
correspondingOutput = SigningSerializationFlag.correspondingOutput |
SigningSerializationFlag.forkId,
correspondingOutputAllUtxos = SigningSerializationFlag.correspondingOutput |
SigningSerializationFlag.utxos |
SigningSerializationFlag.forkId,
correspondingOutputSingleInput = SigningSerializationFlag.correspondingOutput |
SigningSerializationFlag.singleInput |
SigningSerializationFlag.forkId,
noOutputs = SigningSerializationFlag.noOutputs |
SigningSerializationFlag.forkId,
noOutputsAllUtxos = SigningSerializationFlag.noOutputs |
SigningSerializationFlag.utxos |
SigningSerializationFlag.forkId,
noOutputsSingleInput = SigningSerializationFlag.noOutputs |
SigningSerializationFlag.singleInput |
SigningSerializationFlag.forkId,
}
/* eslint-enable no-bitwise, @typescript-eslint/prefer-literal-enum-member */
// eslint-disable-next-line @typescript-eslint/naming-convention
export const SigningSerializationTypeBCH = SigningSerializationType;
const enum Internal {
mask5Bits = 0b11111,
sha256HashByteLength = 32,
}
const match = (type: Uint8Array, flag: SigningSerializationFlag) =>
// eslint-disable-next-line no-bitwise, @typescript-eslint/no-non-null-assertion
(type[0]! & flag) !== 0;
const equals = (
type: Uint8Array,
flag: SigningSerializationFlag
// eslint-disable-next-line no-bitwise, @typescript-eslint/no-non-null-assertion
) => (type[0]! & Internal.mask5Bits) === flag;
const shouldSerializeSingleInput = (type: Uint8Array) =>
match(type, SigningSerializationFlag.singleInput);
const shouldSerializeCorrespondingOutput = (type: Uint8Array) =>
equals(type, SigningSerializationFlag.correspondingOutput);
const shouldSerializeNoOutputs = (type: Uint8Array) =>
equals(type, SigningSerializationFlag.noOutputs);
const shouldSerializeUtxos = (type: Uint8Array) =>
match(type, SigningSerializationFlag.utxos);
const emptyHash = () => new Uint8Array(Internal.sha256HashByteLength).fill(0);
/**
* Return the proper `hashPrevouts` value for a given a signing serialization
* type.
*/
export const hashPrevouts = (
{
signingSerializationType,
transactionOutpoints,
}: {
/**
* The signing serialization type to test
*/
signingSerializationType: Uint8Array;
/**
* See {@link generateSigningSerializationComponentsBCH}
*/
transactionOutpoints: Uint8Array;
},
sha256: { hash: Sha256['hash'] } = internalSha256
) =>
shouldSerializeSingleInput(signingSerializationType)
? emptyHash()
: hash256(transactionOutpoints, sha256);
/**
* Return the proper `hashUtxos` value for a given a signing serialization
* type.
*/
export const hashUtxos = (
{
signingSerializationType,
transactionUtxos,
}: {
/**
* The signing serialization type to test
*/
signingSerializationType: Uint8Array;
/**
* See {@link generateSigningSerializationComponentsBCH}
*/
transactionUtxos: Uint8Array;
},
sha256: { hash: Sha256['hash'] } = internalSha256
) =>
shouldSerializeUtxos(signingSerializationType)
? hash256(transactionUtxos, sha256)
: Uint8Array.of();
/**
* Return the proper `hashSequence` value for a given a signing serialization
* type.
*/
export const hashSequence = (
{
signingSerializationType,
transactionSequenceNumbers,
}: {
/**
* The signing serialization type to test
*/
signingSerializationType: Uint8Array;
/**
* See {@link generateSigningSerializationComponentsBCH}
*/
transactionSequenceNumbers: Uint8Array;
},
sha256: { hash: Sha256['hash'] } = internalSha256
) =>
!shouldSerializeSingleInput(signingSerializationType) &&
!shouldSerializeCorrespondingOutput(signingSerializationType) &&
!shouldSerializeNoOutputs(signingSerializationType)
? hash256(transactionSequenceNumbers, sha256)
: emptyHash();
/**
* Return the proper `hashOutputs` value for a given a signing serialization
* type.
*/
export const hashOutputs = (
{
correspondingOutput,
signingSerializationType,
transactionOutputs,
}: {
/**
* The signing serialization type to test
*/
signingSerializationType: Uint8Array;
/**
* See {@link generateSigningSerializationComponentsBCH}
*/
transactionOutputs: Uint8Array;
/**
* See {@link generateSigningSerializationComponentsBCH}
*/
correspondingOutput: Uint8Array | undefined;
},
sha256: { hash: Sha256['hash'] } = internalSha256
) =>
!shouldSerializeCorrespondingOutput(signingSerializationType) &&
!shouldSerializeNoOutputs(signingSerializationType)
? hash256(transactionOutputs, sha256)
: shouldSerializeCorrespondingOutput(signingSerializationType)
? correspondingOutput === undefined
? emptyHash()
: hash256(correspondingOutput, sha256)
: emptyHash();
/**
* Encode the signature-protected properties of a transaction following the
* algorithm required by the `signingSerializationType` of a signature.
*
* Note: When validating transactions with multiple signatures,
* performance-critical applications should use a memoized sha256 implementation
* to avoid re-computing hashes.
*/
export const encodeSigningSerializationBCH = (
{
correspondingOutput,
coveredBytecode,
forkId = new Uint8Array([0, 0, 0]),
locktime,
outpointIndex,
outpointTransactionHash,
outputTokenPrefix,
outputValue,
sequenceNumber,
signingSerializationType,
transactionOutpoints,
transactionOutputs,
transactionSequenceNumbers,
transactionUtxos,
version,
}: {
/**
* The version number of the transaction.
*/
version: number;
/**
* The serialization of all input outpoints (A.K.A. {@link hashPrevouts}) –
* used if `ANYONECANPAY` is not set.
*/
transactionOutpoints: Uint8Array;
/**
* The serialization of all input sequence numbers. (A.K.A.
* {@link hashSequence}) – used if none of `ANYONECANPAY`, `SINGLE`, or
* `NONE` are set.
*/
transactionSequenceNumbers: Uint8Array;
/**
* The big-endian (standard) transaction hash of the outpoint being spent.
*/
outpointTransactionHash: Uint8Array;
/**
* The index of the outpoint being spent in `outpointTransactionHash`.
*/
outpointIndex: number;
/**
* The encoded script currently being executed, beginning at the
* `lastCodeSeparator`.
*/
coveredBytecode: Uint8Array;
/**
* The encoded token prefix of the output being spent
* (see {@link encodeTokenPrefix}).
*
* If the output includes no tokens, a zero-length Uint8Array.
*/
outputTokenPrefix: Uint8Array;
/**
* The 8-byte `Uint64LE`-encoded value of the outpoint in satoshis (see
* {@link bigIntToBinUint64LE}).
*/
outputValue: Uint8Array;
/**
* The sequence number of the input (A.K.A. `nSequence`).
*/
sequenceNumber: number;
/**
* The serialization of the output at the same index as this input (A.K.A.
* {@link hashOutputs} with `SIGHASH_SINGLE`) – only used if `SINGLE`
* is set.
*/
correspondingOutput: Uint8Array | undefined;
/**
* The serialization of output amounts and locking bytecode values (A.K.A.
* {@link hashOutputs} with `SIGHASH_ALL`) – only used if `ALL` is set.
*/
transactionOutputs: Uint8Array;
/**
* The signing serialization of all UTXOs spent by the transaction's inputs
* (concatenated in input order).
*/
transactionUtxos: Uint8Array;
/**
* The locktime of the transaction.
*/
locktime: number;
/**
* The signing serialization type of the signature (A.K.A. `sighash` type).
*/
signingSerializationType: Uint8Array;
/**
* While a bitcoin-encoded signature only includes a single byte to encode the
* signing serialization type, a 3-byte forkId can be appended to provide
* replay-protection between different forks. (See Bitcoin Cash's Replay
* Protected Sighash spec for details.)
*/
forkId?: Uint8Array;
},
sha256: { hash: Sha256['hash'] } = internalSha256
) =>
flattenBinArray([
numberToBinUint32LE(version),
hashPrevouts({ signingSerializationType, transactionOutpoints }, sha256),
hashUtxos({ signingSerializationType, transactionUtxos }, sha256),
hashSequence(
{
signingSerializationType,
transactionSequenceNumbers,
},
sha256
),
outpointTransactionHash.slice().reverse(),
numberToBinUint32LE(outpointIndex),
outputTokenPrefix,
bigIntToCompactSize(BigInt(coveredBytecode.length)),
coveredBytecode,
outputValue,
numberToBinUint32LE(sequenceNumber),
hashOutputs(
{
correspondingOutput,
signingSerializationType,
transactionOutputs,
},
sha256
),
numberToBinUint32LE(locktime),
signingSerializationType,
forkId,
]);
/**
* The signing serialization components that are shared between all of the
* inputs in a transaction.
*/
export interface SigningSerializationTransactionComponentsBCH {
/**
* A time or block height at which the transaction is considered valid (and
* can be added to the block chain). This allows signers to create time-locked
* transactions that may only become valid in the future.
*/
readonly locktime: number;
/**
* A.K.A. the serialization for {@link hashPrevouts}
*
* The signing serialization of all input outpoints. (See BIP143 or Bitcoin
* Cash's Replay Protected Sighash spec for details.)
*/
readonly transactionOutpoints: Uint8Array;
/*
* A.K.A. the serialization for {@link hashOutputs} with `SIGHASH_ALL`
*
* The signing serialization of output amounts and locking scripts. (See
* BIP143 or Bitcoin Cash's Replay Protected Sighash spec for details.)
*/
readonly transactionOutputs: Uint8Array;
/*
* A.K.A. the serialization for {@link hashSequence}
*
* The signing serialization of all input sequence numbers. (See BIP143 or
* Bitcoin Cash's Replay Protected Sighash spec for details.)
*/
readonly transactionSequenceNumbers: Uint8Array;
/**
* A.K.A. the serialization for {@link hashUtxos}
*
* The signing serialization of all UTXOs spent by the transaction's inputs
* (concatenated in input order).
*/
readonly transactionUtxos: Uint8Array;
/**
* The transaction's version.
*/
readonly version: number;
}
/**
* All signing serialization components for a particular transaction input.
*/
export interface SigningSerializationComponentsBCH
extends SigningSerializationTransactionComponentsBCH {
/*
* A.K.A. the serialization for {@link hashOutputs} with `SIGHASH_SINGLE`
*
* The signing serialization of the output at the same index as this input. If
* this input's index is larger than the total number of outputs (such that
* there is no corresponding output), this should be `undefined`. (See BIP143
* or Bitcoin Cash's Replay Protected Sighash spec for details.)
*/
readonly correspondingOutput: Uint8Array | undefined;
/**
* The index (within the previous transaction) of the outpoint being spent by
* this input.
*/
readonly outpointIndex: number;
/**
* The hash/ID of the transaction from which the outpoint being spent by this
* input originated.
*/
readonly outpointTransactionHash: Uint8Array;
/**
* The 8-byte `Uint64LE`-encoded value of the output being spent in satoshis
* (see {@link bigIntToBinUint64LE}).
*/
readonly outputValue: Uint8Array;
/**
* The encoded token prefix of the output being spent
* (see {@link encodeTokenPrefix}).
*
* If the output includes no tokens, a zero-length Uint8Array.
*/
readonly outputTokenPrefix: Uint8Array;
/**
* The `sequenceNumber` associated with the input being validated. See
* {@link Input.sequenceNumber} for details.
*/
readonly sequenceNumber: number;
}
/**
* Generate the encoded components of a BCH signing serialization from
* compilation context.
*/
export const generateSigningSerializationComponentsBCH = (
context: CompilationContextBCH
): SigningSerializationComponentsBCH => ({
correspondingOutput:
context.inputIndex < context.transaction.outputs.length
? encodeTransactionOutput(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
context.transaction.outputs[context.inputIndex]!
)
: undefined,
locktime: context.transaction.locktime,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
outpointIndex: context.transaction.inputs[context.inputIndex]!.outpointIndex,
outpointTransactionHash:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
context.transaction.inputs[context.inputIndex]!.outpointTransactionHash,
outputTokenPrefix: encodeTokenPrefix(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
context.sourceOutputs[context.inputIndex]!.token
),
outputValue: valueSatoshisToBin(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
context.sourceOutputs[context.inputIndex]!.valueSatoshis
),
sequenceNumber:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
context.transaction.inputs[context.inputIndex]!.sequenceNumber,
transactionOutpoints: encodeTransactionOutpoints(context.transaction.inputs),
transactionOutputs: encodeTransactionOutputsForSigning(
context.transaction.outputs
),
transactionSequenceNumbers: encodeTransactionInputSequenceNumbersForSigning(
context.transaction.inputs
),
transactionUtxos: encodeTransactionOutputsForSigning(context.sourceOutputs),
version: context.transaction.version,
});
/**
* Generate the signing serialization for a particular transaction input
* following the algorithm required by the provided `signingSerializationType`.
*
* Note: When validating transactions with multiple signatures,
* performance-critical applications should use a memoized sha256 implementation
* to avoid re-computing hashes.
*/
export const generateSigningSerializationBCH = (
context: CompilationContextBCH,
{
coveredBytecode,
signingSerializationType,
}: {
/**
* The encoded script currently being executed, beginning at the
* `lastCodeSeparator`.
*/
coveredBytecode: Uint8Array;
/**
* The signing serialization type of the signature (A.K.A. `sighash` type).
*/
signingSerializationType: Uint8Array;
},
sha256: { hash: Sha256['hash'] } = internalSha256
) =>
encodeSigningSerializationBCH(
{
...generateSigningSerializationComponentsBCH(context),
coveredBytecode,
signingSerializationType,
},
sha256
);
/**
* @param signingSerializationType - the 32-bit number indicating the signing
* serialization algorithm to use
*/
export const isLegacySigningSerialization = (
signingSerializationType: number
) => {
// eslint-disable-next-line no-bitwise, @typescript-eslint/no-magic-numbers
const forkValue = signingSerializationType >> 8;
// eslint-disable-next-line no-bitwise, @typescript-eslint/no-magic-numbers
const newForkValue = (forkValue ^ 0xdead) | 0xff0000;
// eslint-disable-next-line no-bitwise, @typescript-eslint/no-magic-numbers
const sighashType = (newForkValue << 8) | (signingSerializationType & 0xff);
// eslint-disable-next-line no-bitwise
return (sighashType & SigningSerializationFlag.forkId) === 0;
};