@alexbosworth/blockchain 4.11.0 → 5.0.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,27 @@
1
1
  # Versions
2
2
 
3
+ ## 5.0.0
4
+
5
+ ### Breaking Changes
6
+
7
+ - `decodeBase58`: Strings longer than 1,024 characters are now rejected
8
+ - `idForTransactionComponents`, `transactionFromComponents`: Inputs now
9
+ require `sequence` and `vout` numbers, they were encoded as zero if missing
10
+ - `idForTransactionComponents`, `transactionFromComponents`: Output `tokens`
11
+ must be a number or a bigint, numeric strings are now rejected
12
+ - `nonWitnessHashToSign`, `v0HashToSign`: A `sighash` of `0` or `null` is now
13
+ rejected instead of defaulting to `SIGHASH_ALL`
14
+ - `nonWitnessHashToSign`, `v0HashToSign`: Data after the end of the
15
+ `transaction` is now rejected
16
+ - `unsignedTxFromPsbt`: A global transaction with input scripts or witnesses
17
+ is now rejected
18
+ - `v0HashToSign`: `tokens` above the safe integer limit are now rejected
19
+
20
+ ## 4.12.0
21
+
22
+ - `queryTransactions`: Add `ids` argument to find transactions by their id
23
+ - `queryTransactions`: Add `transactions` result with raw matching transactions
24
+
3
25
  ## 4.11.0
4
26
 
5
27
  - `decodeWif`: Add method to decode a WIF encoded private key
package/README.md CHANGED
@@ -97,7 +97,8 @@ Decode a base58check encoded string into its payload
97
97
  }
98
98
 
99
99
  @throws
100
- <Error> when the string has invalid characters or a bad checksum
100
+ <Error> when the string is over 1,024 characters, has invalid characters
101
+ or a bad checksum
101
102
 
102
103
  @returns
103
104
  {
@@ -575,7 +576,8 @@ Find matching transactions within a block
575
576
 
576
577
  {
577
578
  block: <Hex Encoded Raw Block String>
578
- outputs: [<Output Script Hex String>]
579
+ [ids]: [<Transaction Id Hex String>]
580
+ [outputs]: [<Output Script Hex String>]
579
581
  }
580
582
 
581
583
  @throws
@@ -589,6 +591,10 @@ Find matching transactions within a block
589
591
  transaction_id: <Transaction Id Hex String>
590
592
  transaction_vout: <Transaction Output Index Number>
591
593
  }]
594
+ transactions: [{
595
+ id: <Transaction Id Hex String>
596
+ transaction: <Hex Encoded Raw Transaction String>
597
+ }]
592
598
  }
593
599
 
594
600
  ### scriptAsScriptElements
@@ -5,8 +5,10 @@ const byteMask = 0xff;
5
5
  const {ceil} = Math;
6
6
  const countChecksumBytes = 4;
7
7
  const leadingZeroCharCode = 0x31;
8
+ const maxEncodedLength = 1024;
8
9
  const notFoundIndex = -1;
9
10
  const sha256 = preimage => createHash('sha256').update(preimage).digest();
11
+ const wipe = bytes => bytes.fill(0);
10
12
 
11
13
  /** Decode a base58check encoded string into its payload
12
14
 
@@ -15,7 +17,8 @@ const sha256 = preimage => createHash('sha256').update(preimage).digest();
15
17
  }
16
18
 
17
19
  @throws
18
- <Error> when the string has invalid characters or a bad checksum
20
+ <Error> when the string is over 1,024 characters, has invalid characters
21
+ or a bad checksum
19
22
 
20
23
  @returns
21
24
  {
@@ -35,6 +38,11 @@ module.exports = ({encoded}) => {
35
38
  throw new Error('ExpectedNonEmptyBase58CheckStringToDecode');
36
39
  }
37
40
 
41
+ // Exit early with error on long strings, decoding cost grows quadratically
42
+ if (str.length > maxEncodedLength) {
43
+ throw new Error('ExpectedShorterBase58CheckStringToDecode');
44
+ }
45
+
38
46
  let bytesLength = 0;
39
47
  let countLeadingZeros = 0;
40
48
  let index = 0;
@@ -56,6 +64,9 @@ module.exports = ({encoded}) => {
56
64
  const value = base58Alphabet.indexOf(str[index]);
57
65
 
58
66
  if (value === notFoundIndex) {
67
+ // The partially decoded bytes could be sensitive
68
+ wipe(working);
69
+
59
70
  throw new Error('ExpectedAllBase58CharactersInBase58CheckString');
60
71
  }
61
72
 
@@ -96,8 +107,14 @@ module.exports = ({encoded}) => {
96
107
  // Copy the meaningful bytes into the final decoded data
97
108
  decoded.set(dataBytes, countLeadingZeros);
98
109
 
110
+ // The working bytes are copied out and could be sensitive, wipe them
111
+ wipe(working);
112
+
99
113
  // Exit early with error when we don't have both a payload and checksum
100
114
  if (decoded.length <= countChecksumBytes) {
115
+ // The decoded bytes could be sensitive, wipe them before exiting
116
+ wipe(decoded);
117
+
101
118
  throw new Error('ExpectedPayloadAndChecksumInBase58CheckString');
102
119
  }
103
120
 
@@ -110,10 +127,18 @@ module.exports = ({encoded}) => {
110
127
  // Calculate the checksum for the given payload
111
128
  const payloadCheck = sha256(sha256(payload)).subarray(0, countChecksumBytes);
112
129
 
130
+ const isValid = checksum.equals(payloadCheck);
131
+
132
+ // Only a payload that matches its checksum is copied out to be returned
133
+ const result = isValid ? Buffer.from(payload) : undefined;
134
+
135
+ // The decoded bytes could be sensitive, wipe them now they are copied out
136
+ wipe(decoded);
137
+
113
138
  // Exit early with error when the double SHA256 of payload doesn't match
114
- if (!checksum.equals(payloadCheck)) {
139
+ if (!isValid) {
115
140
  throw new Error('ExpectedValidPayloadChecksumInBase58CheckString');
116
141
  }
117
142
 
118
- return {payload: Buffer.from(payload)};
143
+ return {payload: result};
119
144
  };
@@ -1,6 +1,7 @@
1
1
  const bech32Type = require('./bech32_type');
2
2
 
3
3
  const alphabet = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
4
+ const isPrintableAscii = n => /^[\x21-\x7e]*$/.test(n);
4
5
  const knownPrefixes = ['bc', 'tb', 'bcrt'];
5
6
  const lengthSeparator = 1;
6
7
  const lengthChecksum = 6;
@@ -41,6 +42,11 @@ module.exports = ({encoded}) => {
41
42
  throw new Error('ExpectedLongerBech32EncodedStringToDecode');
42
43
  }
43
44
 
45
+ // Characters outside of ASCII can change case into alphabet characters
46
+ if (!isPrintableAscii(encoded)) {
47
+ throw new Error('ExpectedPrintableAsciiCharactersInBech32String');
48
+ }
49
+
44
50
  const converted = encoded.toLowerCase();
45
51
 
46
52
  if (encoded !== converted && encoded !== encoded.toUpperCase()) {
@@ -26,6 +26,11 @@ module.exports = ({block}) => {
26
26
  throw new Error('ExpectedHexEncodedBlockToGetIdFor');
27
27
  }
28
28
 
29
+ // Exit early with error when the block is cut short of a full header
30
+ if (block.length < headerEndIndex) {
31
+ throw new Error('ExpectedFullBlockHeaderInBlockToGetIdFor');
32
+ }
33
+
29
34
  const header = block.substring(headerStartIndex, headerEndIndex);
30
35
 
31
36
  return {id: bufferAsHex(sha256(sha256(hexAsBuffer(header))).reverse())};
@@ -1,4 +1,5 @@
1
1
  const {createHash} = require('crypto');
2
+ const {types} = require('util');
2
3
 
3
4
  const {numberAsCompactInt} = require('./../numbers');
4
5
 
@@ -8,6 +9,18 @@ const byteCountHash = 32;
8
9
  const byteCountInt32 = 4;
9
10
  const byteCountInt64 = 8;
10
11
  const {concat} = Buffer;
12
+ const {isArray} = Array;
13
+ const isBigInt = n => typeof n === 'bigint';
14
+ // Unlike instanceof, this matches byte arrays from any VM context too
15
+ const isBytes = n => isUint8Array(n);
16
+ const {isInteger} = Number;
17
+ const isInt32 = n => isInteger(n) && n >= -0x80000000 && n <= 0x7fffffff;
18
+ const {isSafeInteger} = Number;
19
+ // Tokens can be a safe number, or a bigint for the full 64 bit range
20
+ const isTokens = n => (isSafeInteger(n) && n >= 0) || isUInt64(n);
21
+ const isUInt32 = n => isInteger(n) && n >= 0 && n <= 0xffffffff;
22
+ const {isUint8Array} = types;
23
+ const isUInt64 = n => isBigInt(n) && n >= 0n && n <= 0xffffffffffffffffn;
11
24
  const sha256 = preimage => createHash('sha256').update(preimage).digest();
12
25
 
13
26
  /** Determine a transaction id from transaction components
@@ -38,6 +51,40 @@ const sha256 = preimage => createHash('sha256').update(preimage).digest();
38
51
  }
39
52
  */
40
53
  module.exports = ({inputs, locktime, outputs, version}) => {
54
+ if (!isArray(inputs)) {
55
+ throw new Error('ExpectedArrayOfInputsToDeriveTransactionId');
56
+ }
57
+
58
+ if (inputs.some(n => !n || !isBytes(n.hash) || !isBytes(n.script))) {
59
+ throw new Error('ExpectedInputHashesAndScriptsToDeriveTransactionId');
60
+ }
61
+
62
+ // A hash of another length would shift the fields that follow it
63
+ if (inputs.some(input => input.hash.length !== byteCountHash)) {
64
+ throw new Error('ExpectedInputHashLengthToDeriveTransactionId');
65
+ }
66
+
67
+ // Numbers are not defaulted, a missing one would encode as zero
68
+ if (inputs.some(n => !isUInt32(n.sequence) || !isUInt32(n.vout))) {
69
+ throw new Error('ExpectedInputSequencesAndIndexesToDeriveTransactionId');
70
+ }
71
+
72
+ if (!isUInt32(locktime)) {
73
+ throw new Error('ExpectedLocktimeNumberToDeriveTransactionId');
74
+ }
75
+
76
+ if (!isArray(outputs)) {
77
+ throw new Error('ExpectedArrayOfOutputsToDeriveTransactionId');
78
+ }
79
+
80
+ if (outputs.some(n => !n || !isBytes(n.script) || !isTokens(n.tokens))) {
81
+ throw new Error('ExpectedOutputScriptsAndTokensToDeriveTransactionId');
82
+ }
83
+
84
+ if (!isInt32(version)) {
85
+ throw new Error('ExpectedVersionNumberToDeriveTransactionId');
86
+ }
87
+
41
88
  const elements = [];
42
89
 
43
90
  // Write the signed transaction version number
@@ -1,4 +1,7 @@
1
1
  const hashBytesHexCount = 32 * 2;
2
+ const headerHexCount = 80 * 2;
3
+ const isHex = n => !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
4
+ const isString = n => typeof n === 'string';
2
5
  const reverseByteOrder = n => Buffer.from(n, 'hex').reverse().toString('hex');
3
6
  const versionBytesHexCount = 4 * 2;
4
7
 
@@ -17,10 +20,15 @@ const versionBytesHexCount = 4 * 2;
17
20
  }
18
21
  */
19
22
  module.exports = ({block}) => {
20
- if (!block) {
23
+ if (!block || !isString(block) || !isHex(block)) {
21
24
  throw new Error('ExpectedHexEncodedBlockToDerivePreviousBlockId');
22
25
  }
23
26
 
27
+ // Exit early with error when the block is cut short of a full header
28
+ if (block.length < headerHexCount) {
29
+ throw new Error('ExpectedFullBlockHeaderToDerivePreviousBlockId');
30
+ }
31
+
24
32
  const end = hashBytesHexCount + versionBytesHexCount;
25
33
  const start = versionBytesHexCount;
26
34
 
@@ -51,49 +51,50 @@ module.exports = ({network, wif}) => {
51
51
  }
52
52
 
53
53
  // Decode the base58check string and validate its checksum
54
- const decoded = decodeBase58({encoded: wif});
54
+ const {payload} = decodeBase58({encoded: wif});
55
55
 
56
- // Copy the payload into its own memory, it was decoded into shared memory
57
- const payload = copyOf(decoded.payload);
56
+ try {
57
+ // The payload is a version byte and the private key, maybe with a flag
58
+ const keyEnd = countVersionBytes + countPrivateKeyBytes;
58
59
 
59
- // Wipe the shared memory copy of the payload since it has the private key
60
- wipe(decoded.payload);
60
+ // A compressed public key is signaled with a flag after the private key
61
+ const isCompressed = payload.length === keyEnd + countFlagBytes;
61
62
 
62
- // The payload is a version byte and then the private key, maybe with a flag
63
- const keyEnd = countVersionBytes + countPrivateKeyBytes;
63
+ // Make sure that the payload has the version and the private key
64
+ if (payload.length !== keyEnd && !isCompressed) {
65
+ throw new Error('ExpectedVersionAnd32BytePrivateKeyInWifPayload');
66
+ }
64
67
 
65
- // A compressed public key is signaled with a flag byte after the private key
66
- const isCompressed = payload.length === keyEnd + countFlagBytes;
68
+ // The compressed public key flag byte only has a single valid value
69
+ if (isCompressed && payload[keyEnd] !== compressedFlag) {
70
+ throw new Error('UnexpectedCompressionFlagValueInWifPayload');
71
+ }
67
72
 
68
- // Make sure that the payload has the version and the private key
69
- if (payload.length !== keyEnd && !isCompressed) {
70
- throw new Error('ExpectedVersionAnd32BytePrivateKeyInWifPayload');
71
- }
73
+ const [version] = payload;
72
74
 
73
- // The compressed public key flag byte only has a single valid value
74
- if (isCompressed && payload[keyEnd] !== compressedFlag) {
75
- throw new Error('UnexpectedCompressionFlagValueInWifPayload');
76
- }
75
+ // Exit early with error when the version is not for the given network
76
+ if (isDefined(network) && networks[network].wif !== version) {
77
+ throw new Error('UnexpectedWifVersionForNetwork');
78
+ }
77
79
 
78
- const [version] = payload;
80
+ // Exit early with error when the version is not for any known network
81
+ if (!values(networks).some(n => n.wif === version)) {
82
+ throw new Error('UnexpectedWifVersionForKnownNetworks');
83
+ }
79
84
 
80
- // Exit early with error when the version is not for the specified network
81
- if (isDefined(network) && networks[network].wif !== version) {
82
- throw new Error('UnexpectedWifVersionForNetwork');
83
- }
85
+ // The private key gets its own memory, the payload is in shared memory
86
+ const privateKey = copyOf(payload.subarray(countVersionBytes, keyEnd));
84
87
 
85
- // Exit early with error when the version is not for any known network
86
- if (!values(networks).some(n => n.wif === version)) {
87
- throw new Error('UnexpectedWifVersionForKnownNetworks');
88
- }
88
+ // A private key must be greater than zero and less than the curve order
89
+ if (isZero(privateKey) || privateKey.compare(curveOrder) >= 0) {
90
+ wipe(privateKey);
89
91
 
90
- // The private key gets its own memory, apart from the rest of the payload
91
- const privateKey = copyOf(payload.subarray(countVersionBytes, keyEnd));
92
+ throw new Error('ExpectedValidSecp256k1PrivateKeyInWifPayload');
93
+ }
92
94
 
93
- // A private key must be greater than zero and less than the curve order
94
- if (isZero(privateKey) || privateKey.compare(curveOrder) >= 0) {
95
- throw new Error('ExpectedValidSecp256k1PrivateKeyInWifPayload');
95
+ return {is_compressed: isCompressed, private_key: privateKey};
96
+ } finally {
97
+ // Wipe the shared memory payload on every path, it has the private key
98
+ wipe(payload);
96
99
  }
97
-
98
- return {is_compressed: isCompressed, private_key: privateKey};
99
100
  };
package/package.json CHANGED
@@ -30,5 +30,5 @@
30
30
  "scripts": {
31
31
  "test": "node --experimental-test-coverage --test test/5bit/*.js test/addresses/*.js test/hashes/*.js test/keys/*.js test/numbers/*.js test/script/*.js test/transactions/*.js"
32
32
  },
33
- "version": "4.11.0"
33
+ "version": "5.0.0"
34
34
  }
@@ -6,6 +6,7 @@ const {isArray} = Array;
6
6
  const {isBuffer} = Buffer;
7
7
  const {isInteger} = Number;
8
8
  const maxKeysCount = 20;
9
+ const minRequiredCount = 1;
9
10
  const numberAsElement = num => num <= 16 ? 0x50 + num : Buffer.from([num]);
10
11
  const OP_CHECKMULTISIG = 0xae;
11
12
  const publicKeyLength = 33;
@@ -42,7 +43,7 @@ module.exports = ({keys, required}) => {
42
43
  throw new Error('ExpectedCompressedPublicKeysToDeriveP2msScript');
43
44
  }
44
45
 
45
- if (!required || !isInteger(required)) {
46
+ if (!isInteger(required) || required < minRequiredCount) {
46
47
  throw new Error('ExpectedRequiredKeysCountToDeriveP2msScript');
47
48
  }
48
49
 
@@ -61,7 +61,7 @@ module.exports = ({script, sighash, transaction, vin}) => {
61
61
  throw new Error('ExpectedScriptCodeHexToCalculateNonWitnessHashToSign');
62
62
  }
63
63
 
64
- if (!!sighash && !hashTypes.includes(sighash)) {
64
+ if (sighash !== undefined && !hashTypes.includes(sighash)) {
65
65
  throw new Error('ExpectedValidSigHashTypeForNonWitnessHashToSign');
66
66
  }
67
67
 
@@ -73,8 +73,16 @@ module.exports = ({script, sighash, transaction, vin}) => {
73
73
  throw new Error('ExpectedInputIndexToCalculateNonWitnessHashToSign');
74
74
  }
75
75
 
76
+ const buffer = hexAsBuffer(transaction);
76
77
  const data = hexAsBuffer(script);
77
- const decoded = parseTransaction({buffer: hexAsBuffer(transaction)});
78
+
79
+ const decoded = parseTransaction({buffer});
80
+
81
+ // Exit early with error when there is extra data after the transaction
82
+ if (decoded.bytes.length !== buffer.length) {
83
+ throw new Error('UnexpectedDataAfterTransactionForNonWitnessHashToSign');
84
+ }
85
+
78
86
  const hashType = sighash || defaultHashType;
79
87
  const parts = [];
80
88
 
@@ -1,5 +1,3 @@
1
- const {createHash} = require('crypto');
2
-
3
1
  const {compactIntAsNumber} = require('./../numbers');
4
2
 
5
3
  const {idForTransactionComponents} = require('./../hashes');
@@ -8,6 +6,9 @@ const parseTransaction = require('./parse_transaction');
8
6
  const bufferAsHex = buffer => buffer.toString('hex');
9
7
  const hexAsBuffer = hex => Buffer.from(hex, 'hex');
10
8
  const {isArray} = Array;
9
+ const isHex = n => !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
10
+ const isString = n => typeof n === 'string';
11
+ const isTxId = n => isString(n) && /^[0-9A-F]{64}$/i.test(n);
11
12
  const minTxByteLength = 60;
12
13
  const transactionsStartIndex = 80;
13
14
 
@@ -15,7 +16,8 @@ const transactionsStartIndex = 80;
15
16
 
16
17
  {
17
18
  block: <Hex Encoded Raw Block String>
18
- outputs: [<Output Script Hex String>]
19
+ [ids]: [<Transaction Id Hex String>]
20
+ [outputs]: [<Output Script Hex String>]
19
21
  }
20
22
 
21
23
  @throws
@@ -29,17 +31,37 @@ const transactionsStartIndex = 80;
29
31
  transaction_id: <Transaction Id Hex String>
30
32
  transaction_vout: <Transaction Output Index Number>
31
33
  }]
34
+ transactions: [{
35
+ id: <Transaction Id Hex String>
36
+ transaction: <Hex Encoded Raw Transaction String>
37
+ }]
32
38
  }
33
39
  */
34
- module.exports = ({block, outputs}) => {
35
- if (!block) {
40
+ module.exports = ({block, ids, outputs}) => {
41
+ if (!block || !isString(block) || !isHex(block)) {
36
42
  throw new Error('ExpectedHexEncodedBlockToQueryTransactions');
37
43
  }
38
44
 
39
- if (!isArray(outputs)) {
45
+ if (ids === undefined && outputs === undefined) {
46
+ throw new Error('ExpectedTransactionIdsOrOutputsToQueryTransactions');
47
+ }
48
+
49
+ if (outputs !== undefined && !isArray(outputs)) {
40
50
  throw new Error('ExpectedArrayOfOutputsToQueryTransactionsInBlock');
41
51
  }
42
52
 
53
+ if (ids !== undefined && !isArray(ids)) {
54
+ throw new Error('ExpectedArrayOfIdsToQueryTransactionsInBlock');
55
+ }
56
+
57
+ if (!!ids && !ids.every(isTxId)) {
58
+ throw new Error('ExpectedTransactionIdHexStringToQueryTransactions');
59
+ }
60
+
61
+ if (!!outputs && !outputs.every(n => isString(n) && isHex(n))) {
62
+ throw new Error('ExpectedOutputScriptHexStringsToQueryTransactions');
63
+ }
64
+
43
65
  const buffer = hexAsBuffer(block);
44
66
 
45
67
  // Exit early with error when the block header data is cut short
@@ -54,8 +76,12 @@ module.exports = ({block, outputs}) => {
54
76
  });
55
77
 
56
78
  let cursor = transactionsStartIndex + txCount.bytes;
79
+ const found = new Set();
57
80
  const hits = [];
81
+ const pendingIds = new Set((ids || []).map(id => id.toLowerCase()));
58
82
  let remaining = txCount.number;
83
+ const scripts = new Set((outputs || []).map(n => n.toLowerCase()));
84
+ const transactions = [];
59
85
 
60
86
  // Confirm the data could possibly contain the claimed count of txs
61
87
  if (txCount.number * minTxByteLength > buffer.length - cursor) {
@@ -66,31 +92,61 @@ module.exports = ({block, outputs}) => {
66
92
  while (remaining--) {
67
93
  const tx = parseTransaction({buffer, start: cursor});
68
94
 
95
+ cursor += tx.bytes.length;
96
+
97
+ const matches = [];
98
+
69
99
  // Look at the transaction outputs to see if there is a match
70
- const matches = tx.outputs.forEach((output, vout) => {
100
+ tx.outputs.forEach((output, vout) => {
101
+ const script = bufferAsHex(output.script);
102
+
71
103
  // Exit early when the script isn't included in the outputs
72
- if (!outputs.includes(bufferAsHex(output.script))) {
104
+ if (!scripts.has(script)) {
73
105
  return;
74
106
  }
75
107
 
76
- // Calculate the transaction id
77
- const {id} = idForTransactionComponents({
78
- inputs: tx.inputs,
79
- locktime: tx.locktime,
80
- outputs: tx.outputs,
81
- version: tx.version,
82
- });
108
+ return matches.push({script, vout, tokens: output.tokens});
109
+ });
110
+
111
+ // Exit early when there are no output hits and no more ids to look for
112
+ if (!matches.length && !pendingIds.size) {
113
+ continue;
114
+ }
115
+
116
+ // Calculate the transaction id
117
+ const {id} = idForTransactionComponents({
118
+ inputs: tx.inputs,
119
+ locktime: tx.locktime,
120
+ outputs: tx.outputs,
121
+ version: tx.version,
122
+ });
83
123
 
84
- // Add the output to found hits
124
+ // Add the matching outputs to found hits
125
+ matches.forEach(({script, tokens, vout}) => {
85
126
  return hits.push({
86
- script: bufferAsHex(output.script),
87
- tokens: output.tokens,
127
+ script,
128
+ tokens,
88
129
  transaction_id: id,
89
130
  transaction_vout: vout,
90
131
  });
91
132
  });
92
133
 
93
- cursor += tx.bytes.length;
134
+ // Exit early when the transaction was already found in the block
135
+ if (found.has(id)) {
136
+ continue;
137
+ }
138
+
139
+ // Exit early when the transaction matches neither an output nor an id
140
+ if (!matches.length && !pendingIds.has(id)) {
141
+ continue;
142
+ }
143
+
144
+ found.add(id);
145
+
146
+ pendingIds.delete(id);
147
+
148
+ // Add the transaction to found transactions
149
+ transactions.push({id, transaction: bufferAsHex(tx.bytes)});
94
150
  }
95
151
 
96
152
  // Exit early with error when there is extra data after the transactions
@@ -98,5 +154,5 @@ module.exports = ({block, outputs}) => {
98
154
  throw new Error('UnexpectedDataAfterBlockTransactions');
99
155
  }
100
156
 
101
- return {outputs: hits};
157
+ return {transactions, outputs: hits};
102
158
  };
@@ -8,8 +8,17 @@ 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 => typeof n === 'string' && !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
12
- const isTxId = n => /^[0-9A-F]{64}$/i.test(n);
11
+ const isBigInt = n => typeof n === 'bigint';
12
+ const isHex = n => isString(n) && !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
13
+ const {isInteger} = Number;
14
+ const isInt32 = n => isInteger(n) && n >= -0x80000000 && n <= 0x7fffffff;
15
+ const {isSafeInteger} = Number;
16
+ const isString = n => typeof n === 'string';
17
+ // Tokens can be a safe number, or a bigint for the full 64 bit range
18
+ const isTokens = n => (isSafeInteger(n) && n >= 0) || isUInt64(n);
19
+ const isTxId = n => isString(n) && /^[0-9A-F]{64}$/i.test(n);
20
+ const isUInt32 = n => isInteger(n) && n >= 0 && n <= 0xffffffff;
21
+ const isUInt64 = n => isBigInt(n) && n >= 0n && n <= 0xffffffffffffffffn;
13
22
  const markerAndFlag = Buffer.from([0x00, 0x01]);
14
23
  const txIdAsTxHash = id => hexAsBuffer(id).reverse();
15
24
 
@@ -52,6 +61,11 @@ module.exports = ({inputs, locktime, outputs, version}) => {
52
61
  throw new Error('ExpectedHexEncodedInputScriptsToFormTransaction');
53
62
  }
54
63
 
64
+ // A witness that is not an array of elements would be silently dropped
65
+ if (inputs.some(n => n.witness !== undefined && !isArray(n.witness))) {
66
+ throw new Error('ExpectedArrayOfWitnessElementsToFormTransaction');
67
+ }
68
+
55
69
  // Confirm witness stack elements are hex encoded when present
56
70
  if (inputs.some(n => isArray(n.witness) && !n.witness.every(isHex))) {
57
71
  throw new Error('ExpectedHexEncodedWitnessElementsToFormTransaction');
@@ -61,6 +75,10 @@ module.exports = ({inputs, locktime, outputs, version}) => {
61
75
  throw new Error('ExpectedLocktimeToFormTransactionFromComponents');
62
76
  }
63
77
 
78
+ if (!isUInt32(locktime)) {
79
+ throw new Error('ExpectedLocktimeNumberToFormTransactionFromComponents');
80
+ }
81
+
64
82
  if (!isArray(outputs)) {
65
83
  throw new Error('ExpectedArrayOfOutputsToFormTransactionFromComponents');
66
84
  }
@@ -69,10 +87,28 @@ module.exports = ({inputs, locktime, outputs, version}) => {
69
87
  throw new Error('ExpectedHexEncodedOutputScriptsToFormTransaction');
70
88
  }
71
89
 
90
+ if (outputs.some(output => !isTokens(output.tokens))) {
91
+ throw new Error('ExpectedOutputTokensNumbersToFormTransaction');
92
+ }
93
+
72
94
  if (version === undefined) {
73
95
  throw new Error('ExpectedVersionNumberToFormTransactionFromComponents');
74
96
  }
75
97
 
98
+ if (!isInt32(version)) {
99
+ throw new Error('ExpectedSignedVersionNumberToFormTransaction');
100
+ }
101
+
102
+ // Sequence numbers are not defaulted, a missing one would encode as zero
103
+ if (inputs.some(input => !isUInt32(input.sequence))) {
104
+ throw new Error('ExpectedInputSequenceNumbersToFormTransaction');
105
+ }
106
+
107
+ // Output indexes are not defaulted, a missing one would encode as zero
108
+ if (inputs.some(input => !isUInt32(input.vout))) {
109
+ throw new Error('ExpectedSpendingOutputIndexesToFormTransaction');
110
+ }
111
+
76
112
  // Only use SegWit encoding when an input has witness stack elements
77
113
  const isSegWit = inputs.some(n => isArray(n.witness) && !!n.witness.length);
78
114
 
@@ -53,7 +53,7 @@ module.exports = ({psbt}) => {
53
53
  const valueSize = decodeCompactInt(psbtData, psbtStartBytes.length + 1);
54
54
 
55
55
  // Read in the transaction from the global value bytes
56
- const {bytes} = parseTransaction({
56
+ const {bytes, inputs} = parseTransaction({
57
57
  buffer: psbtData,
58
58
  start: psbtStartBytes.length + valueSize.bytes + 1,
59
59
  });
@@ -63,5 +63,10 @@ module.exports = ({psbt}) => {
63
63
  throw new Error('UnexpectedByteLengthOfPsbtUnsignedTransaction');
64
64
  }
65
65
 
66
+ // The global transaction of a PSBT carries no input scripts or witnesses
67
+ if (inputs.some(n => !!n.script.length || n.witness !== undefined)) {
68
+ throw new Error('ExpectedUnsignedTransactionInPsbtGlobalValue');
69
+ }
70
+
66
71
  return {transaction: bytes};
67
72
  };
@@ -12,6 +12,7 @@ const hashTypes = [0x01, 0x02, 0x03, 0x81, 0x82, 0x83];
12
12
  const hexAsBuffer = hex => Buffer.from(hex, 'hex');
13
13
  const isHex = n => !!n && !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
14
14
  const {isInteger} = Number;
15
+ const {isSafeInteger} = Number;
15
16
  const isString = n => typeof n === 'string';
16
17
  const outputTypeMask = 0x1f;
17
18
  const sha256 = preimage => createHash('sha256').update(preimage).digest();
@@ -51,11 +52,11 @@ module.exports = ({script, sighash, tokens, transaction, vin}) => {
51
52
  throw new Error('ExpectedScriptCodeHexStringToCalculateV0HashToSign');
52
53
  }
53
54
 
54
- if (!!sighash && !hashTypes.includes(sighash)) {
55
+ if (sighash !== undefined && !hashTypes.includes(sighash)) {
55
56
  throw new Error('ExpectedValidSignatureHashTypeToCalculateV0HashToSign');
56
57
  }
57
58
 
58
- if (!isInteger(tokens)) {
59
+ if (!isSafeInteger(tokens)) {
59
60
  throw new Error('ExpectedSpendTokensNumberToCalculateV0HashToSign');
60
61
  }
61
62
 
@@ -67,7 +68,15 @@ module.exports = ({script, sighash, tokens, transaction, vin}) => {
67
68
  throw new Error('ExpectedInputIndexNumberToCalculateV0HashToSign');
68
69
  }
69
70
 
70
- const decoded = parseTransaction({buffer: hexAsBuffer(transaction)});
71
+ const buffer = hexAsBuffer(transaction);
72
+
73
+ const decoded = parseTransaction({buffer});
74
+
75
+ // Exit early with error when there is extra data after the transaction
76
+ if (decoded.bytes.length !== buffer.length) {
77
+ throw new Error('UnexpectedDataAfterTransactionToCalculateV0HashToSign');
78
+ }
79
+
71
80
  const hashType = sighash || defaultHashType;
72
81
  const scriptCode = hexAsBuffer(script);
73
82