@alexbosworth/blockchain 3.2.0 → 4.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,13 @@
1
1
  # Versions
2
2
 
3
+ ## 4.0.0
4
+
5
+ - `sizeOfTransaction`: Add method to get transaction weight and virtual size
6
+
7
+ ### Breaking Changes
8
+
9
+ - End support for Node.js v20, require v22+
10
+
3
11
  ## 3.2.0
4
12
 
5
13
  - `decode_bech32_address.js`: Add method to decode a bech32/bech32m address
package/README.md CHANGED
@@ -4,6 +4,27 @@ Utility methods for working with Blockchain data
4
4
 
5
5
  ## Methods
6
6
 
7
+ - [compactIntAsNumber](#compactintasnumber)
8
+ - [componentsOfTransaction](#componentsoftransaction)
9
+ - [decodeBase58Address](#decodebase58address)
10
+ - [decodeBech32Address](#decodebech32address)
11
+ - [idForBlock](#idforblock)
12
+ - [idForTransaction](#idfortransaction)
13
+ - [idForTransactionComponents](#idfortransactioncomponents)
14
+ - [noLocktimeIdForTransaction](#nolocktimeidfortransaction)
15
+ - [numberAsCompactInt](#numberascompactint)
16
+ - [p2pkhOutputScript](#p2pkhoutputscript)
17
+ - [p2shOutputScript](#p2shoutputscript)
18
+ - [p2trOutputScript](#p2troutputscript)
19
+ - [p2wpkhOutputScript](#p2wpkhoutputscript)
20
+ - [p2wshOutputScript](#p2wshoutputscript)
21
+ - [previousBlockId](#previousblockid)
22
+ - [queryTransactions](#querytransactions)
23
+ - [scriptAsScriptElements](#scriptasscriptelements)
24
+ - [scriptElementsAsScript](#scriptelementsasscript)
25
+ - [sizeOfTransaction](#sizeoftransaction)
26
+ - [unsignedTxFromPsbt](#unsignedtxfrompsbt)
27
+
7
28
  ### compactIntAsNumber
8
29
 
9
30
  Convert a compact integer to a regular number
@@ -335,6 +356,23 @@ Map array of script buffer elements to a fully formed script
335
356
  script: <Script Hex String>
336
357
  }
337
358
 
359
+ ### sizeOfTransaction
360
+
361
+ Get the weight and virtual size of a hex-encoded transaction
362
+
363
+ {
364
+ transaction: <Hex Encoded Transaction String>
365
+ }
366
+
367
+ @throws
368
+ <Error>
369
+
370
+ @returns
371
+ {
372
+ vsize: <Transaction Virtual Size Number>
373
+ weight: <Transaction Weight Units Number>
374
+ }
375
+
338
376
  ### unsignedTxFromPsbt
339
377
 
340
378
  Get the unsigned transaction out of a PSBT
package/index.js CHANGED
@@ -16,6 +16,7 @@ const {previousBlockId} = require('./hashes');
16
16
  const {queryTransactions} = require('./transactions');
17
17
  const {scriptAsScriptElements} = require('./script');
18
18
  const {scriptElementsAsScript} = require('./script');
19
+ const {sizeOfTransaction} = require('./transactions');
19
20
  const {unsignedTxFromPsbt} = require('./transactions');
20
21
 
21
22
  module.exports = {
@@ -37,5 +38,6 @@ module.exports = {
37
38
  queryTransactions,
38
39
  scriptAsScriptElements,
39
40
  scriptElementsAsScript,
41
+ sizeOfTransaction,
40
42
  unsignedTxFromPsbt,
41
43
  };
@@ -40,14 +40,13 @@ module.exports = ({encoded, start}) => {
40
40
 
41
41
  case 5:
42
42
  return {bytes, number: encoded.readUInt32LE(offset + lengthMarkerOffset)};
43
+ }
43
44
 
44
- default:
45
- const number = encoded.readBigUInt64LE(offset + lengthMarkerOffset);
46
-
47
- if (!isSafeNumber(number)) {
48
- throw new Error('ExpectedSafeSizeEncodedCompactInteger');
49
- }
45
+ const number = encoded.readBigUInt64LE(offset + lengthMarkerOffset);
50
46
 
51
- return {bytes, number: Number(number)};
47
+ if (!isSafeNumber(number)) {
48
+ throw new Error('ExpectedSafeSizeEncodedCompactInteger');
52
49
  }
50
+
51
+ return {bytes, number: Number(number)};
53
52
  };
package/package.json CHANGED
@@ -8,7 +8,7 @@
8
8
  },
9
9
  "description": "Blockchain data utility methods",
10
10
  "engines": {
11
- "node": ">=20"
11
+ "node": ">=22"
12
12
  },
13
13
  "license": "MIT",
14
14
  "name": "@alexbosworth/blockchain",
@@ -17,7 +17,7 @@
17
17
  "url": "https://github.com/alexbosworth/blockchain.git"
18
18
  },
19
19
  "scripts": {
20
- "test": "npx nyc@17.1.0 node --experimental-test-coverage --test test/addresses/*.js test/hashes/*.js test/numbers/*.js test/script/*.js test/transactions/*.js"
20
+ "test": "node --experimental-test-coverage --test test/addresses/*.js test/hashes/*.js test/numbers/*.js test/script/*.js test/transactions/*.js"
21
21
  },
22
- "version": "3.2.0"
22
+ "version": "4.0.0"
23
23
  }
@@ -55,7 +55,6 @@ module.exports = ({offset, script}) => {
55
55
  };
56
56
 
57
57
  case OP_PUSHDATA4:
58
- default:
59
58
  // Exit early when there isn't enough data for UInt32
60
59
  if (data.length < countUInt32Bytes) {
61
60
  return {};
@@ -0,0 +1,15 @@
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
+ });
@@ -0,0 +1,84 @@
1
+ const {deepStrictEqual} = require('node:assert').strict;
2
+ const {throws} = require('node:assert').strict;
3
+ const test = require('node:test');
4
+
5
+ const {sizeOfTransaction} = require('./../../');
6
+
7
+ const legacyTransaction = [
8
+ '02000000',
9
+ '01',
10
+ '0000000000000000000000000000000000000000000000000000000000000000',
11
+ '00000000',
12
+ '00',
13
+ 'ffffffff',
14
+ '01',
15
+ '0100000000000000',
16
+ '01',
17
+ '51',
18
+ '00000000',
19
+ ].join('');
20
+
21
+ const witnessTransaction = [
22
+ '02000000',
23
+ '0001',
24
+ '01',
25
+ '0000000000000000000000000000000000000000000000000000000000000000',
26
+ '00000000',
27
+ '00',
28
+ 'ffffffff',
29
+ '01',
30
+ '0100000000000000',
31
+ '01',
32
+ '51',
33
+ '01',
34
+ '01',
35
+ '00',
36
+ '00000000',
37
+ ].join('');
38
+
39
+ const tests = [
40
+ {
41
+ args: {transaction: ''},
42
+ description: 'A transaction is required',
43
+ error: 'ExpectedHexEncodedTransactionToGetSize',
44
+ },
45
+ {
46
+ args: {transaction: '00f'},
47
+ description: 'An even-length transaction is required',
48
+ error: 'ExpectedHexEncodedTransactionToGetSize',
49
+ },
50
+ {
51
+ args: {transaction: 'not hex'},
52
+ description: 'A hex-encoded transaction is required',
53
+ error: 'ExpectedHexEncodedTransactionToGetSize',
54
+ },
55
+ {
56
+ args: {transaction: `${legacyTransaction}00`},
57
+ description: 'Data after the transaction is not accepted',
58
+ error: 'UnexpectedDataAfterTransactionToGetSize',
59
+ },
60
+ {
61
+ args: {transaction: legacyTransaction},
62
+ description: 'The size of a legacy transaction is returned',
63
+ expected: {vsize: 61, weight: 244},
64
+ },
65
+ {
66
+ args: {transaction: witnessTransaction},
67
+ description: 'The size of a witness transaction is returned',
68
+ expected: {vsize: 63, weight: 249},
69
+ },
70
+ ];
71
+
72
+ tests.forEach(({args, description, error, expected}) => {
73
+ return test(description, (t, end) => {
74
+ if (!!error) {
75
+ throws(() => sizeOfTransaction(args), new Error(error), 'Got error');
76
+ } else {
77
+ const res = sizeOfTransaction(args);
78
+
79
+ deepStrictEqual(res, expected, 'Got expected result');
80
+ }
81
+
82
+ return end();
83
+ });
84
+ });
@@ -3,6 +3,7 @@ const idForTransaction = require('./id_for_transaction');
3
3
  const noLocktimeIdForTransaction = require('./no_locktime_id_for_transaction');
4
4
  const parseTransaction = require('./parse_transaction');
5
5
  const queryTransactions = require('./query_transactions');
6
+ const sizeOfTransaction = require('./size_of_transaction');
6
7
  const unsignedTxFromPsbt = require('./unsigned_tx_from_psbt');
7
8
 
8
9
  module.exports = {
@@ -11,5 +12,6 @@ module.exports = {
11
12
  noLocktimeIdForTransaction,
12
13
  parseTransaction,
13
14
  queryTransactions,
15
+ sizeOfTransaction,
14
16
  unsignedTxFromPsbt,
15
17
  };
@@ -0,0 +1,58 @@
1
+ const parseTransaction = require('./parse_transaction');
2
+
3
+ const byteCountLocktime = 4;
4
+ const byteCountMarkerFlag = 2;
5
+ const {ceil} = Math;
6
+ const hexAsBuffer = hex => Buffer.from(hex, 'hex');
7
+ const isHex = n => !!n && !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
8
+ const noFlagAndMarker = 0;
9
+ const witnessScaling = 4;
10
+
11
+ /** Get the weight and virtual size of a hex-encoded transaction
12
+
13
+ {
14
+ transaction: <Hex Encoded Transaction String>
15
+ }
16
+
17
+ @throws
18
+ <Error>
19
+
20
+ @returns
21
+ {
22
+ vsize: <Transaction Virtual Size Number>
23
+ weight: <Transaction Weight Units Number>
24
+ }
25
+ */
26
+ module.exports = ({transaction}) => {
27
+ if (!isHex(transaction)) {
28
+ throw new Error('ExpectedHexEncodedTransactionToGetSize');
29
+ }
30
+
31
+ const buffer = hexAsBuffer(transaction);
32
+
33
+ const {bytes, inputs} = parseTransaction({buffer});
34
+
35
+ if (bytes.length !== buffer.length) {
36
+ throw new Error('UnexpectedDataAfterTransactionToGetSize');
37
+ }
38
+
39
+ // Parse through the outputs, stopping before witness data and nLockTime
40
+ const txBeforeWitness = parseTransaction({
41
+ buffer,
42
+ is_terminating_after_outputs: true,
43
+ });
44
+
45
+ // Before the witness, a SegWit transaction includes marker and flag bytes
46
+ const hasWitness = inputs.some(input => input.witness !== undefined);
47
+
48
+ const markerFlagSize = hasWitness ? byteCountMarkerFlag : noFlagAndMarker;
49
+ const sizeBeforeWitness = txBeforeWitness.bytes.length;
50
+
51
+ // Stripped size includes nLockTime but excludes marker, flag, and witnesses
52
+ const strippedSize = sizeBeforeWitness + byteCountLocktime - markerFlagSize;
53
+
54
+ // Base bytes weigh four units and witness bytes weigh one unit
55
+ const weight = strippedSize * witnessScaling + bytes.length - strippedSize;
56
+
57
+ return {weight, vsize: ceil(weight / witnessScaling)};
58
+ };