@alexbosworth/blockchain 4.5.3 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Versions
2
2
 
3
+ ## 4.7.0
4
+
5
+ - `nonWitnessHashToSign`: Add method to calculate the pre-SegWit hash to sign
6
+
7
+ ## 4.6.0
8
+
9
+ - `v0HashToSign`: Add method to calculate the v0 witness hash to sign
10
+
3
11
  ## 4.5.3
4
12
 
5
13
  - `encodeBase58Address`: Add method to convert hash and version to b58 address
package/README.md CHANGED
@@ -16,6 +16,7 @@ Utility methods for working with Blockchain data
16
16
  - [idForTransaction](#idfortransaction)
17
17
  - [idForTransactionComponents](#idfortransactioncomponents)
18
18
  - [noLocktimeIdForTransaction](#nolocktimeidfortransaction)
19
+ - [nonWitnessHashToSign](#nonwitnesshashtosign)
19
20
  - [numberAsCompactInt](#numberascompactint)
20
21
  - [p2msScript](#p2msscript)
21
22
  - [p2pkhOutputScript](#p2pkhoutputscript)
@@ -30,6 +31,7 @@ Utility methods for working with Blockchain data
30
31
  - [sizeOfTransaction](#sizeoftransaction)
31
32
  - [transactionFromComponents](#transactionfromcomponents)
32
33
  - [unsignedTxFromPsbt](#unsignedtxfrompsbt)
34
+ - [v0HashToSign](#v0hashtosign)
33
35
 
34
36
  ### compactIntAsNumber
35
37
 
@@ -295,6 +297,34 @@ Get an id for a transaction with witness data and mlocktime not included
295
297
  id: <No nLockTime Transaction Id Hex String>
296
298
  }
297
299
 
300
+ ### nonWitnessHashToSign
301
+
302
+ Calculate the pre-SegWit transaction hash to sign
303
+
304
+ For P2PK, P2PKH, or bare multisig the script is the output script being spent
305
+
306
+ For P2SH the script is the redeem script that hashes to the output script
307
+
308
+ When a code separator was executed, pass only the script following it, any
309
+ remaining code separators are removed from the script before hashing
310
+
311
+ Signing for a single output requires an output matching the input index
312
+
313
+ {
314
+ script: <Signing Input Script Hex String>
315
+ [sighash]: <Signature Hash Type Number>
316
+ transaction: <Raw Transaction Hex String>
317
+ vin: <Signing Transaction Input Index Number>
318
+ }
319
+
320
+ @throws
321
+ <Error>
322
+
323
+ @returns
324
+ {
325
+ hash: <Hash to Sign Hex String>
326
+ }
327
+
298
328
  ### numberAsCompactInt
299
329
 
300
330
  Convert a number to compact size integer serialization
@@ -553,3 +583,29 @@ Get the unsigned transaction out of a PSBT
553
583
  {
554
584
  transaction: <Unsigned Transaction Buffer Object>
555
585
  }
586
+
587
+ ### v0HashToSign
588
+
589
+ Calculate the v0 witness transaction hash to sign
590
+
591
+ The script is the BIP 143 script code of the output being spent
592
+
593
+ For P2WPKH the script code is the P2PKH script of the public key hash
594
+
595
+ For P2WSH the script code is the witness script
596
+
597
+ {
598
+ script: <Signing Input Script Hex String>
599
+ [sighash]: <Signature Hash Type Number>
600
+ tokens: <Spending Output Tokens Number>
601
+ transaction: <Raw Transaction Hex String>
602
+ vin: <Signing Transaction Input Index Number>
603
+ }
604
+
605
+ @throws
606
+ <Error>
607
+
608
+ @returns
609
+ {
610
+ hash: <Hash to Sign Hex String>
611
+ }
package/index.js CHANGED
@@ -10,6 +10,7 @@ const {idForBlock} = require('./hashes');
10
10
  const {idForTransaction} = require('./transactions');
11
11
  const {idForTransactionComponents} = require('./hashes');
12
12
  const {noLocktimeIdForTransaction} = require('./transactions');
13
+ const {nonWitnessHashToSign} = require('./transactions');
13
14
  const {numberAsCompactInt} = require('./numbers');
14
15
  const {p2msScript} = require('./script');
15
16
  const {p2pkhOutputScript} = require('./script');
@@ -24,6 +25,7 @@ const {scriptElementsAsScript} = require('./script');
24
25
  const {sizeOfTransaction} = require('./transactions');
25
26
  const {transactionFromComponents} = require('./transactions');
26
27
  const {unsignedTxFromPsbt} = require('./transactions');
28
+ const {v0HashToSign} = require('./transactions');
27
29
 
28
30
  module.exports = {
29
31
  compactIntAsNumber,
@@ -38,6 +40,7 @@ module.exports = {
38
40
  idForTransaction,
39
41
  idForTransactionComponents,
40
42
  noLocktimeIdForTransaction,
43
+ nonWitnessHashToSign,
41
44
  numberAsCompactInt,
42
45
  p2msScript,
43
46
  p2pkhOutputScript,
@@ -52,4 +55,5 @@ module.exports = {
52
55
  sizeOfTransaction,
53
56
  transactionFromComponents,
54
57
  unsignedTxFromPsbt,
58
+ v0HashToSign,
55
59
  };
package/numbers/index.js CHANGED
@@ -1,11 +1,13 @@
1
1
  const compactIntAsNumber = require('./compact_int_as_number');
2
2
  const encodePushBytesCount = require('./encode_push_bytes_count');
3
3
  const numberAsCompactInt = require('./number_as_compact_int');
4
+ const numberAsLittleEndian = require('./number_as_little_endian');
4
5
  const parsePushBytesCount = require('./parse_push_bytes_count');
5
6
 
6
7
  module.exports = {
7
8
  compactIntAsNumber,
8
9
  encodePushBytesCount,
9
10
  numberAsCompactInt,
11
+ numberAsLittleEndian,
10
12
  parsePushBytesCount,
11
13
  };
@@ -0,0 +1,65 @@
1
+ const {alloc} = Buffer;
2
+ const asBigInt = number => BigInt(number);
3
+ const bitsPerByte = 8;
4
+ const byteCountBigInt = 8;
5
+ const byteCounts = [1, 2, 3, 4, 5, 6, 8];
6
+ const {isInteger} = Number;
7
+ const maxSigned = bytes => 2 ** (bytes * bitsPerByte - 1) - 1;
8
+ const maxUnsigned = bytes => 2 ** (bytes * bitsPerByte) - 1;
9
+ const minSigned = bytes => -(2 ** (bytes * bitsPerByte - 1));
10
+ const minUnsigned = 0;
11
+ const writeOffset = 0;
12
+
13
+ /** Encode a number as little endian bytes
14
+
15
+ A signed negative number is encoded as its twos complement representation
16
+
17
+ {
18
+ bytes: <Encoded Bytes Count Number>
19
+ [is_signed]: <Number Is A Signed Number Bool>
20
+ number: <Number to Encode Number>
21
+ }
22
+
23
+ @throws
24
+ <Error>
25
+
26
+ @returns
27
+ {
28
+ encoded: <Little Endian Encoded Number Buffer Object>
29
+ }
30
+ */
31
+ module.exports = args => {
32
+ if (!byteCounts.includes(args.bytes)) {
33
+ throw new Error('ExpectedBytesCountToEncodeNumberAsLittleEndian');
34
+ }
35
+
36
+ if (!isInteger(args.number)) {
37
+ throw new Error('ExpectedNumberToEncodeAsLittleEndianBytes');
38
+ }
39
+
40
+ const isSigned = !!args.is_signed;
41
+
42
+ const max = isSigned ? maxSigned(args.bytes) : maxUnsigned(args.bytes);
43
+ const min = isSigned ? minSigned(args.bytes) : minUnsigned;
44
+
45
+ if (args.number < min || args.number > max) {
46
+ throw new Error('ExpectedNumberInByteRangeToEncodeAsLittleEndian');
47
+ }
48
+
49
+ const encoded = alloc(args.bytes);
50
+
51
+ if (args.bytes === byteCountBigInt && isSigned) {
52
+ // Eight byte signed numbers are written as signed big int numbers
53
+ encoded.writeBigInt64LE(asBigInt(args.number));
54
+ } else if (args.bytes === byteCountBigInt) {
55
+ // Eight byte numbers are written as unsigned big int numbers
56
+ encoded.writeBigUInt64LE(asBigInt(args.number));
57
+ } else if (isSigned) {
58
+ // Signed numbers are written as twos complement integers
59
+ encoded.writeIntLE(args.number, writeOffset, args.bytes);
60
+ } else {
61
+ encoded.writeUIntLE(args.number, writeOffset, args.bytes);
62
+ }
63
+
64
+ return {encoded};
65
+ };
package/package.json CHANGED
@@ -19,5 +19,5 @@
19
19
  "scripts": {
20
20
  "test": "node --experimental-test-coverage --test test/5bit/*.js test/addresses/*.js test/hashes/*.js test/numbers/*.js test/script/*.js test/transactions/*.js"
21
21
  },
22
- "version": "4.5.3"
22
+ "version": "4.7.0"
23
23
  }
@@ -0,0 +1,77 @@
1
+ const {deepStrictEqual} = require('node:assert').strict;
2
+ const {throws} = require('node:assert').strict;
3
+ const test = require('node:test');
4
+
5
+ const {numberAsLittleEndian} = require('./../../numbers');
6
+
7
+ const tests = [
8
+ {
9
+ args: {bytes: 7, number: 1},
10
+ description: 'A supported bytes count is required',
11
+ error: 'ExpectedBytesCountToEncodeNumberAsLittleEndian',
12
+ },
13
+ {
14
+ args: {bytes: 4, number: '1'},
15
+ description: 'A number to encode is required',
16
+ error: 'ExpectedNumberToEncodeAsLittleEndianBytes',
17
+ },
18
+ {
19
+ args: {bytes: 1, number: 256},
20
+ description: 'A number within the byte range is required',
21
+ error: 'ExpectedNumberInByteRangeToEncodeAsLittleEndian',
22
+ },
23
+ {
24
+ args: {bytes: 4, number: -1},
25
+ description: 'A negative number requires the signed flag',
26
+ error: 'ExpectedNumberInByteRangeToEncodeAsLittleEndian',
27
+ },
28
+ {
29
+ args: {bytes: 4, is_signed: true, number: -2147483649},
30
+ description: 'A negative number within the byte range is required',
31
+ error: 'ExpectedNumberInByteRangeToEncodeAsLittleEndian',
32
+ },
33
+ {
34
+ args: {bytes: 4, is_signed: true, number: 2147483648},
35
+ description: 'A signed number within the signed range is required',
36
+ error: 'ExpectedNumberInByteRangeToEncodeAsLittleEndian',
37
+ },
38
+ {
39
+ args: {bytes: 1, number: 255},
40
+ description: 'A single byte number is encoded',
41
+ expected: {encoded: Buffer.from('ff', 'hex')},
42
+ },
43
+ {
44
+ args: {bytes: 4, number: 16843009},
45
+ description: 'A four byte number is encoded as little endian',
46
+ expected: {encoded: Buffer.from('01010101', 'hex')},
47
+ },
48
+ {
49
+ args: {bytes: 4, is_signed: true, number: -1},
50
+ description: 'A negative number is encoded as twos complement',
51
+ expected: {encoded: Buffer.from('ffffffff', 'hex')},
52
+ },
53
+ {
54
+ args: {bytes: 8, number: 987654321},
55
+ description: 'An eight byte number is encoded as little endian',
56
+ expected: {encoded: Buffer.from('b168de3a00000000', 'hex')},
57
+ },
58
+ {
59
+ args: {bytes: 8, is_signed: true, number: -1},
60
+ description: 'A negative eight byte number is encoded as twos complement',
61
+ expected: {encoded: Buffer.from('ffffffffffffffff', 'hex')},
62
+ },
63
+ ];
64
+
65
+ tests.forEach(({args, description, error, expected}) => {
66
+ return test(description, (t, end) => {
67
+ if (!!error) {
68
+ throws(() => numberAsLittleEndian(args), new Error(error), 'Got error');
69
+ } else {
70
+ const res = numberAsLittleEndian(args);
71
+
72
+ deepStrictEqual(res, expected, 'Got expected result');
73
+ }
74
+
75
+ return end();
76
+ });
77
+ });
@@ -0,0 +1,404 @@
1
+ const {deepStrictEqual} = require('node:assert').strict;
2
+ const {throws} = require('node:assert').strict;
3
+ const test = require('node:test');
4
+
5
+ const {nonWitnessHashToSign} = require('./../../');
6
+
7
+ const anyOnePaysP2pkScriptCode = '21035e7f0d4d0841bcd56c39337ed086b1a633ee770c1ffdd94ac552a95ac2ce0efcac';
8
+ const anyOnePaysTransaction = '010000000200010000000000000000000000000000000000000000000000000000000000000000000049483045022100d180fd2eb9140aeb4210c9204d3f358766eb53842b2a9473db687fa24b12a3cc022079781799cd4f038b85135bbe49ec2b57f306b2bb17101b17f71f000fcab2b6fb01ffffffff0002000000000000000000000000000000000000000000000000000000000000000000004847304402205f7530653eea9b38699e476320ab135b74771e1c48b81a5d041e2ca84b9be7a802200ac8d1f40fb026674fe5a5edd3dea715c27baa9baca51ed45ea750ac9dc0a55e81ffffffff010100000000000000015100000000';
9
+ const changedSequenceTransaction = '01000000020001000000000000000000000000000000000000000000000000000000000000000000004948304502203a0f5f0e1f2bdbcd04db3061d18f3af70e07f4f467cbc1b8116f267025f5360b022100c792b6e215afc5afc721a351ec413e714305cb749aae3d7fee76621313418df101010000000002000000000000000000000000000000000000000000000000000000000000000000004847304402205f7530653eea9b38699e476320ab135b74771e1c48b81a5d041e2ca84b9be7a802200ac8d1f40fb026674fe5a5edd3dea715c27baa9baca51ed45ea750ac9dc0a55e81ffffffff010100000000000000015100000000';
10
+ const p2pkhScriptCode = '76a9141d0f172a0ecb48aee1be1f2687d2963ae33f71a188ac';
11
+ const singleAnyOnePaysP2pkScriptCode = '2103596d3451025c19dbbdeb932d6bf8bfb4ad499b95b6f88db8899efac102e5fc71ac';
12
+ const singleAnyOnePaysP2pkTransaction = '01000000020001000000000000000000000000000000000000000000000000000000000000000000004847304402202a0b4b1294d70540235ae033d78e64b4897ec859c7b6f1b2b1d8a02e1d46006702201445e756d2254b0f1dfda9ab8e1e1bc26df9668077403204f32d16a49a36eb6983ffffffff00010000000000000000000000000000000000000000000000000000000000000100000049483045022100acb96cfdbda6dc94b489fd06f2d720983b5f350e31ba906cdbd800773e80b21c02200d74ea5bdf114212b4bbe9ed82c36d2e369e302dff57cb60d01c428f0bd3daab83ffffffff02e8030000000000000151e903000000000000015100000000';
13
+ const singleAnyOnePaysTransaction = '010000000390d31c6107013d754529d8818eff285fe40a3e7635f6930fec5d12eb02107a43010000006b483045022100f40815ae3c81a0dd851cc8d376d6fd226c88416671346a9033468cca2cdcc6c202204f764623903e6c4bed1b734b75d82c40f1725e4471a55ad4f51218f86130ac038321033d710ab45bb54ac99618ad23b3c1da661631aa25f23bfe9d22b41876f1d46e4effffffff3ff04a68e22bdd52e7c8cb848156d2d158bd5515b3c50adabc87d0ca2cd3482d010000006a4730440220598d263c107004008e9e26baa1e770be30fd31ee55ded1898f7c00da05a75977022045536bead322ca246779698b9c3df3003377090f41afeca7fb2ce9e328ec4af2832102b738b531def73020bd637f32935924cc88549c8206976226d968edd3a42fc2d7ffffffff46a8dc8970eb96622f27a516adcf40e0fcec5731e7556e174f2a271aef6861c7010000006b483045022100c5b90a777a9fdc90c208dbef7290d1fc1be651f47151ee4ccff646872a454cf90220640cfbc4550446968fbbe9d12528f3adf7d87b31541569c59e790db8a220482583210391332546e22bbe8fe3af54addfad6f8b83d05fa4f5e047593d4c07ae938795beffffffff028036be26000000001976a914ddfb29efad43a667465ac59ff14dc6442a1adfca88ac3d5cba01000000001976a914b64dde7a505a13ca986c40e86e984a8dc81368b688ac00000000';
14
+ const singleScriptCode = '76a914dcf72c4fd02f5a987cf9b02f2fabfcac3341a87d88ac';
15
+ const singleTransaction = '010000000370ac0a1ae588aaf284c308d67ca92c69a39e2db81337e563bf40c59da0a5cf63000000006a4730440220360d20baff382059040ba9be98947fd678fb08aab2bb0c172efa996fd8ece9b702201b4fb0de67f015c90e7ac8a193aeab486a1f587e0f54d0fb9552ef7f5ce6caec032103579ca2e6d107522f012cd00b52b9a65fb46f0c57b9b8b6e377c48f526a44741affffffff7d815b6447e35fbea097e00e028fb7dfbad4f3f0987b4734676c84f3fcd0e804010000006b483045022100c714310be1e3a9ff1c5f7cacc65c2d8e781fc3a88ceb063c6153bf950650802102200b2d0979c76e12bb480da635f192cc8dc6f905380dd4ac1ff35a4f68f462fffd032103579ca2e6d107522f012cd00b52b9a65fb46f0c57b9b8b6e377c48f526a44741affffffff3f1f097333e4d46d51f5e77b53264db8f7f5d2e18217e1099957d0f5af7713ee010000006c493046022100b663499ef73273a3788dea342717c2640ac43c5a1cf862c9e09b206fcb3f6bb8022100b09972e75972d9148f2bdd462e5cb69b57c1214b88fc55ca638676c07cfc10d8032103579ca2e6d107522f012cd00b52b9a65fb46f0c57b9b8b6e377c48f526a44741affffffff0380841e00000000001976a914bfb282c70c4191f45b5a6665cad1682f2c9cfdfb88ac80841e00000000001976a9149857cc07bed33a5cf12b9c5e0500b675d500c81188ace0fd1c00000000001976a91443c52850606c872403c0601e69fa34b26f62db4a88ac00000000';
16
+ const twoInTwoOutTransaction = '0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac11000000';
17
+
18
+ const tests = [
19
+ {
20
+ args: {script: undefined},
21
+ description: 'A script code hex string is required',
22
+ error: 'ExpectedScriptCodeHexToCalculateNonWitnessHashToSign',
23
+ },
24
+ {
25
+ args: {script: '00', sighash: 0x04},
26
+ description: 'A known signature hash type is required',
27
+ error: 'ExpectedValidSigHashTypeForNonWitnessHashToSign',
28
+ },
29
+ {
30
+ args: {script: '00', sighash: 0x01},
31
+ description: 'A transaction hex string is required',
32
+ error: 'ExpectedTransactionHexToCalculateNonWitnessHashToSign',
33
+ },
34
+ {
35
+ args: {script: '00', sighash: 0x01, transaction: twoInTwoOutTransaction},
36
+ description: 'An input index number is required',
37
+ error: 'ExpectedInputIndexToCalculateNonWitnessHashToSign',
38
+ },
39
+ {
40
+ args: {
41
+ script: '00',
42
+ sighash: 0x01,
43
+ transaction: twoInTwoOutTransaction,
44
+ vin: 2,
45
+ },
46
+ description: 'A matching input is required',
47
+ error: 'ExpectedMatchingInputToCalculateNonWitnessHashToSign',
48
+ },
49
+ {
50
+ args: {
51
+ script: '76a91434fea2c5a75414fd945273ae2d029ce1f28dafcf88ac',
52
+ sighash: 0x83,
53
+ transaction: singleAnyOnePaysTransaction,
54
+ vin: 2,
55
+ },
56
+ description: 'A single input past the outputs is refused not signed as one',
57
+ error: 'ExpectedMatchingOutputForSingleNonWitnessHashToSign',
58
+ },
59
+ {
60
+ args: {
61
+ script: '4c',
62
+ sighash: 0x01,
63
+ transaction: twoInTwoOutTransaction,
64
+ vin: 0,
65
+ },
66
+ description: 'A well formed script code is required',
67
+ error: 'ExpectedValidScriptCodeForNonWitnessHashToSign',
68
+ },
69
+ {
70
+ args: {
71
+ script: '02ab',
72
+ sighash: 0x01,
73
+ transaction: twoInTwoOutTransaction,
74
+ vin: 0,
75
+ },
76
+ description: 'Complete script code push data bytes are required',
77
+ error: 'ExpectedValidScriptCodeForNonWitnessHashToSign',
78
+ },
79
+ {
80
+ args: {
81
+ script: '410411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3ac',
82
+ sighash: 0x01,
83
+ transaction: '0100000001c997a5e56e104102fa209c6a852dd90660a20b2d9c352423edce25857fcd3704000000004847304402204e45e16932b8af514961a1d3a1a25fdf3f4f7732e9d624c6c61548ab5fb8cd410220181522ec8eca07de4860a4acdd12909d831cc56cbbac4622082221a8768d1d0901ffffffff0200ca9a3b00000000434104ae1a62fe09c5f51b13905f07f06b99a2f7159b2225f374cd378d71302fa28414e7aab37397f554a7df5f142c21c1b7303b8a0626f1baded5c72a704f7e6cd84cac00286bee0000000043410411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3ac00000000',
84
+ vin: 0,
85
+ },
86
+ description: 'The first ever transaction signature hash is calculated',
87
+ expected: {
88
+ hash: '7a05c6145f10101e9d6325494245adf1297d80f8f38d4d576d57cdba220bcb19',
89
+ },
90
+ },
91
+ {
92
+ args: {
93
+ script: singleScriptCode,
94
+ sighash: 0x03,
95
+ transaction: singleTransaction,
96
+ vin: 0,
97
+ },
98
+ description: 'A mainnet single hash is calculated for the first input',
99
+ expected: {
100
+ hash: '465f0318f9801d56aeb1737d1e9af8e27d841a493b11494a9283477a1fdccc1e',
101
+ },
102
+ },
103
+ {
104
+ args: {
105
+ script: singleScriptCode,
106
+ sighash: 0x03,
107
+ transaction: singleTransaction,
108
+ vin: 1,
109
+ },
110
+ description: 'A mainnet single hash is calculated for the second input',
111
+ expected: {
112
+ hash: '3b8eee7ff2be39a1d7a69cfdfda487985caa090f33858a60de0b4df67ae84319',
113
+ },
114
+ },
115
+ {
116
+ args: {
117
+ script: singleScriptCode,
118
+ sighash: 0x03,
119
+ transaction: singleTransaction,
120
+ vin: 2,
121
+ },
122
+ description: 'A mainnet single hash is calculated for the third input',
123
+ expected: {
124
+ hash: 'd694785005d3292d4771695034ee3f07b4dc8a3bacfdb0ecf221a7a68d061f1c',
125
+ },
126
+ },
127
+ {
128
+ args: {
129
+ script: '76a914383fb81cb0a3fc724b5e08cf8bbd404336d711f688ac',
130
+ sighash: 0x83,
131
+ transaction: singleAnyOnePaysTransaction,
132
+ vin: 0,
133
+ },
134
+ description: 'A p2pkh single anyone can pay hash is calculated',
135
+ expected: {
136
+ hash: 'dc8584ae65a4ee4485d402bfadebb501077579adda20de321a1cbfb2a7dcff5b',
137
+ },
138
+ },
139
+ {
140
+ args: {
141
+ script: '76a914275ec2a233e5b23d43fa19e7bf9beb0cb399611788ac',
142
+ sighash: 0x83,
143
+ transaction: singleAnyOnePaysTransaction,
144
+ vin: 1,
145
+ },
146
+ description: 'A p2pkh single anyone can pay hash blanks the first output',
147
+ expected: {
148
+ hash: '2c0c915ab013457e84e8fedbd834d9c2c659c15caacb501c22eae52e65bd06da',
149
+ },
150
+ },
151
+ {
152
+ args: {
153
+ script: anyOnePaysP2pkScriptCode,
154
+ sighash: 0x01,
155
+ transaction: anyOnePaysTransaction,
156
+ vin: 0,
157
+ },
158
+ description: 'A p2pk hash is calculated for all beside an anyone can pay',
159
+ expected: {
160
+ hash: 'f69b639c5d2ee6f886701efaf4616daa84793a48d851d19434bb6a13dd6225cc',
161
+ },
162
+ },
163
+ {
164
+ args: {
165
+ script: anyOnePaysP2pkScriptCode,
166
+ sighash: 0x81,
167
+ transaction: anyOnePaysTransaction,
168
+ vin: 1,
169
+ },
170
+ description: 'A p2pk hash is calculated for all anyone can pay',
171
+ expected: {
172
+ hash: '57f5a54d548db73fa8ef7a43d011120f9935fe792f0a0630d28ee70b4c72a7e8',
173
+ },
174
+ },
175
+ {
176
+ args: {
177
+ script: anyOnePaysP2pkScriptCode,
178
+ sighash: 0x81,
179
+ transaction: changedSequenceTransaction,
180
+ vin: 1,
181
+ },
182
+ description: 'An anyone can pay hash ignores other input sequence changes',
183
+ expected: {
184
+ hash: '57f5a54d548db73fa8ef7a43d011120f9935fe792f0a0630d28ee70b4c72a7e8',
185
+ },
186
+ },
187
+ {
188
+ args: {
189
+ script: singleAnyOnePaysP2pkScriptCode,
190
+ sighash: 0x83,
191
+ transaction: singleAnyOnePaysP2pkTransaction,
192
+ vin: 0,
193
+ },
194
+ description: 'A single anyone can pay hash commits to the input position',
195
+ expected: {
196
+ hash: 'e67f282e8931e966e29d467b36d974cc67fa8cfbf8b230673e7dfa04d8213a95',
197
+ },
198
+ },
199
+ {
200
+ args: {
201
+ script: singleAnyOnePaysP2pkScriptCode,
202
+ sighash: 0x83,
203
+ transaction: singleAnyOnePaysP2pkTransaction,
204
+ vin: 1,
205
+ },
206
+ description: 'A single anyone can pay hash differs for the second input',
207
+ expected: {
208
+ hash: '63df76233203400e0af3395d8eba7fe3f98095bf1a0c0f5ac0d356981fb6033a',
209
+ },
210
+ },
211
+ {
212
+ args: {
213
+ script: 'ad',
214
+ sighash: 0x01,
215
+ transaction: '010000000169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f1581b0000b64830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0121037a3fb04bcdb09eba90f69961ba1692a3528e45e67c85b200df820212d7594d334aad4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e01ffffffff0101000000000000000000000000',
216
+ vin: 0,
217
+ },
218
+ description: 'A p2sh redeem script code with a deleted signature is hashed',
219
+ expected: {
220
+ hash: '1ba1fe3bc90c5d1265460e684ce6774e324f0fabdf67619eda729e64e8b6bc08',
221
+ },
222
+ },
223
+ {
224
+ args: {
225
+ script: '52af75',
226
+ sighash: 0x01,
227
+ transaction: '01000000019275cb8d4a485ce95741c013f7c0d28722160008021bb469a11982d47a662896581b0000fd6f01004830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c03959601522102cd74a2809ffeeed0092bc124fd79836706e41f048db3f6ae9df8708cefb83a1c2102e615999372426e46fd107b76eaf007156a507584aa2cc21de9eee3bdbd26d36c4c9552af4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c0395960175ffffffff0101000000000000000000000000',
228
+ vin: 0,
229
+ },
230
+ description: 'A multisig redeem script code with deleted signatures is hashed',
231
+ expected: {
232
+ hash: '1d50f00ba4db2917b903b0ec5002e017343bb38876398c9510570f5dce099295',
233
+ },
234
+ },
235
+ {
236
+ args: {
237
+ script: p2pkhScriptCode,
238
+ sighash: 0x01,
239
+ transaction: twoInTwoOutTransaction,
240
+ vin: 0,
241
+ },
242
+ description: 'A non witness hash to sign is calculated for all',
243
+ expected: {
244
+ hash: '47194bc3c303a30aa5f78e45c7c2980b3be1284a9d69b1ea9ec0d29aac5f6848',
245
+ },
246
+ },
247
+ {
248
+ args: {
249
+ script: p2pkhScriptCode,
250
+ transaction: twoInTwoOutTransaction,
251
+ vin: 0,
252
+ },
253
+ description: 'A non witness hash to sign defaults to signing for all',
254
+ expected: {
255
+ hash: '47194bc3c303a30aa5f78e45c7c2980b3be1284a9d69b1ea9ec0d29aac5f6848',
256
+ },
257
+ },
258
+ {
259
+ args: {
260
+ script: p2pkhScriptCode,
261
+ sighash: 0x02,
262
+ transaction: twoInTwoOutTransaction,
263
+ vin: 1,
264
+ },
265
+ description: 'A non witness hash to sign is calculated for none',
266
+ expected: {
267
+ hash: 'ffbbcf554debe55f76a79db7d205edc891f194184a93a660366bb8f7facb89e2',
268
+ },
269
+ },
270
+ {
271
+ args: {
272
+ script: p2pkhScriptCode,
273
+ sighash: 0x03,
274
+ transaction: twoInTwoOutTransaction,
275
+ vin: 1,
276
+ },
277
+ description: 'A non witness hash to sign is calculated for single',
278
+ expected: {
279
+ hash: '33cd468bd6b82f04bcef180b748c521d6fdee3b11711a2f27b2e465915afaec2',
280
+ },
281
+ },
282
+ {
283
+ args: {
284
+ script: p2pkhScriptCode,
285
+ sighash: 0x81,
286
+ transaction: twoInTwoOutTransaction,
287
+ vin: 0,
288
+ },
289
+ description: 'A non witness hash is calculated for all anyone can pay',
290
+ expected: {
291
+ hash: '4e7de48ff097d47bb87912759ec9380049a160289f2b89d48a28887ee30a41d4',
292
+ },
293
+ },
294
+ {
295
+ args: {
296
+ script: p2pkhScriptCode,
297
+ sighash: 0x82,
298
+ transaction: twoInTwoOutTransaction,
299
+ vin: 1,
300
+ },
301
+ description: 'A non witness hash is calculated for none anyone can pay',
302
+ expected: {
303
+ hash: 'bd8ca4cb1ab60a8db8451bd58bc068a9abd5ea20a08029b38934c9d50c1d6721',
304
+ },
305
+ },
306
+ {
307
+ args: {
308
+ script: p2pkhScriptCode,
309
+ sighash: 0x83,
310
+ transaction: twoInTwoOutTransaction,
311
+ vin: 1,
312
+ },
313
+ description: 'A non witness hash is calculated for single anyone can pay',
314
+ expected: {
315
+ hash: '865c7791b88917498a4c402176c302f146c53a6c2f50ecda08548f515237dca6',
316
+ },
317
+ },
318
+ {
319
+ args: {
320
+ script: '00ab' + p2pkhScriptCode,
321
+ sighash: 0x01,
322
+ transaction: twoInTwoOutTransaction,
323
+ vin: 0,
324
+ },
325
+ description: 'A zero op code is kept in the committed script code',
326
+ expected: {
327
+ hash: 'bc2a4d64ca999408ad71506b90d27225e59e3bf3f1308a9f43e67c04a8515fbc',
328
+ },
329
+ },
330
+ {
331
+ args: {
332
+ script: '4c50' + 'ab'.repeat(80) + '75' + p2pkhScriptCode + 'ab',
333
+ sighash: 0x01,
334
+ transaction: twoInTwoOutTransaction,
335
+ vin: 0,
336
+ },
337
+ description: 'Separator bytes inside a push data 1 push are kept',
338
+ expected: {
339
+ hash: '64b2d0421e77f95ee403ff7eec49c2066af6fcfcbb8822e32a3813fe6878afd9',
340
+ },
341
+ },
342
+ {
343
+ args: {
344
+ script: 'ab4d0001' + 'ab'.repeat(256) + '75' + p2pkhScriptCode + 'ab',
345
+ sighash: 0x01,
346
+ transaction: twoInTwoOutTransaction,
347
+ vin: 0,
348
+ },
349
+ description: 'Separator bytes inside a push data 2 push are kept',
350
+ expected: {
351
+ hash: '778dffb8dc7acbbece56410ca48e663ba2e2c10ecb13509575d30f74a0a77f27',
352
+ },
353
+ },
354
+ {
355
+ args: {
356
+ script: p2pkhScriptCode,
357
+ sighash: 0x03,
358
+ transaction: twoInTwoOutTransaction,
359
+ vin: 0,
360
+ },
361
+ description: 'A single hash for the first input blanks no outputs',
362
+ expected: {
363
+ hash: '0d8ad17ba098be7eaf7efff778bb22e234805b5d370c996271a7f5ff7416f263',
364
+ },
365
+ },
366
+ {
367
+ args: {
368
+ script: p2pkhScriptCode,
369
+ sighash: 0x01,
370
+ transaction: 'ffffffff' + twoInTwoOutTransaction.slice(8),
371
+ vin: 0,
372
+ },
373
+ description: 'A negative version number is committed to as signed bytes',
374
+ expected: {
375
+ hash: '19ed79919ad5a3f911dec0e134b52ba4d9ac5a6b15bcbdd685ff146a8690c024',
376
+ },
377
+ },
378
+ {
379
+ args: {
380
+ script: 'ab' + p2pkhScriptCode + 'ab',
381
+ sighash: 0x01,
382
+ transaction: twoInTwoOutTransaction,
383
+ vin: 0,
384
+ },
385
+ description: 'Code separators are removed from the script code',
386
+ expected: {
387
+ hash: '47194bc3c303a30aa5f78e45c7c2980b3be1284a9d69b1ea9ec0d29aac5f6848',
388
+ },
389
+ },
390
+ ];
391
+
392
+ tests.forEach(({args, description, error, expected}) => {
393
+ return test(description, (t, end) => {
394
+ if (!!error) {
395
+ throws(() => nonWitnessHashToSign(args), new Error(error), 'Got error');
396
+ } else {
397
+ const res = nonWitnessHashToSign(args);
398
+
399
+ deepStrictEqual(res, expected, 'Got expected result');
400
+ }
401
+
402
+ return end();
403
+ });
404
+ });
@@ -0,0 +1,262 @@
1
+ const {deepStrictEqual} = require('node:assert').strict;
2
+ const {throws} = require('node:assert').strict;
3
+ const test = require('node:test');
4
+
5
+ const {v0HashToSign} = require('./../../');
6
+
7
+ const nativeP2shP2wshTransaction = '010000000136641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1ca29787b96e0100000000ffffffff0200e9a435000000001976a914389ffce9cd9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976a9147480a33f950689af511e6e84c138dbbd3c3ee41588ac00000000';
8
+ const p2shP2wshWitnessScript = '56210307b8ae49ac90a048e9b53357a2354b3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56ae';
9
+
10
+ const singleAnyoneCanPayTransaction = '0100000002e9b542c5176808107ff1df906f46bb1f2583b16112b95ee5380665ba7fcfc0010000000000ffffffff80e68831516392fcd100d186b3c2c7b95c80b53c77e77c35ba03a66b429a2a1b0000000000ffffffff0280969800000000001976a914de4b231626ef508c9a74a8517e6783c0546d6b2888ac80969800000000001976a9146648a8cd4531e1ec47f35916de8e259237294d1e88ac00000000';
11
+
12
+ const tests = [
13
+ {
14
+ args: {script: undefined},
15
+ description: 'A script code hex string is required',
16
+ error: 'ExpectedScriptCodeHexStringToCalculateV0HashToSign',
17
+ },
18
+ {
19
+ args: {script: '00', sighash: 0x04},
20
+ description: 'A known signature hash type is required',
21
+ error: 'ExpectedValidSignatureHashTypeToCalculateV0HashToSign',
22
+ },
23
+ {
24
+ args: {script: '00', sighash: 0x01},
25
+ description: 'A spend tokens number is required',
26
+ error: 'ExpectedSpendTokensNumberToCalculateV0HashToSign',
27
+ },
28
+ {
29
+ args: {script: '00', sighash: 0x01, tokens: 1},
30
+ description: 'A transaction hex string is required',
31
+ error: 'ExpectedTransactionHexStringToCalculateV0HashToSign',
32
+ },
33
+ {
34
+ args: {
35
+ script: '00',
36
+ sighash: 0x01,
37
+ tokens: 1,
38
+ transaction: nativeP2shP2wshTransaction,
39
+ },
40
+ description: 'An input index number is required',
41
+ error: 'ExpectedInputIndexNumberToCalculateV0HashToSign',
42
+ },
43
+ {
44
+ args: {
45
+ script: '00',
46
+ sighash: 0x01,
47
+ tokens: 1,
48
+ transaction: nativeP2shP2wshTransaction,
49
+ vin: 1,
50
+ },
51
+ description: 'A matching input is required',
52
+ error: 'ExpectedMatchingInputToCalculateV0HashToSign',
53
+ },
54
+ {
55
+ args: {
56
+ script: '76a9141d0f172a0ecb48aee1be1f2687d2963ae33f71a188ac',
57
+ sighash: 0x01,
58
+ tokens: 600000000,
59
+ transaction: '0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac11000000',
60
+ vin: 1,
61
+ },
62
+ description: 'A native P2WPKH input hash to sign is calculated',
63
+ expected: {
64
+ hash: 'c37af31116d1b27caf68aae9e3ac82f1477929014d5b917657d0eb49478cb670',
65
+ },
66
+ },
67
+ {
68
+ args: {
69
+ script: '76a91479091972186c449eb1ded22b78e40d009bdf008988ac',
70
+ tokens: 1000000000,
71
+ transaction: '0100000001db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a54770100000000feffffff02b8b4eb0b000000001976a914a457b684d7f0d539a46a45bbc043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fea7ad0402e8bd8ad6d77c88ac92040000',
72
+ vin: 0,
73
+ },
74
+ description: 'A P2SH-P2WPKH input hash to sign uses the default sighash',
75
+ expected: {
76
+ hash: '64f3b0f4dd2bb3aa1ce8566d220cc74dda9df97d8490cc81d89d735c92e59fb6',
77
+ },
78
+ },
79
+ {
80
+ args: {
81
+ script: '21026dccc749adc2a9d0d89497ac511f760f45c47dc5ed9cf352a58ac706453880aeadab210255a9626aebf5e29c0e6538428ba0d1dcf6ca98ffdf086aa8ced5e0d0215ea465ac',
82
+ sighash: 0x03,
83
+ tokens: 4900000000,
84
+ transaction: '0100000002fe3dc9208094f3ffd12645477b3dc56f60ec4fa8e6f5d67c565d1c6b9216b36e0000000000ffffffff0815cf020f013ed6cf91d29f4202e8a58726b1ac6c79da47c23d1bee0a6925f80000000000ffffffff0100f2052a010000001976a914a30741f8145e5acadf23f751864167f32e0963f788ac00000000',
85
+ vin: 1,
86
+ },
87
+ description: 'A single hash with no matching output commits to a zero hash',
88
+ expected: {
89
+ hash: '82dde6e4f1e94d02c2b7ad03d2115d691f48d064e9d52f58194a6637e4194391',
90
+ },
91
+ },
92
+ {
93
+ args: {
94
+ script: '76a91479091972186c449eb1ded22b78e40d009bdf008988ac',
95
+ sighash: 0x01,
96
+ tokens: 1000000000,
97
+ transaction: 'ffffffff01db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a54770100000000feffffff02b8b4eb0b000000001976a914a457b684d7f0d539a46a45bbc043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fea7ad0402e8bd8ad6d77c88ac92040000',
98
+ vin: 0,
99
+ },
100
+ description: 'A negative version number is committed to as signed bytes',
101
+ expected: {
102
+ hash: '78ce09cf80ea77a65379cfca01af97312d9d6d03d011f9d53a0db17decb4a22f',
103
+ },
104
+ },
105
+ {
106
+ args: {
107
+ script: '210255a9626aebf5e29c0e6538428ba0d1dcf6ca98ffdf086aa8ced5e0d0215ea465ac',
108
+ sighash: 0x03,
109
+ tokens: 4900000000,
110
+ transaction: '0100000002fe3dc9208094f3ffd12645477b3dc56f60ec4fa8e6f5d67c565d1c6b9216b36e0000000000ffffffff0815cf020f013ed6cf91d29f4202e8a58726b1ac6c79da47c23d1bee0a6925f80000000000ffffffff0100f2052a010000001976a914a30741f8145e5acadf23f751864167f32e0963f788ac00000000',
111
+ vin: 1,
112
+ },
113
+ description: 'A script code following a code separator is committed to',
114
+ expected: {
115
+ hash: 'fef7bd749cce710c5c052bd796df1af0d935e59cea63736268bcbe2d2134fc47',
116
+ },
117
+ },
118
+ {
119
+ args: {
120
+ script: '0063ab68210392972e2eb617b2388771abe27235fd5ac44af8e61693261550447a4c3e39da98ac',
121
+ sighash: 0x83,
122
+ tokens: 16777215,
123
+ transaction: singleAnyoneCanPayTransaction,
124
+ vin: 0,
125
+ },
126
+ description: 'A single anyone can pay hash commits to the first input',
127
+ expected: {
128
+ hash: 'e9071e75e25b8a1e298a72f0d2e9f4f95a0f5cdf86a533cda597eb402ed13b3a',
129
+ },
130
+ },
131
+ {
132
+ args: {
133
+ script: '68210392972e2eb617b2388771abe27235fd5ac44af8e61693261550447a4c3e39da98ac',
134
+ sighash: 0x83,
135
+ tokens: 16777215,
136
+ transaction: singleAnyoneCanPayTransaction,
137
+ vin: 1,
138
+ },
139
+ description: 'A single anyone can pay hash commits to the second input',
140
+ expected: {
141
+ hash: 'cd72f1f1a433ee9df816857fad88d8ebd97e09a75cd481583eb841c330275e54',
142
+ },
143
+ },
144
+ {
145
+ args: {
146
+ script: 'ad4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e01',
147
+ sighash: 0x01,
148
+ tokens: 200000,
149
+ transaction: '010000000169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f14c1d000000ffffffff0101000000000000000000000000',
150
+ vin: 0,
151
+ },
152
+ description: 'A signature in a script code is not found and deleted',
153
+ expected: {
154
+ hash: '71c9cd9b2869b9c70b01b1f0360c148f42dee72297db312638df136f43311f23',
155
+ },
156
+ },
157
+ {
158
+ args: {
159
+ script: '52af4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c0395960175',
160
+ sighash: 0x01,
161
+ tokens: 200000,
162
+ transaction: '01000000019275cb8d4a485ce95741c013f7c0d28722160008021bb469a11982d47a6628964c1d000000ffffffff010100000000000000000000000000',
163
+ vin: 0,
164
+ },
165
+ description: 'Signatures in a multisig script code are not deleted',
166
+ expected: {
167
+ hash: 'c1628a1e7c67f14ca0c27c06e4fdeec2e6d1a73c7a91d7c046ff83e835aebb72',
168
+ },
169
+ },
170
+ {
171
+ args: {
172
+ script: p2shP2wshWitnessScript,
173
+ sighash: 0x01,
174
+ tokens: 987654321,
175
+ transaction: nativeP2shP2wshTransaction,
176
+ vin: 0,
177
+ },
178
+ description: 'A P2SH-P2WSH input hash to sign is calculated for all',
179
+ expected: {
180
+ hash: '185c0be5263dce5b4bb50a047973c1b6272bfbd0103a89444597dc40b248ee7c',
181
+ },
182
+ },
183
+ {
184
+ args: {
185
+ script: p2shP2wshWitnessScript,
186
+ sighash: 0x02,
187
+ tokens: 987654321,
188
+ transaction: nativeP2shP2wshTransaction,
189
+ vin: 0,
190
+ },
191
+ description: 'A P2SH-P2WSH input hash to sign is calculated for none',
192
+ expected: {
193
+ hash: 'e9733bc60ea13c95c6527066bb975a2ff29a925e80aa14c213f686cbae5d2f36',
194
+ },
195
+ },
196
+ {
197
+ args: {
198
+ script: p2shP2wshWitnessScript,
199
+ sighash: 0x03,
200
+ tokens: 987654321,
201
+ transaction: nativeP2shP2wshTransaction,
202
+ vin: 0,
203
+ },
204
+ description: 'A P2SH-P2WSH input hash to sign is calculated for single',
205
+ expected: {
206
+ hash: '1e1f1c303dc025bd664acb72e583e933fae4cff9148bf78c157d1e8f78530aea',
207
+ },
208
+ },
209
+ {
210
+ args: {
211
+ script: p2shP2wshWitnessScript,
212
+ sighash: 0x81,
213
+ tokens: 987654321,
214
+ transaction: nativeP2shP2wshTransaction,
215
+ vin: 0,
216
+ },
217
+ description: 'A P2SH-P2WSH hash to sign is calculated for all one pays',
218
+ expected: {
219
+ hash: '2a67f03e63a6a422125878b40b82da593be8d4efaafe88ee528af6e5a9955c6e',
220
+ },
221
+ },
222
+ {
223
+ args: {
224
+ script: p2shP2wshWitnessScript,
225
+ sighash: 0x82,
226
+ tokens: 987654321,
227
+ transaction: nativeP2shP2wshTransaction,
228
+ vin: 0,
229
+ },
230
+ description: 'A P2SH-P2WSH hash to sign is calculated for none one pays',
231
+ expected: {
232
+ hash: '781ba15f3779d5542ce8ecb5c18716733a5ee42a6f51488ec96154934e2c890a',
233
+ },
234
+ },
235
+ {
236
+ args: {
237
+ script: p2shP2wshWitnessScript,
238
+ sighash: 0x83,
239
+ tokens: 987654321,
240
+ transaction: nativeP2shP2wshTransaction,
241
+ vin: 0,
242
+ },
243
+ description: 'A P2SH-P2WSH hash to sign is calculated for single one pays',
244
+ expected: {
245
+ hash: '511e8e52ed574121fc1b654970395502128263f62662e076dc6baf05c2e6a99b',
246
+ },
247
+ },
248
+ ];
249
+
250
+ tests.forEach(({args, description, error, expected}) => {
251
+ return test(description, (t, end) => {
252
+ if (!!error) {
253
+ throws(() => v0HashToSign(args), new Error(error), 'Got error');
254
+ } else {
255
+ const res = v0HashToSign(args);
256
+
257
+ deepStrictEqual(res, expected, 'Got expected result');
258
+ }
259
+
260
+ return end();
261
+ });
262
+ });
@@ -1,19 +1,23 @@
1
1
  const componentsOfTransaction = require('./components_of_transaction');
2
2
  const idForTransaction = require('./id_for_transaction');
3
3
  const noLocktimeIdForTransaction = require('./no_locktime_id_for_transaction');
4
+ const nonWitnessHashToSign = require('./non_witness_hash_to_sign');
4
5
  const parseTransaction = require('./parse_transaction');
5
6
  const queryTransactions = require('./query_transactions');
6
7
  const sizeOfTransaction = require('./size_of_transaction');
7
8
  const transactionFromComponents = require('./transaction_from_components');
8
9
  const unsignedTxFromPsbt = require('./unsigned_tx_from_psbt');
10
+ const v0HashToSign = require('./v0_hash_to_sign');
9
11
 
10
12
  module.exports = {
11
13
  componentsOfTransaction,
12
14
  idForTransaction,
13
15
  noLocktimeIdForTransaction,
16
+ nonWitnessHashToSign,
14
17
  parseTransaction,
15
18
  queryTransactions,
16
19
  sizeOfTransaction,
17
20
  transactionFromComponents,
18
21
  unsignedTxFromPsbt,
22
+ v0HashToSign,
19
23
  };
@@ -0,0 +1,203 @@
1
+ const {createHash} = require('crypto');
2
+
3
+ const {numberAsCompactInt} = require('./../numbers');
4
+ const {numberAsLittleEndian} = require('./../numbers');
5
+ const {parsePushBytesCount} = require('./../numbers');
6
+ const parseTransaction = require('./parse_transaction');
7
+
8
+ const anyOnePaysFlag = 0x80;
9
+ const blankedOutput = Buffer.from('ffffffffffffffff00', 'hex');
10
+ const bufferAsHex = buffer => buffer.toString('hex');
11
+ const {concat} = Buffer;
12
+ const countOf = number => numberAsCompactInt({number}).encoded;
13
+ const defaultHashType = 0x01;
14
+ const hashTypes = [0x01, 0x02, 0x03, 0x81, 0x82, 0x83];
15
+ const hexAsBuffer = hex => Buffer.from(hex, 'hex');
16
+ const isHex = n => !!n && !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
17
+ const {isInteger} = Number;
18
+ const isString = n => typeof n === 'string';
19
+ const opCodeSeparator = 0xab;
20
+ const opPushData4 = 78;
21
+ const opZero = 0;
22
+ const outputTypeMask = 0x1f;
23
+ const sha256 = preimage => createHash('sha256').update(preimage).digest();
24
+ const sigHashNone = 2;
25
+ const sigHashSingle = 3;
26
+ const singleByte = 1;
27
+ const sizeOf = script => numberAsCompactInt({number: script.length}).encoded;
28
+ const start = 0;
29
+ const uint32 = n => numberAsLittleEndian({bytes: 4, number: n}).encoded;
30
+ const uint64 = n => numberAsLittleEndian({bytes: 8, number: n}).encoded;
31
+ const zeroSequence = 0;
32
+
33
+ /** Calculate the pre-SegWit transaction hash to sign
34
+
35
+ For P2PK, P2PKH, or bare multisig the script is the output script being spent
36
+
37
+ For P2SH the script is the redeem script that hashes to the output script
38
+
39
+ When a code separator was executed, pass only the script following it, any
40
+ remaining code separators are removed from the script before hashing
41
+
42
+ Signing for a single output requires an output matching the input index
43
+
44
+ {
45
+ script: <Signing Input Script Hex String>
46
+ [sighash]: <Signature Hash Type Number>
47
+ transaction: <Raw Transaction Hex String>
48
+ vin: <Signing Transaction Input Index Number>
49
+ }
50
+
51
+ @throws
52
+ <Error>
53
+
54
+ @returns
55
+ {
56
+ hash: <Hash to Sign Hex String>
57
+ }
58
+ */
59
+ module.exports = ({script, sighash, transaction, vin}) => {
60
+ if (!isString(script) || !isHex(script)) {
61
+ throw new Error('ExpectedScriptCodeHexToCalculateNonWitnessHashToSign');
62
+ }
63
+
64
+ if (!!sighash && !hashTypes.includes(sighash)) {
65
+ throw new Error('ExpectedValidSigHashTypeForNonWitnessHashToSign');
66
+ }
67
+
68
+ if (!isString(transaction) || !isHex(transaction)) {
69
+ throw new Error('ExpectedTransactionHexToCalculateNonWitnessHashToSign');
70
+ }
71
+
72
+ if (!isInteger(vin)) {
73
+ throw new Error('ExpectedInputIndexToCalculateNonWitnessHashToSign');
74
+ }
75
+
76
+ const data = hexAsBuffer(script);
77
+ const decoded = parseTransaction({buffer: hexAsBuffer(transaction)});
78
+ const hashType = sighash || defaultHashType;
79
+ const parts = [];
80
+
81
+ // The signing input is expected to be present in the transaction
82
+ if (!decoded.inputs[vin]) {
83
+ throw new Error('ExpectedMatchingInputToCalculateNonWitnessHashToSign');
84
+ }
85
+
86
+ const isAnyOnePays = !!(hashType & anyOnePaysFlag);
87
+ const outputType = hashType & outputTypeMask;
88
+
89
+ // Signing for a single output requires an output at the input index
90
+ if (outputType === sigHashSingle && !decoded.outputs[vin]) {
91
+ throw new Error('ExpectedMatchingOutputForSingleNonWitnessHashToSign');
92
+ }
93
+
94
+ // Signing for all outputs is any type that isn't for none or a single one
95
+ const isAllOutputs = ![sigHashNone, sigHashSingle].includes(outputType);
96
+
97
+ let offset = start;
98
+
99
+ // The script code is committed to with its code separators removed
100
+ while (offset < data.length) {
101
+ const code = data.readUInt8(offset);
102
+
103
+ // Code separators are dropped from the committed script code
104
+ if (code === opCodeSeparator) {
105
+ offset += singleByte;
106
+
107
+ continue;
108
+ }
109
+
110
+ // Exit early when the code is a simple op code and not a data push
111
+ if (code === opZero || code > opPushData4) {
112
+ parts.push(data.subarray(offset, offset + singleByte));
113
+
114
+ offset += singleByte;
115
+
116
+ continue;
117
+ }
118
+
119
+ const push = parsePushBytesCount({offset, script: data});
120
+
121
+ // The pushed data bytes are expected to be present in the script
122
+ if (!push.bytes || offset + push.bytes.length + push.count > data.length) {
123
+ throw new Error('ExpectedValidScriptCodeForNonWitnessHashToSign');
124
+ }
125
+
126
+ parts.push(data.subarray(offset, offset + push.bytes.length + push.count));
127
+
128
+ offset += push.bytes.length + push.count;
129
+ }
130
+
131
+ const scriptCode = concat(parts);
132
+
133
+ // Only the signing input is committed to when anyone can pay
134
+ const committed = decoded.inputs
135
+ .map(({hash, sequence, vout}, index) => ({hash, index, sequence, vout}))
136
+ .filter(({index}) => !isAnyOnePays || index === vin);
137
+
138
+ // The transaction version number is a signed integer
139
+ const version = numberAsLittleEndian({
140
+ bytes: 4,
141
+ is_signed: true,
142
+ number: decoded.version,
143
+ });
144
+
145
+ // Elements to hash over start with the signed transaction version number
146
+ const elements = [version.encoded];
147
+
148
+ // Write how many inputs there are
149
+ elements.push(countOf(committed.length));
150
+
151
+ // Write the inputs
152
+ committed.forEach(({hash, index, sequence, vout}) => {
153
+ // Write the outpoint being spent
154
+ elements.push(hash);
155
+ elements.push(uint32(vout));
156
+
157
+ // The signing input commits to the script code, others are blanked
158
+ if (index === vin) {
159
+ elements.push(sizeOf(scriptCode));
160
+ elements.push(scriptCode);
161
+ } else {
162
+ elements.push(sizeOf(hexAsBuffer(String())));
163
+ }
164
+
165
+ // Other input sequence numbers are zeroed unless signing for all outputs
166
+ if (index === vin || isAllOutputs) {
167
+ elements.push(uint32(sequence));
168
+ } else {
169
+ elements.push(uint32(zeroSequence));
170
+ }
171
+ });
172
+
173
+ // Signing for a single output only commits up to the matching output
174
+ const outputs = decoded.outputs.slice(
175
+ start,
176
+ outputType === sigHashSingle ? vin + [vin].length : decoded.outputs.length
177
+ );
178
+
179
+ // Write how many outputs there are, none commits to no outputs at all
180
+ elements.push(countOf(outputType === sigHashNone ? start : outputs.length));
181
+
182
+ // Write the outputs, blanking outputs before the single matching output
183
+ if (outputType !== sigHashNone) {
184
+ outputs.forEach(({script, tokens}, index) => {
185
+ // Outputs before the single matching output have negative one values
186
+ if (outputType === sigHashSingle && index < vin) {
187
+ return elements.push(blankedOutput);
188
+ }
189
+
190
+ elements.push(uint64(tokens));
191
+ elements.push(sizeOf(script));
192
+
193
+ return elements.push(script);
194
+ });
195
+ }
196
+
197
+ // Commit to the transaction locktime and the signature hash type
198
+ elements.push(uint32(decoded.locktime));
199
+ elements.push(uint32(hashType));
200
+
201
+ // The hash to sign is the double sha256 hash of the elements
202
+ return {hash: bufferAsHex(sha256(sha256(concat(elements))))};
203
+ };
@@ -0,0 +1,155 @@
1
+ const {createHash} = require('crypto');
2
+
3
+ const {numberAsCompactInt} = require('./../numbers');
4
+ const {numberAsLittleEndian} = require('./../numbers');
5
+ const parseTransaction = require('./parse_transaction');
6
+
7
+ const anyOnePaysFlag = 0x80;
8
+ const bufferAsHex = buffer => buffer.toString('hex');
9
+ const {concat} = Buffer;
10
+ const defaultHashType = 0x01;
11
+ const hashTypes = [0x01, 0x02, 0x03, 0x81, 0x82, 0x83];
12
+ const hexAsBuffer = hex => Buffer.from(hex, 'hex');
13
+ const isHex = n => !!n && !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
14
+ const {isInteger} = Number;
15
+ const isString = n => typeof n === 'string';
16
+ const outputTypeMask = 0x1f;
17
+ const sha256 = preimage => createHash('sha256').update(preimage).digest();
18
+ const sigHashNone = 2;
19
+ const sigHashSingle = 3;
20
+ const sizeOf = script => numberAsCompactInt({number: script.length}).encoded;
21
+ const uint32 = n => numberAsLittleEndian({bytes: 4, number: n}).encoded;
22
+ const uint64 = n => numberAsLittleEndian({bytes: 8, number: n}).encoded;
23
+ const zeroHash = Buffer.alloc(32);
24
+
25
+ /** Calculate the v0 witness transaction hash to sign
26
+
27
+ The script is the BIP 143 script code of the output being spent
28
+
29
+ For P2WPKH the script code is the P2PKH script of the public key hash
30
+
31
+ For P2WSH the script code is the witness script
32
+
33
+ {
34
+ script: <Signing Input Script Hex String>
35
+ [sighash]: <Signature Hash Type Number>
36
+ tokens: <Spending Output Tokens Number>
37
+ transaction: <Raw Transaction Hex String>
38
+ vin: <Signing Transaction Input Index Number>
39
+ }
40
+
41
+ @throws
42
+ <Error>
43
+
44
+ @returns
45
+ {
46
+ hash: <Hash to Sign Hex String>
47
+ }
48
+ */
49
+ module.exports = ({script, sighash, tokens, transaction, vin}) => {
50
+ if (!isString(script) || !isHex(script)) {
51
+ throw new Error('ExpectedScriptCodeHexStringToCalculateV0HashToSign');
52
+ }
53
+
54
+ if (!!sighash && !hashTypes.includes(sighash)) {
55
+ throw new Error('ExpectedValidSignatureHashTypeToCalculateV0HashToSign');
56
+ }
57
+
58
+ if (!isInteger(tokens)) {
59
+ throw new Error('ExpectedSpendTokensNumberToCalculateV0HashToSign');
60
+ }
61
+
62
+ if (!isString(transaction) || !isHex(transaction)) {
63
+ throw new Error('ExpectedTransactionHexStringToCalculateV0HashToSign');
64
+ }
65
+
66
+ if (!isInteger(vin)) {
67
+ throw new Error('ExpectedInputIndexNumberToCalculateV0HashToSign');
68
+ }
69
+
70
+ const decoded = parseTransaction({buffer: hexAsBuffer(transaction)});
71
+ const hashType = sighash || defaultHashType;
72
+ const scriptCode = hexAsBuffer(script);
73
+
74
+ // The signing input is expected to be present in the transaction
75
+ if (!decoded.inputs[vin]) {
76
+ throw new Error('ExpectedMatchingInputToCalculateV0HashToSign');
77
+ }
78
+
79
+ const isAnyOnePays = !!(hashType & anyOnePaysFlag);
80
+ const outputType = hashType & outputTypeMask;
81
+
82
+ // Signing for all outputs is any type that isn't for none or a single one
83
+ const isAllOutputs = ![sigHashNone, sigHashSingle].includes(outputType);
84
+
85
+ // The hash commits to inputs as outpoints and little endian sequences
86
+ const spending = decoded.inputs.map(({hash, sequence, vout}) => ({
87
+ outpoint: concat([hash, uint32(vout)]),
88
+ sequence: uint32(sequence),
89
+ }));
90
+
91
+ const spend = spending[vin];
92
+
93
+ // The transaction version number is a signed integer
94
+ const version = numberAsLittleEndian({
95
+ bytes: 4,
96
+ is_signed: true,
97
+ number: decoded.version,
98
+ });
99
+
100
+ // Elements to hash over start with the signed transaction version number
101
+ const elements = [version.encoded];
102
+
103
+ // Commit to all of the outpoints being spent unless anyone can pay
104
+ if (!isAnyOnePays) {
105
+ const outpoints = spending.map(({outpoint}) => outpoint);
106
+
107
+ elements.push(sha256(sha256(concat(outpoints))));
108
+ } else {
109
+ elements.push(zeroHash);
110
+ }
111
+
112
+ // Commit to all input sequence numbers when signing for all outputs
113
+ if (!isAnyOnePays && isAllOutputs) {
114
+ const sequences = spending.map(({sequence}) => sequence);
115
+
116
+ elements.push(sha256(sha256(concat(sequences))));
117
+ } else {
118
+ elements.push(zeroHash);
119
+ }
120
+
121
+ // Commit to the outpoint, script code, value, sequence of the signing input
122
+ elements.push(spend.outpoint);
123
+ elements.push(sizeOf(scriptCode));
124
+ elements.push(scriptCode);
125
+ elements.push(uint64(tokens));
126
+ elements.push(spend.sequence);
127
+
128
+ const output = decoded.outputs[vin];
129
+
130
+ if (isAllOutputs) {
131
+ // Commit to all of the outputs of the transaction
132
+ const outputs = decoded.outputs.map(({script, tokens}) => {
133
+ return concat([uint64(tokens), sizeOf(script), script]);
134
+ });
135
+
136
+ elements.push(sha256(sha256(concat(outputs))));
137
+ } else if (outputType === sigHashSingle && !!output) {
138
+ // Commit to the matching output when signing for a single output
139
+ elements.push(sha256(sha256(concat([
140
+ uint64(output.tokens),
141
+ sizeOf(output.script),
142
+ output.script,
143
+ ]))));
144
+ } else {
145
+ // There are no outputs committed to when signing for none
146
+ elements.push(zeroHash);
147
+ }
148
+
149
+ // Commit to the transaction locktime and the signature hash type
150
+ elements.push(uint32(decoded.locktime));
151
+ elements.push(uint32(hashType));
152
+
153
+ // The hash to sign is the double sha256 hash of the elements
154
+ return {hash: bufferAsHex(sha256(sha256(concat(elements))))};
155
+ };