@alexbosworth/blockchain 4.5.1 → 4.5.2

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.2
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
  }
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.2"
23
23
  }
@@ -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',
@@ -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
  };