@alexbosworth/blockchain 4.5.1 → 4.5.3

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,6 +1,6 @@
1
1
  # Versions
2
2
 
3
- ## 4.5.1
3
+ ## 4.5.3
4
4
 
5
5
  - `encodeBase58Address`: Add method to convert hash and version to b58 address
6
6
 
@@ -4,6 +4,9 @@ const {isBuffer} = Buffer;
4
4
  const isSafeNumber = n => n <= BigInt(Number.MAX_SAFE_INTEGER);
5
5
  const lengthMarkerOffset = 1;
6
6
  const limitBytes1 = 253;
7
+ const minNumberBytes3 = 253;
8
+ const minNumberBytes5 = 65536;
9
+ const minNumberBytes9 = BigInt(4294967296);
7
10
 
8
11
  /** Convert a compact integer to a regular number
9
12
 
@@ -45,15 +48,36 @@ module.exports = ({encoded, start}) => {
45
48
  case 1:
46
49
  return {bytes, number: size};
47
50
 
48
- case 3:
49
- return {bytes, number: encoded.readUInt16LE(offset + lengthMarkerOffset)};
51
+ case 3: {
52
+ const number = encoded.readUInt16LE(offset + lengthMarkerOffset);
50
53
 
51
- case 5:
52
- return {bytes, number: encoded.readUInt32LE(offset + lengthMarkerOffset)};
54
+ // Exit early with error when the number encoding is not minimal
55
+ if (number < minNumberBytes3) {
56
+ throw new Error('ExpectedMinimallyEncodedCompactIntegerNumber');
57
+ }
58
+
59
+ return {bytes, number};
60
+ }
61
+
62
+ case 5: {
63
+ const number = encoded.readUInt32LE(offset + lengthMarkerOffset);
64
+
65
+ // Exit early with error when the number encoding is not minimal
66
+ if (number < minNumberBytes5) {
67
+ throw new Error('ExpectedMinimallyEncodedCompactIntegerNumber');
68
+ }
69
+
70
+ return {bytes, number};
71
+ }
53
72
  }
54
73
 
55
74
  const number = encoded.readBigUInt64LE(offset + lengthMarkerOffset);
56
75
 
76
+ // Exit early with error when the number encoding is not minimal
77
+ if (number < minNumberBytes9) {
78
+ throw new Error('ExpectedMinimallyEncodedCompactIntegerNumber');
79
+ }
80
+
57
81
  if (!isSafeNumber(number)) {
58
82
  throw new Error('ExpectedSafeSizeEncodedCompactInteger');
59
83
  }
@@ -0,0 +1,65 @@
1
+ const {alloc} = Buffer;
2
+ const byteCountUInt16 = 2;
3
+ const byteCountUInt32 = 4;
4
+ const {concat} = Buffer;
5
+ const {from} = Buffer;
6
+ const {isInteger} = Number;
7
+ const maxDirectPushByteLength = 75;
8
+ const maxUInt8 = 255;
9
+ const maxUInt16 = 65535;
10
+ const maxUInt32 = 4294967295;
11
+ const minimumCount = 0;
12
+ const OP_PUSHDATA1 = 76;
13
+ const OP_PUSHDATA2 = 77;
14
+ const OP_PUSHDATA4 = 78;
15
+
16
+ /** Encode the byte count of a script data push
17
+
18
+ A count up to 75 is a direct single byte, larger counts use OP_PUSHDATA
19
+
20
+ {
21
+ count: <Pushed Data Byte Count Number>
22
+ }
23
+
24
+ @throws
25
+ <Error>
26
+
27
+ @returns
28
+ {
29
+ encoded: <Push Byte Count Encoding Buffer Object>
30
+ }
31
+ */
32
+ module.exports = ({count}) => {
33
+ if (!isInteger(count) || count < minimumCount) {
34
+ throw new Error('ExpectedPushBytesCountNumberToEncode');
35
+ }
36
+
37
+ if (count > maxUInt32) {
38
+ throw new Error('UnexpectedlyLargePushBytesCountToEncode');
39
+ }
40
+
41
+ // Exit early when the byte count fits in a direct single byte push
42
+ if (count <= maxDirectPushByteLength) {
43
+ return {encoded: from([count])};
44
+ }
45
+
46
+ // Exit early when the byte count fits in an OP_PUSHDATA1 push
47
+ if (count <= maxUInt8) {
48
+ return {encoded: from([OP_PUSHDATA1, count])};
49
+ }
50
+
51
+ // Exit early when the byte count fits in an OP_PUSHDATA2 push
52
+ if (count <= maxUInt16) {
53
+ const encodedCount = alloc(byteCountUInt16);
54
+
55
+ encodedCount.writeUInt16LE(count);
56
+
57
+ return {encoded: concat([from([OP_PUSHDATA2]), encodedCount])};
58
+ }
59
+
60
+ const encodedCount = alloc(byteCountUInt32);
61
+
62
+ encodedCount.writeUInt32LE(count);
63
+
64
+ return {encoded: concat([from([OP_PUSHDATA4]), encodedCount])};
65
+ };
package/numbers/index.js CHANGED
@@ -1,4 +1,11 @@
1
1
  const compactIntAsNumber = require('./compact_int_as_number');
2
+ const encodePushBytesCount = require('./encode_push_bytes_count');
2
3
  const numberAsCompactInt = require('./number_as_compact_int');
4
+ const parsePushBytesCount = require('./parse_push_bytes_count');
3
5
 
4
- module.exports = {compactIntAsNumber, numberAsCompactInt};
6
+ module.exports = {
7
+ compactIntAsNumber,
8
+ encodePushBytesCount,
9
+ numberAsCompactInt,
10
+ parsePushBytesCount,
11
+ };
package/package.json CHANGED
@@ -14,10 +14,10 @@
14
14
  "name": "@alexbosworth/blockchain",
15
15
  "repository": {
16
16
  "type": "git",
17
- "url": "https://github.com/alexbosworth/blockchain.git"
17
+ "url": "git+https://github.com/alexbosworth/blockchain.git"
18
18
  },
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.1"
22
+ "version": "4.5.3"
23
23
  }
@@ -1,4 +1,4 @@
1
- const parsePushBytesCount = require('./parse_push_bytes_count');
1
+ const {parsePushBytesCount} = require('./../numbers');
2
2
 
3
3
  const hexAsBuffer = hex => Buffer.from(hex, 'hex');
4
4
  const isHex = n => n !== undefined && !(n.length%2) && /^[0-9A-F]*$/i.test(n);
@@ -1,11 +1,14 @@
1
- const {numberAsCompactInt} = require('./../numbers');
1
+ const {encodePushBytesCount} = require('./../numbers');
2
2
 
3
+ const {alloc} = Buffer;
3
4
  const {concat} = Buffer;
4
- const encode = number => numberAsCompactInt({number}).encoded;
5
- const flatten = arr => arr.reduce((sum, n) => Buffer.concat([sum, n]));
5
+ const encode = count => encodePushBytesCount({count}).encoded;
6
+ const flatten = arr => arr.reduce((s, n) => concat([s, n]), Buffer.alloc(0));
6
7
  const {from} = Buffer;
7
8
  const {isArray} = Array;
8
9
  const {isBuffer} = Buffer;
10
+ const {isInteger} = Number;
11
+ const isOpCode = code => code >= 0 && code <= 255;
9
12
 
10
13
  /** Map array of script buffer elements to an output script
11
14
 
@@ -26,6 +29,16 @@ module.exports = ({elements}) => {
26
29
  throw new Error('ExpectedArrayOfScriptElementsToEncodeScript');
27
30
  }
28
31
 
32
+ // Elements are either data pushes or op code numbers
33
+ if (elements.some(n => !isBuffer(n) && !isInteger(n))) {
34
+ throw new Error('ExpectedDataOrOpCodeScriptElementsToEncodeScript');
35
+ }
36
+
37
+ // Op code elements must be single byte values
38
+ if (elements.some(n => isInteger(n) && !isOpCode(n))) {
39
+ throw new Error('ExpectedSingleByteOpCodeElementToFormOutputScript');
40
+ }
41
+
29
42
  // Convert numbers to buffers and hex data to pushdata
30
43
  const fullScript = elements.map(element => {
31
44
  // Exit early when element is a data push
@@ -25,6 +25,21 @@ const tests = [
25
25
  description: 'A complete encoded number is expected',
26
26
  error: 'ExpectedFullEncodedCompactIntegerToConvertToNumber',
27
27
  },
28
+ {
29
+ args: {encoded: 'fdfc00'},
30
+ description: 'A two byte encoding of a one byte number is rejected',
31
+ error: 'ExpectedMinimallyEncodedCompactIntegerNumber',
32
+ },
33
+ {
34
+ args: {encoded: 'feffff0000'},
35
+ description: 'A four byte encoding of a two byte number is rejected',
36
+ error: 'ExpectedMinimallyEncodedCompactIntegerNumber',
37
+ },
38
+ {
39
+ args: {encoded: 'ffffffffff00000000'},
40
+ description: 'An eight byte encoding of a four byte number is rejected',
41
+ error: 'ExpectedMinimallyEncodedCompactIntegerNumber',
42
+ },
28
43
  {
29
44
  args: {encoded: '00'},
30
45
  description: 'Smallest possible one byte number decoded',
@@ -0,0 +1,82 @@
1
+ const {deepStrictEqual} = require('node:assert').strict;
2
+ const {throws} = require('node:assert').strict;
3
+ const test = require('node:test');
4
+
5
+ const {encodePushBytesCount} = require('./../../numbers');
6
+
7
+ const tests = [
8
+ {
9
+ args: {},
10
+ description: 'A count number is required',
11
+ error: 'ExpectedPushBytesCountNumberToEncode',
12
+ },
13
+ {
14
+ args: {count: -1},
15
+ description: 'A non-negative count number is required',
16
+ error: 'ExpectedPushBytesCountNumberToEncode',
17
+ },
18
+ {
19
+ args: {count: 1.5},
20
+ description: 'An integer count number is required',
21
+ error: 'ExpectedPushBytesCountNumberToEncode',
22
+ },
23
+ {
24
+ args: {count: 4294967296},
25
+ description: 'A count beyond OP_PUSHDATA4 size is rejected',
26
+ error: 'UnexpectedlyLargePushBytesCountToEncode',
27
+ },
28
+ {
29
+ args: {count: 0},
30
+ description: 'A zero count is encoded as a direct byte',
31
+ expected: {encoded: Buffer.from('00', 'hex')},
32
+ },
33
+ {
34
+ args: {count: 75},
35
+ description: 'The largest direct push count is encoded as a direct byte',
36
+ expected: {encoded: Buffer.from('4b', 'hex')},
37
+ },
38
+ {
39
+ args: {count: 76},
40
+ description: 'The smallest OP_PUSHDATA1 count is encoded',
41
+ expected: {encoded: Buffer.from('4c4c', 'hex')},
42
+ },
43
+ {
44
+ args: {count: 255},
45
+ description: 'The largest OP_PUSHDATA1 count is encoded',
46
+ expected: {encoded: Buffer.from('4cff', 'hex')},
47
+ },
48
+ {
49
+ args: {count: 256},
50
+ description: 'The smallest OP_PUSHDATA2 count is encoded',
51
+ expected: {encoded: Buffer.from('4d0001', 'hex')},
52
+ },
53
+ {
54
+ args: {count: 65535},
55
+ description: 'The largest OP_PUSHDATA2 count is encoded',
56
+ expected: {encoded: Buffer.from('4dffff', 'hex')},
57
+ },
58
+ {
59
+ args: {count: 65536},
60
+ description: 'The smallest OP_PUSHDATA4 count is encoded',
61
+ expected: {encoded: Buffer.from('4e00000100', 'hex')},
62
+ },
63
+ {
64
+ args: {count: 4294967295},
65
+ description: 'The largest OP_PUSHDATA4 count is encoded',
66
+ expected: {encoded: Buffer.from('4effffffff', 'hex')},
67
+ },
68
+ ];
69
+
70
+ tests.forEach(({args, description, error, expected}) => {
71
+ return test(description, (t, end) => {
72
+ if (!!error) {
73
+ throws(() => encodePushBytesCount(args), new Error(error), 'Got err');
74
+ } else {
75
+ const res = encodePushBytesCount(args);
76
+
77
+ deepStrictEqual(res, expected, 'Got expected result');
78
+ }
79
+
80
+ return end();
81
+ });
82
+ });
@@ -0,0 +1,67 @@
1
+ const {deepStrictEqual} = require('node:assert').strict;
2
+ const test = require('node:test');
3
+
4
+ const {parsePushBytesCount} = require('./../../numbers');
5
+
6
+ const hexAsBuffer = hex => Buffer.from(hex, 'hex');
7
+
8
+ const tests = [
9
+ {
10
+ args: {offset: 0, script: hexAsBuffer('4f00000000')},
11
+ description: 'An unsupported op code is not parsed as a push',
12
+ expected: undefined,
13
+ },
14
+ {
15
+ args: {offset: 0, script: hexAsBuffer('00')},
16
+ description: 'A zero byte count is parsed as a direct push',
17
+ expected: {bytes: hexAsBuffer('00'), count: 0},
18
+ },
19
+ {
20
+ args: {offset: 0, script: hexAsBuffer('4b' + 'ff'.repeat(75))},
21
+ description: 'The largest direct push byte count is parsed',
22
+ expected: {bytes: hexAsBuffer('4b'), count: 75},
23
+ },
24
+ {
25
+ args: {offset: 0, script: hexAsBuffer('4c4c' + 'ff'.repeat(76))},
26
+ description: 'An OP_PUSHDATA1 byte count is parsed',
27
+ expected: {bytes: hexAsBuffer('4c4c'), count: 76},
28
+ },
29
+ {
30
+ args: {offset: 0, script: hexAsBuffer('4c')},
31
+ description: 'An OP_PUSHDATA1 without a length byte is not parsed',
32
+ expected: {},
33
+ },
34
+ {
35
+ args: {offset: 0, script: hexAsBuffer('4d0001' + 'ff'.repeat(256))},
36
+ description: 'An OP_PUSHDATA2 byte count is parsed',
37
+ expected: {bytes: hexAsBuffer('4d0001'), count: 256},
38
+ },
39
+ {
40
+ args: {offset: 0, script: hexAsBuffer('4dff')},
41
+ description: 'An OP_PUSHDATA2 with a short length is not parsed',
42
+ expected: {},
43
+ },
44
+ {
45
+ args: {offset: 0, script: hexAsBuffer('4e70110100')},
46
+ description: 'An OP_PUSHDATA4 byte count is parsed',
47
+ expected: {bytes: hexAsBuffer('4e70110100'), count: 70000},
48
+ },
49
+ {
50
+ args: {offset: 0, script: hexAsBuffer('4e112233')},
51
+ description: 'An OP_PUSHDATA4 with a short length is not parsed',
52
+ expected: {},
53
+ },
54
+ {
55
+ args: {offset: 2, script: hexAsBuffer('ffff4c4c')},
56
+ description: 'A push byte count is parsed at an offset',
57
+ expected: {bytes: hexAsBuffer('4c4c'), count: 76},
58
+ },
59
+ ];
60
+
61
+ tests.forEach(({args, description, expected}) => {
62
+ return test(description, (t, end) => {
63
+ deepStrictEqual(parsePushBytesCount(args), expected, 'Got expected');
64
+
65
+ return end();
66
+ });
67
+ });
@@ -10,6 +10,46 @@ const tests = [
10
10
  description: 'An array of elements is required',
11
11
  error: 'ExpectedArrayOfScriptElementsToEncodeScript',
12
12
  },
13
+ {
14
+ args: {elements: []},
15
+ description: 'No elements are mapped to an empty script',
16
+ expected: {script: ''},
17
+ },
18
+ {
19
+ args: {elements: [Buffer.alloc(76)]},
20
+ description: 'A data element beyond direct push uses OP_PUSHDATA1',
21
+ expected: {script: '4c4c' + '00'.repeat(76)},
22
+ },
23
+ {
24
+ args: {elements: [Buffer.alloc(256)]},
25
+ description: 'A data element beyond one byte length uses OP_PUSHDATA2',
26
+ expected: {script: '4d0001' + '00'.repeat(256)},
27
+ },
28
+ {
29
+ args: {elements: [Buffer.alloc(70000)]},
30
+ description: 'A data element beyond two byte length uses OP_PUSHDATA4',
31
+ expected: {script: '4e70110100' + '00'.repeat(70000)},
32
+ },
33
+ {
34
+ args: {elements: [300, Buffer.alloc(20)]},
35
+ description: 'Op code elements above a single byte value are rejected',
36
+ error: 'ExpectedSingleByteOpCodeElementToFormOutputScript',
37
+ },
38
+ {
39
+ args: {elements: [-1, Buffer.alloc(20)]},
40
+ description: 'Negative op code elements are rejected',
41
+ error: 'ExpectedSingleByteOpCodeElementToFormOutputScript',
42
+ },
43
+ {
44
+ args: {elements: ['76', Buffer.alloc(20)]},
45
+ description: 'Non number op code elements are rejected',
46
+ error: 'ExpectedDataOrOpCodeScriptElementsToEncodeScript',
47
+ },
48
+ {
49
+ args: {elements: [0, Buffer.alloc(75)]},
50
+ description: 'A maximum length direct data push is encoded',
51
+ expected: {script: '004b' + '00'.repeat(75)},
52
+ },
13
53
  {
14
54
  args: {elements: [118, 169, Buffer.alloc(20), 136, 172]},
15
55
  description: 'Elements are mapped to an output script',
@@ -12,6 +12,97 @@ const tests = [
12
12
  description: 'A transaction hex is required',
13
13
  error: 'ExpectedHexEncodedTransactionToGetComponentsOf',
14
14
  },
15
+ {
16
+ args: {
17
+ transaction: '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff0101000000000000000000000000deadbeef',
18
+ },
19
+ description: 'A tx with extra data on the end is rejected',
20
+ error: 'UnexpectedDataAfterTransactionToGetComponentsOf',
21
+ },
22
+ {
23
+ args: {
24
+ transaction: '01000000010000000000000000000000000000000000000000000000000000000000000000fffffffffd0000ffffffff0101000000000000000000000000',
25
+ },
26
+ description: 'A tx with a non-minimal script length encoding is rejected',
27
+ error: 'ExpectedMinimallyEncodedCompactIntegerNumber',
28
+ },
29
+ {
30
+ args: {
31
+ transaction: '0100',
32
+ },
33
+ description: 'A tx cut short in the version is rejected',
34
+ error: 'ExpectedAdditionalTransactionDataToParse',
35
+ },
36
+ {
37
+ args: {
38
+ transaction: '0100000000',
39
+ },
40
+ description: 'A tx cut short after a zero marker byte is rejected',
41
+ error: 'ExpectedAdditionalTransactionDataToParse',
42
+ },
43
+ {
44
+ args: {
45
+ transaction: '01000000fdffff0000000000000000000000000000000000000000',
46
+ },
47
+ description: 'A tx claiming more inputs than the data holds is rejected',
48
+ error: 'UnexpectedInputCountForTransactionDataLength',
49
+ },
50
+ {
51
+ args: {
52
+ transaction: '01000000010000000000000000000000000000000000000000000000000000000000000000fffffffffc0000000000000000000000000000000000000000000000',
53
+ },
54
+ description: 'A tx claiming a script larger than the data is rejected',
55
+ error: 'ExpectedAdditionalTransactionDataToParse',
56
+ },
57
+ {
58
+ args: {
59
+ transaction: '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00fffffffffdffff0000000000000000',
60
+ },
61
+ description: 'A tx claiming more outputs than the data holds is rejected',
62
+ error: 'UnexpectedOutputCountForTransactionDataLength',
63
+ },
64
+ {
65
+ args: {
66
+ transaction: '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff010100000000000000fc',
67
+ },
68
+ description: 'A tx claiming an output script larger than data is rejected',
69
+ error: 'ExpectedAdditionalTransactionDataToParse',
70
+ },
71
+ {
72
+ args: {
73
+ transaction: '010000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff01010000000000000000fc00000000',
74
+ },
75
+ description: 'A tx claiming more witness elements than data is rejected',
76
+ error: 'UnexpectedWitnessCountForTransactionDataLength',
77
+ },
78
+ {
79
+ args: {
80
+ transaction: '010000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff0101000000000000000001fc00000000',
81
+ },
82
+ description: 'A tx claiming a witness element larger than data is rejected',
83
+ error: 'ExpectedAdditionalTransactionDataToParse',
84
+ },
85
+ {
86
+ args: {
87
+ transaction: '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff010100000000000000000000',
88
+ },
89
+ description: 'A tx cut short in the locktime is rejected',
90
+ error: 'ExpectedAdditionalTransactionDataToParse',
91
+ },
92
+ {
93
+ args: {
94
+ transaction: '010000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff0101000000000000000000' + '00000000',
95
+ },
96
+ description: 'A witness serialized tx with no witness data is rejected',
97
+ error: 'UnexpectedSuperfluousWitnessDataInTransaction',
98
+ },
99
+ {
100
+ args: {
101
+ transaction: '010000000002010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff010100000000000000000101510000' + '0000',
102
+ },
103
+ description: 'A witness serialized tx with an unknown flag is rejected',
104
+ error: 'UnexpectedWitnessFlagByteValueInTransaction',
105
+ },
15
106
  {
16
107
  args: {
17
108
  transaction: '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000',
@@ -12,6 +12,42 @@ const tests = [
12
12
  description: 'A block is required',
13
13
  error: 'ExpectedHexEncodedBlockToQueryTransactions',
14
14
  },
15
+ {
16
+ args: {block: '00'.repeat(80), outputs: []},
17
+ description: 'A block with transaction data is required',
18
+ error: 'ExpectedBlockHeaderAndTransactionsToQueryTransactions',
19
+ },
20
+ {
21
+ args: {
22
+ block: '00'.repeat(80) + 'fdffff' + '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff010100000000000000016a00000000',
23
+ outputs: [],
24
+ },
25
+ description: 'A block claiming more txs than the data holds is rejected',
26
+ error: 'UnexpectedTransactionCountForBlockDataLength',
27
+ },
28
+ {
29
+ args: {
30
+ block: '00'.repeat(80) + '01' + '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff010100000000000000016a00000000' + 'ff',
31
+ outputs: [],
32
+ },
33
+ description: 'A block with extra data after the transactions is rejected',
34
+ error: 'UnexpectedDataAfterBlockTransactions',
35
+ },
36
+ {
37
+ args: {
38
+ block: '00'.repeat(80) + 'fd0201' + '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff010100000000000000016a00000000'.repeat(258),
39
+ outputs: ['6a'],
40
+ },
41
+ description: 'A block with a multi-byte transaction count is queried',
42
+ expected: {
43
+ outputs: Array.from({length: 258}, () => ({
44
+ script: '6a',
45
+ tokens: 1,
46
+ transaction_id: 'ac73f5333d533da8ff546e9e9fa255977fe117d025eef4bcf3f88b7010ca960d',
47
+ transaction_vout: 0,
48
+ })),
49
+ },
50
+ },
15
51
  {
16
52
  args: {
17
53
  block: '00008020b43ebc848b8a78430f745b58dd0cfecb5a41fda1f9a0793833a98dad00000000cbbb00aa6ab7ea52d99e87088d2d80e7ca27f217f4cb8bc7ac635f17a1ff336900ccd364f4422e1906713cdb07010000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff1a03bcb725012013090909200909200904686700c4ee5902000000ffffffff022162250000000000160014820d4a343a44e915c36494995c2899abe37418930000000000000000266a24aa21a9ed78afc412c2c7c1b3135c2a2473a6837068c5ea891e5068d396041057114a749501200000000000000000000000000000000000000000000000000000000000000000000000000100000001ce99c6498760022c4a268bb2bd553b71c5dd7e705ad47704ca2b8cdf72b2d755030000006b483045022100ca65bd58a725c83c3420874e4e0017562ef451f1df17eb42cfd35ee9dd28f98902204a6aafb47a2e1492e50cb0c7038000741d952e3770f9a1f9c9a6229c124e5e790121037435c194e9b01b3d7f7a2802d6684a3af68d05bbf4ec8f17021980d777691f1dfdffffff040000000000000000536a4c5054325bb3a276c4f8c7ecdccd704cf9a0e691db1364e66648672e23871de8b005816f3ec0ecda15e15dbec4e7f2be15f1e4e52e72c187deb36bd3b89d9793ea0e7c71e00025b7b9000f0025b12400114a10270000000000001976a914000000000000000000000000000000000000000088ac10270000000000001976a914000000000000000000000000000000000000000088acb2e8ae08000000001976a914ba27f99e007c7f605a8305e318c1abde3cd220ac88ac00000000010000000001014d4f50b9002361be3b82382e628e41ec29ffb5a28abec8a59ebbf4f28ba4675401000000171600142642be55762762143195a7eb3b965fcc47df9000ffffffff013b0d0000000000001600146ad03f5c84f201cbcbae045ffb9a8b9d769f83d40247304402205993d5c216bcb968c8ed1a99d67a3e4bcf54434c29ffc1bd72c49769d4814f6302200a40821effc9c1fb00d6de454b35244cb70f294b7f3971fee796b9a302f7efa1012103eadead8e5b3a54e36ad936096bd4ca8960ef753b2d81db9afb4ce7a458155e2e0000000002000000000101a4a1f7f07d0d95cd22e7039646133cb29d7b3c5ec55f86720f9cfbd0aa5d155001000000000000000002102700000000000017a91423269e856a01136288e09d8ea5049f5e64d56399872ca218000000000016001456ddc1cec4c3cf468646d6cc2d531d232d43dd4502473044022069f7f79e6c8cfe3ad43e9a5e3da0d77f93169bd4d98a9ef1f5d521340510d688022053b18b1914a40b2b60cb453d8421fa8f2d1c05c9f084b90f38092379276281c701210216243ae4738f200518bf8f0204f6b95e408aadd65f553bad98f0f8a9fd7472eb0000000002000000000102c9f48fe21843a24377835106e94e3ecee80e128027a4fa84d9371df56464b0190000000000fdffffffc9f48fe21843a24377835106e94e3ecee80e128027a4fa84d9371df56464b0190100000000fdffffff01e7170000000000001976a91459cada50314c829e19f5a7786f8ee0d4987f429d88ac0247304402204d578466dad41a451ac42a58bfb15b4ede988181ca384d3d7dfc158289dc369402205b35dd90b83ed4b02ccd300b370d57d3f919d4a100280ba9b2b68feef6f75e720121039757fd1ca6e33c3433cd8de13178dfd50f5688b688301a932cc4eba38e85e80c02473044022052dbdb28b87d8bed9edb8abc664452ad4bd85dd0c068f61a4bffa92a66748d090220674e642420b027c00dc3a0fcec74f53fdd31b9bcd76d20397ef9c8f61a45788c01210251db63b01e13ff7656cb606d732970b4760466162c83e041e018846c627760a1bab7250002000000011e43091d1b554f7e3ce175241aba175bf797996dda991bfdc34fc5cb8298ee5e010000006a473044022027af54aec1a603c1260312241f6cc27d49db4d79cb946a3fb56aff6c8e5e4132022022d3954e49699d369480624c3e8397fd361d9baffdd700d1e9882b465e523b670121021bc2b79284dca29127ed41021571fd3026157c01b4fef8824e94976592b165b3fdffffff0280d725000000000016001475f1d3e5088db87f9a336287cb55142d2062ada3ab72000000000000160014f5e5e9b3af38635bf6992f9732206d0ccb421e9ebbb7250001000000017c1194e8b17d9d26aaba8a78c2cd84490d96d5405619da3b2a9f454860b18911010000006b483045022100e1a219e719575a51e70ccfb06a1968dfd6d2055a3c46664ede399b8a3aab7f8902204b7994dec9e0a6f74e4db0d5a0a06738bd608476160c530392f8f220ad3cb4c6012103ef3f06ff6ea92d1b0a4693ed3f83ad45740b02259739e6427209cb88581416a0ffffffff0278350000000000001976a914e830afe90f87e5c561df7e66ef530d4dd8ea182088ac55d61300000000001976a914fe0f6279060ba6bc6a8b4375d7de8cf8b35a683788ac00000000',
@@ -82,6 +82,40 @@ const tests = [
82
82
  description: 'A version number is required',
83
83
  error: 'ExpectedVersionNumberToFormTransactionFromComponents',
84
84
  },
85
+ {
86
+ args: {
87
+ inputs: [{
88
+ id: '0000000000000000000000000000000000000000000000000000000000000000',
89
+ script: '',
90
+ sequence: 4294967295,
91
+ vout: 0,
92
+ witness: ['zz'],
93
+ }],
94
+ locktime: 0,
95
+ outputs: [{script: '6a', tokens: 1}],
96
+ version: 1,
97
+ },
98
+ description: 'Hex encoded witness stack elements are expected',
99
+ error: 'ExpectedHexEncodedWitnessElementsToFormTransaction',
100
+ },
101
+ {
102
+ args: {
103
+ inputs: [{
104
+ id: '0000000000000000000000000000000000000000000000000000000000000000',
105
+ script: '',
106
+ sequence: 4294967295,
107
+ vout: 4294967295,
108
+ witness: [],
109
+ }],
110
+ locktime: 0,
111
+ outputs: [{script: '6a', tokens: 1}],
112
+ version: 1,
113
+ },
114
+ description: 'Empty witness stacks are encoded as a legacy transaction',
115
+ expected: {
116
+ transaction: '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff010100000000000000016a00000000',
117
+ },
118
+ },
85
119
  {
86
120
  args: {
87
121
  inputs: [{
@@ -12,6 +12,23 @@ const tests = [
12
12
  description: 'A psbt is required',
13
13
  error: 'ExpectedPsbtToGetUnsignedTransaction',
14
14
  },
15
+ {
16
+ args: {psbt: '70736274ff01'},
17
+ description: 'A key type byte is expected after the psbt start bytes',
18
+ error: 'ExpectedUnsignedTransactionKeyTypeInPsbt',
19
+ },
20
+ {
21
+ args: {psbt: '70736274ff0101'},
22
+ description: 'An unsigned transaction global key type is expected',
23
+ error: 'ExpectedUnsignedTransactionKeyTypeInPsbt',
24
+ },
25
+ {
26
+ args: {
27
+ psbt: '70736274ff01003e01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff010100000000000000016a0000000000',
28
+ },
29
+ description: 'The declared unsigned transaction length must match',
30
+ error: 'UnexpectedByteLengthOfPsbtUnsignedTransaction',
31
+ },
15
32
  {
16
33
  args: {
17
34
  psbt: '0200000001268171371edff285e937adeea4b37b78000c0566cbb3ad64641713ca42171bf6000000006a473044022070b2245123e6bf474d60c5b50c043d4c691a5d2435f09a34a7662a9dc251790a022001329ca9dacf280bdf30740ec0390422422c81cb45839457aeb76fc12edd95b3012102657d118d3357b8e0f4c2cd46db7b39f6d9c38d9a70abcb9b2de5dc8dbfe4ce31feffffff02d3dff505000000001976a914d0c59903c5bac2868760e90fd521a4665aa7652088ac00e1f5050000000017a9143545e6e33b832c47050f24d3eeb93c9c03948bc787b32e1300',
@@ -36,7 +36,14 @@ module.exports = ({transaction}) => {
36
36
  throw new Error('ExpectedHexEncodedTransactionToGetComponentsOf');
37
37
  }
38
38
 
39
- const details = parseTransaction({buffer: hexAsBuffer(transaction)});
39
+ const buffer = hexAsBuffer(transaction);
40
+
41
+ const details = parseTransaction({buffer});
42
+
43
+ // Exit early with error when there is extra data after the transaction
44
+ if (details.bytes.length !== buffer.length) {
45
+ throw new Error('UnexpectedDataAfterTransactionToGetComponentsOf');
46
+ }
40
47
 
41
48
  return {
42
49
  inputs: details.inputs.map(input => ({
@@ -7,11 +7,15 @@ const byteCountInt64 = 8;
7
7
  const byteCountMarkerFlag = 2;
8
8
  const byteCountNoMarkerFlag = 0;
9
9
  const decodeCompactInt = (b, o) => compactIntAsNumber({encoded: b, start: o});
10
+ const defaultFlagValue = 0;
10
11
  const defaultLocktime = 0;
11
12
  const defaultStartIndex = 0;
12
13
  const defaultWitnessCount = 0;
13
14
  const {isBuffer} = Buffer;
15
+ const minByteLengthInput = 41;
16
+ const minByteLengthOutput = 9;
14
17
  const times = n => [...Array(n).keys()];
18
+ const witnessFlagValue = 1;
15
19
 
16
20
  /** Parse a raw transaction out of a buffer at a specific offset start
17
21
 
@@ -48,6 +52,16 @@ module.exports = args => {
48
52
 
49
53
  let offset = start;
50
54
 
55
+ // Make sure there is enough data remaining to read a count of bytes
56
+ const guardRead = bytes => {
57
+ if (args.buffer.length - offset < bytes) {
58
+ throw new Error('ExpectedAdditionalTransactionDataToParse');
59
+ }
60
+ };
61
+
62
+ // Confirm the transaction version bytes are present
63
+ guardRead(byteCountInt32);
64
+
51
65
  // Transaction version is a signed 4 byte integer
52
66
  const version = args.buffer.readInt32LE(offset);
53
67
 
@@ -56,12 +70,25 @@ module.exports = args => {
56
70
  // For SegWit transactions, the next 2 bytes would be a marker and flag
57
71
  const flagSplit = offset + byteCountInt8;
58
72
 
73
+ // Confirm the marker byte is present
74
+ guardRead(byteCountInt8);
75
+
59
76
  const marker = args.buffer.readUInt8(offset);
60
77
 
61
- const flag = args.buffer.readUInt8(flagSplit);
78
+ // A zero marker byte means a witness flag byte follows the marker
79
+ if (!marker) {
80
+ guardRead(byteCountMarkerFlag);
81
+ }
82
+
83
+ const flag = !marker ? args.buffer.readUInt8(flagSplit) : defaultFlagValue;
62
84
 
63
85
  // The presence of the marker and flag indicates SegWit tx encoding
64
- const isSegWit = !marker && !!flag;
86
+ const isSegWit = !marker && flag === witnessFlagValue;
87
+
88
+ // A zero marker byte requires the BIP 144 witness flag value to follow
89
+ if (!marker && !isSegWit) {
90
+ throw new Error('UnexpectedWitnessFlagByteValueInTransaction');
91
+ }
65
92
 
66
93
  // When tx isn't SegWit though, the bytes are not marker and flag
67
94
  offset += isSegWit ? byteCountMarkerFlag : byteCountNoMarkerFlag;
@@ -70,11 +97,19 @@ module.exports = args => {
70
97
 
71
98
  offset += inputsCount.bytes;
72
99
 
100
+ // Confirm the data could possibly contain the claimed count of inputs
101
+ if (inputsCount.number * minByteLengthInput > args.buffer.length - offset) {
102
+ throw new Error('UnexpectedInputCountForTransactionDataLength');
103
+ }
104
+
73
105
  // For SegWit the witness stacks will be at the end of the transaction
74
106
  const witnessCount = isSegWit ? inputsCount.number : defaultWitnessCount;
75
107
 
76
108
  // Read in the inputs
77
109
  const inputs = times(inputsCount.number).map(i => {
110
+ // Confirm the outpoint hash and output index bytes are present
111
+ guardRead(byteCountHash + byteCountInt32);
112
+
78
113
  // The hash is the internal byte order hash of the tx being spent
79
114
  const hash = args.buffer.subarray(offset, offset + byteCountHash);
80
115
 
@@ -90,6 +125,9 @@ module.exports = args => {
90
125
 
91
126
  offset += scriptLength.bytes;
92
127
 
128
+ // Confirm the script and sequence bytes are present
129
+ guardRead(scriptLength.number + byteCountInt32);
130
+
93
131
  // Scripts are variable byte length
94
132
  const script = args.buffer.subarray(offset, offset + scriptLength.number);
95
133
 
@@ -107,8 +145,16 @@ module.exports = args => {
107
145
 
108
146
  offset += outputsCount.bytes;
109
147
 
148
+ // Confirm the data could possibly contain the claimed count of outputs
149
+ if (outputsCount.number * minByteLengthOutput > args.buffer.length - offset) {
150
+ throw new Error('UnexpectedOutputCountForTransactionDataLength');
151
+ }
152
+
110
153
  // Read in the outputs of the transaction
111
154
  const outputs = times(outputsCount.number).map(i => {
155
+ // Confirm the output value bytes are present
156
+ guardRead(byteCountInt64);
157
+
112
158
  // The value being spent
113
159
  const value = args.buffer.readBigUInt64LE(offset);
114
160
 
@@ -119,6 +165,9 @@ module.exports = args => {
119
165
 
120
166
  offset += scriptLength.bytes;
121
167
 
168
+ // Confirm the output script bytes are present
169
+ guardRead(scriptLength.number);
170
+
122
171
  const script = args.buffer.subarray(offset, offset + scriptLength.number);
123
172
 
124
173
  offset += scriptLength.number;
@@ -144,6 +193,11 @@ module.exports = args => {
144
193
 
145
194
  offset += stackElementsCount.bytes;
146
195
 
196
+ // Confirm the data could possibly contain the claimed stack elements
197
+ if (stackElementsCount.number > args.buffer.length - offset) {
198
+ throw new Error('UnexpectedWitnessCountForTransactionDataLength');
199
+ }
200
+
147
201
  // Read in the witness stack elements
148
202
  const elements = [...Array(stackElementsCount.number).keys()].map(i => {
149
203
  // Stack elements are variable length
@@ -151,6 +205,9 @@ module.exports = args => {
151
205
 
152
206
  offset += elementLength.bytes;
153
207
 
208
+ // Confirm the witness stack element bytes are present
209
+ guardRead(elementLength.number);
210
+
154
211
  const item = args.buffer.subarray(offset, offset + elementLength.number);
155
212
 
156
213
  offset += elementLength.number;
@@ -162,7 +219,14 @@ module.exports = args => {
162
219
  return inputs[i].witness = elements;
163
220
  });
164
221
 
222
+ // Witness serialization requires a non-empty witness on some input
223
+ if (isSegWit && !inputs.some(input => !!input.witness.length)) {
224
+ throw new Error('UnexpectedSuperfluousWitnessDataInTransaction');
225
+ }
226
+
165
227
  // The final element is the 4 byte transaction nLockTime
228
+ guardRead(byteCountInt32);
229
+
166
230
  const locktime = args.buffer.readUInt32LE(offset);
167
231
 
168
232
  offset += byteCountInt32;
@@ -1,12 +1,15 @@
1
1
  const {createHash} = require('crypto');
2
2
 
3
+ const {compactIntAsNumber} = require('./../numbers');
4
+
3
5
  const {idForTransactionComponents} = require('./../hashes');
4
6
  const parseTransaction = require('./parse_transaction');
5
7
 
6
8
  const bufferAsHex = buffer => buffer.toString('hex');
7
9
  const hexAsBuffer = hex => Buffer.from(hex, 'hex');
8
10
  const {isArray} = Array;
9
- const transactionsStartIndex = 81;
11
+ const minTxByteLength = 60;
12
+ const transactionsStartIndex = 80;
10
13
 
11
14
  /** Find matching transactions within a block
12
15
 
@@ -38,11 +41,29 @@ module.exports = ({block, outputs}) => {
38
41
  }
39
42
 
40
43
  const buffer = hexAsBuffer(block);
41
- let cursor = transactionsStartIndex;
44
+
45
+ // Exit early with error when the block header data is cut short
46
+ if (buffer.length <= transactionsStartIndex) {
47
+ throw new Error('ExpectedBlockHeaderAndTransactionsToQueryTransactions');
48
+ }
49
+
50
+ // A compact int count of transactions follows the block header
51
+ const txCount = compactIntAsNumber({
52
+ encoded: buffer,
53
+ start: transactionsStartIndex,
54
+ });
55
+
56
+ let cursor = transactionsStartIndex + txCount.bytes;
42
57
  const hits = [];
58
+ let remaining = txCount.number;
59
+
60
+ // Confirm the data could possibly contain the claimed count of txs
61
+ if (txCount.number * minTxByteLength > buffer.length - cursor) {
62
+ throw new Error('UnexpectedTransactionCountForBlockDataLength');
63
+ }
43
64
 
44
65
  // Iterate forward through the block, parsing txs and looking for hits
45
- while (cursor < buffer.length) {
66
+ while (remaining--) {
46
67
  const tx = parseTransaction({buffer, start: cursor});
47
68
 
48
69
  // Look at the transaction outputs to see if there is a match
@@ -72,5 +93,10 @@ module.exports = ({block, outputs}) => {
72
93
  cursor += tx.bytes.length;
73
94
  }
74
95
 
96
+ // Exit early with error when there is extra data after the transactions
97
+ if (cursor !== buffer.length) {
98
+ throw new Error('UnexpectedDataAfterBlockTransactions');
99
+ }
100
+
75
101
  return {outputs: hits};
76
102
  };
@@ -8,7 +8,7 @@ const {concat} = Buffer;
8
8
  const encodeCount = number => numberAsCompactInt({number}).encoded;
9
9
  const hexAsBuffer = hex => Buffer.from(hex, 'hex');
10
10
  const {isArray} = Array;
11
- const isHex = n => !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
11
+ const isHex = n => typeof n === 'string' && !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
12
12
  const isTxId = n => /^[0-9A-F]{64}$/i.test(n);
13
13
  const markerAndFlag = Buffer.from([0x00, 0x01]);
14
14
  const txIdAsTxHash = id => hexAsBuffer(id).reverse();
@@ -52,6 +52,11 @@ module.exports = ({inputs, locktime, outputs, version}) => {
52
52
  throw new Error('ExpectedHexEncodedInputScriptsToFormTransaction');
53
53
  }
54
54
 
55
+ // Confirm witness stack elements are hex encoded when present
56
+ if (inputs.some(n => isArray(n.witness) && !n.witness.every(isHex))) {
57
+ throw new Error('ExpectedHexEncodedWitnessElementsToFormTransaction');
58
+ }
59
+
55
60
  if (locktime === undefined) {
56
61
  throw new Error('ExpectedLocktimeToFormTransactionFromComponents');
57
62
  }
@@ -68,8 +73,8 @@ module.exports = ({inputs, locktime, outputs, version}) => {
68
73
  throw new Error('ExpectedVersionNumberToFormTransactionFromComponents');
69
74
  }
70
75
 
71
- // The presence of any input witness indicates SegWit tx encoding
72
- const isSegWit = !!inputs.find(input => isArray(input.witness));
76
+ // Only use SegWit encoding when an input has witness stack elements
77
+ const isSegWit = inputs.some(n => isArray(n.witness) && !!n.witness.length);
73
78
 
74
79
  const elements = [];
75
80
 
@@ -2,7 +2,9 @@ const {compactIntAsNumber} = require('./../numbers');
2
2
  const parseTransaction = require('./parse_transaction');
3
3
 
4
4
  const decodeCompactInt = (b, o) => compactIntAsNumber({encoded: b, start: o});
5
+ const globalUnsignedTxKeyType = 0;
5
6
  const hexAsBuffer = hex => Buffer.from(hex, 'hex');
7
+ const isHex = n => !!n && !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
6
8
  const psbtStartBytes = Buffer.from([0x70, 0x73, 0x62, 0x74, 0xff, 0x01]);
7
9
 
8
10
  /** Get the unsigned transaction out of a PSBT
@@ -20,7 +22,7 @@ const psbtStartBytes = Buffer.from([0x70, 0x73, 0x62, 0x74, 0xff, 0x01]);
20
22
  }
21
23
  */
22
24
  module.exports = ({psbt}) => {
23
- if (!psbt) {
25
+ if (!isHex(psbt)) {
24
26
  throw new Error('ExpectedPsbtToGetUnsignedTransaction');
25
27
  }
26
28
 
@@ -34,14 +36,32 @@ module.exports = ({psbt}) => {
34
36
  throw new Error('ExpectedKnownPsbtStartBytesToGetUnsignedTransaction');
35
37
  }
36
38
 
39
+ // Exit early with error when there is no key type byte to read
40
+ if (psbtData.length <= psbtStartBytes.length) {
41
+ throw new Error('ExpectedUnsignedTransactionKeyTypeInPsbt');
42
+ }
43
+
44
+ // The single byte key of the first global pair follows the start bytes
45
+ const keyType = psbtData.readUInt8(psbtStartBytes.length);
46
+
47
+ // The first global key is expected to be the unsigned transaction type
48
+ if (keyType !== globalUnsignedTxKeyType) {
49
+ throw new Error('ExpectedUnsignedTransactionKeyTypeInPsbt');
50
+ }
51
+
37
52
  // The next byte will be a compact int number that describes the tx length
38
- const keySize = decodeCompactInt(psbtData, psbtStartBytes.length + 1).bytes;
53
+ const valueSize = decodeCompactInt(psbtData, psbtStartBytes.length + 1);
39
54
 
40
55
  // Read in the transaction from the global value bytes
41
56
  const {bytes} = parseTransaction({
42
57
  buffer: psbtData,
43
- start: psbtStartBytes.length + keySize + 1,
58
+ start: psbtStartBytes.length + valueSize.bytes + 1,
44
59
  });
45
60
 
61
+ // Confirm the unsigned transaction matches its declared value length
62
+ if (bytes.length !== valueSize.number) {
63
+ throw new Error('UnexpectedByteLengthOfPsbtUnsignedTransaction');
64
+ }
65
+
46
66
  return {transaction: bytes};
47
67
  };
@@ -1,15 +0,0 @@
1
- const {strictEqual} = require('node:assert').strict;
2
- const test = require('node:test');
3
-
4
- const parsePushBytesCount = require('./../../script/parse_push_bytes_count');
5
-
6
- test('An unsupported op code is not parsed as a push', (t, end) => {
7
- const res = parsePushBytesCount({
8
- offset: 0,
9
- script: Buffer.from('4f00000000', 'hex'),
10
- });
11
-
12
- strictEqual(res, undefined, 'Got no push bytes count');
13
-
14
- return end();
15
- });
File without changes