@alexbosworth/blockchain 4.2.0 → 4.4.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.4.0
4
+
5
+ - `transactionFromComponents`: Add method to form a raw tx from tx components
6
+
7
+ ## 4.3.0
8
+
9
+ - `hashForP2pkh`: Add method to get the p2pkh hash160 for a public key
10
+
3
11
  ## 4.2.0
4
12
 
5
13
  - `encodeBech32Address`: Add method to encode a bech32/bech32m address string
package/README.md CHANGED
@@ -9,6 +9,7 @@ Utility methods for working with Blockchain data
9
9
  - [decodeBase58Address](#decodebase58address)
10
10
  - [decodeBech32Address](#decodebech32address)
11
11
  - [encodeBech32Address](#encodebech32address)
12
+ - [hashForP2pkh](#hashforp2pkh)
12
13
  - [hashForP2wpkh](#hashforp2wpkh)
13
14
  - [idForBlock](#idforblock)
14
15
  - [idForTransaction](#idfortransaction)
@@ -26,6 +27,7 @@ Utility methods for working with Blockchain data
26
27
  - [scriptAsScriptElements](#scriptasscriptelements)
27
28
  - [scriptElementsAsScript](#scriptelementsasscript)
28
29
  - [sizeOfTransaction](#sizeoftransaction)
30
+ - [transactionFromComponents](#transactionfromcomponents)
29
31
  - [unsignedTxFromPsbt](#unsignedtxfrompsbt)
30
32
 
31
33
  ### compactIntAsNumber
@@ -149,6 +151,24 @@ const {address} = encodeBech32Address({
149
151
  });
150
152
  ```
151
153
 
154
+ ### hashForP2pkh
155
+
156
+ Get the hash160 of a public key to pay to via P2PKH
157
+
158
+ Use `hash` with `p2pkhOutputScript` for a P2PKH output script
159
+
160
+ {
161
+ key: <Public Key Buffer Object>
162
+ }
163
+
164
+ @throws
165
+ <Error>
166
+
167
+ @returns
168
+ {
169
+ hash: <Public Key Hash160 Buffer Object>
170
+ }
171
+
152
172
  ### hashForP2wpkh
153
173
 
154
174
  Get the hash160 of a public key to pay to via P2WPKH
@@ -295,7 +315,7 @@ const {script} = p2wshOutputScript({hash});
295
315
 
296
316
  ### p2pkhOutputScript
297
317
 
298
- Get a Pay To Witness Public Key Hash Output Script
318
+ Get a Pay To Public Key Hash Output Script
299
319
 
300
320
  {
301
321
  hash: <Public Key Hash Buffer Object>
@@ -460,6 +480,34 @@ Get the weight and virtual size of a hex-encoded transaction
460
480
  weight: <Transaction Weight Units Number>
461
481
  }
462
482
 
483
+ ### transactionFromComponents
484
+
485
+ Form a hex-encoded transaction from its component elements
486
+
487
+ {
488
+ inputs: [{
489
+ id: <Spending Transaction Id Hex String>
490
+ script: <ScriptSig Script Hex String>
491
+ sequence: <Sequence Number>
492
+ vout: <Spending Transaction Output Index Number>
493
+ [witness]: [<Script Stack Element Hex String>]
494
+ }]
495
+ locktime: <Timelock nLockTime Number>
496
+ outputs: [{
497
+ script: <ScriptPub Script Hex String>
498
+ tokens: <Tokens Count Number>
499
+ }]
500
+ version: <Version Number>
501
+ }
502
+
503
+ @throws
504
+ <Error>
505
+
506
+ @returns
507
+ {
508
+ transaction: <Hex Encoded Transaction String>
509
+ }
510
+
463
511
  ### unsignedTxFromPsbt
464
512
 
465
513
  Get the unsigned transaction out of a PSBT
@@ -0,0 +1,32 @@
1
+ const {createHash} = require('node:crypto');
2
+
3
+ const {isBuffer} = Buffer;
4
+ const publicKeyLength = 33;
5
+ const ripemd160 = data => createHash('ripemd160').update(data).digest();
6
+ const sha256 = data => createHash('sha256').update(data).digest();
7
+
8
+ /** Get the hash160 of a public key
9
+
10
+ {
11
+ key: <Public Key Buffer Object>
12
+ }
13
+
14
+ @throws
15
+ <Error>
16
+
17
+ @returns
18
+ {
19
+ hash: <Public Key Hash160 Buffer Object>
20
+ }
21
+ */
22
+ module.exports = ({key}) => {
23
+ if (!isBuffer(key)) {
24
+ throw new Error('ExpectedPublicKeyToDerivePublicKeyHash160');
25
+ }
26
+
27
+ if (key.length !== publicKeyLength) {
28
+ throw new Error('ExpectedCompressedPublicKeyToDerivePublicKeyHash160');
29
+ }
30
+
31
+ return {hash: ripemd160(sha256(key))};
32
+ };
@@ -0,0 +1,19 @@
1
+ const hash160ForPublicKey = require('./hash160_for_public_key');
2
+
3
+ /** Get the hash160 of a public key to pay to via P2PKH
4
+
5
+ Use `hash` with `p2pkhOutputScript` for a P2PKH output script
6
+
7
+ {
8
+ key: <Public Key Buffer Object>
9
+ }
10
+
11
+ @throws
12
+ <Error>
13
+
14
+ @returns
15
+ {
16
+ hash: <Public Key Hash160 Buffer Object>
17
+ }
18
+ */
19
+ module.exports = ({key}) => hash160ForPublicKey({key});
@@ -1,9 +1,4 @@
1
- const {createHash} = require('node:crypto');
2
-
3
- const {isBuffer} = Buffer;
4
- const publicKeyLength = 33;
5
- const ripemd160 = data => createHash('ripemd160').update(data).digest();
6
- const sha256 = data => createHash('sha256').update(data).digest();
1
+ const hash160ForPublicKey = require('./hash160_for_public_key');
7
2
 
8
3
  /** Get the hash160 of a public key to pay to via P2WPKH
9
4
 
@@ -21,14 +16,4 @@ const sha256 = data => createHash('sha256').update(data).digest();
21
16
  hash: <Public Key Hash160 Buffer Object>
22
17
  }
23
18
  */
24
- module.exports = ({key}) => {
25
- if (!isBuffer(key)) {
26
- throw new Error('ExpectedPublicKeyToDeriveHashForP2wpkh');
27
- }
28
-
29
- if (key.length !== publicKeyLength) {
30
- throw new Error('ExpectedCompressedPublicKeyToDeriveHashForP2wpkh');
31
- }
32
-
33
- return {hash: ripemd160(sha256(key))};
34
- };
19
+ module.exports = ({key}) => hash160ForPublicKey({key});
package/hashes/index.js CHANGED
@@ -1,9 +1,11 @@
1
+ const hashForP2pkh = require('./hash_for_p2pkh');
1
2
  const hashForP2wpkh = require('./hash_for_p2wpkh');
2
3
  const idForBlock = require('./id_for_block');
3
4
  const idForTransactionComponents = require('./id_for_transaction_components');
4
5
  const previousBlockId = require('./previous_block_id');
5
6
 
6
7
  module.exports = {
8
+ hashForP2pkh,
7
9
  hashForP2wpkh,
8
10
  idForBlock,
9
11
  idForTransactionComponents,
package/index.js CHANGED
@@ -3,6 +3,7 @@ const {componentsOfTransaction} = require('./transactions');
3
3
  const {decodeBase58Address} = require('./addresses');
4
4
  const {decodeBech32Address} = require('./addresses');
5
5
  const {encodeBech32Address} = require('./addresses');
6
+ const {hashForP2pkh} = require('./hashes');
6
7
  const {hashForP2wpkh} = require('./hashes');
7
8
  const {idForBlock} = require('./hashes');
8
9
  const {idForTransaction} = require('./transactions');
@@ -20,6 +21,7 @@ const {queryTransactions} = require('./transactions');
20
21
  const {scriptAsScriptElements} = require('./script');
21
22
  const {scriptElementsAsScript} = require('./script');
22
23
  const {sizeOfTransaction} = require('./transactions');
24
+ const {transactionFromComponents} = require('./transactions');
23
25
  const {unsignedTxFromPsbt} = require('./transactions');
24
26
 
25
27
  module.exports = {
@@ -28,6 +30,7 @@ module.exports = {
28
30
  decodeBase58Address,
29
31
  decodeBech32Address,
30
32
  encodeBech32Address,
33
+ hashForP2pkh,
31
34
  hashForP2wpkh,
32
35
  idForBlock,
33
36
  idForTransaction,
@@ -45,5 +48,6 @@ module.exports = {
45
48
  scriptAsScriptElements,
46
49
  scriptElementsAsScript,
47
50
  sizeOfTransaction,
51
+ transactionFromComponents,
48
52
  unsignedTxFromPsbt,
49
53
  };
package/package.json CHANGED
@@ -19,5 +19,5 @@
19
19
  "scripts": {
20
20
  "test": "node --experimental-test-coverage --test test/5bit/*.js test/addresses/*.js test/hashes/*.js test/numbers/*.js test/script/*.js test/transactions/*.js"
21
21
  },
22
- "version": "4.2.0"
22
+ "version": "4.4.0"
23
23
  }
@@ -0,0 +1,54 @@
1
+ const {deepStrictEqual} = require('node:assert').strict;
2
+ const {throws} = require('node:assert').strict;
3
+ const test = require('node:test');
4
+
5
+ const {hashForP2pkh} = require('./../../');
6
+
7
+ const bufferFromHex = hex => Buffer.from(hex, 'hex');
8
+
9
+ const tests = [
10
+ {
11
+ args: {},
12
+ description: 'A public key is required',
13
+ error: 'ExpectedPublicKeyToDerivePublicKeyHash160',
14
+ },
15
+ {
16
+ args: {
17
+ key: bufferFromHex('0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
18
+ },
19
+ description: 'A compressed public key is required',
20
+ error: 'ExpectedCompressedPublicKeyToDerivePublicKeyHash160',
21
+ },
22
+ {
23
+ args: {
24
+ key: bufferFromHex('0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
25
+ },
26
+ description: 'A hash is derived for the BIP 173 example public key',
27
+ expected: {
28
+ hash: bufferFromHex('751e76e8199196d454941c45d1b3a323f1433bd6'),
29
+ },
30
+ },
31
+ {
32
+ args: {
33
+ key: bufferFromHex('025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee6357'),
34
+ },
35
+ description: 'A hash is derived for the BIP 143 example public key',
36
+ expected: {
37
+ hash: bufferFromHex('1d0f172a0ecb48aee1be1f2687d2963ae33f71a1'),
38
+ },
39
+ },
40
+ ];
41
+
42
+ tests.forEach(({args, description, error, expected}) => {
43
+ return test(description, (t, end) => {
44
+ if (!!error) {
45
+ throws(() => hashForP2pkh(args), new Error(error), 'Got err');
46
+ } else {
47
+ const res = hashForP2pkh(args);
48
+
49
+ deepStrictEqual(res, expected, 'Got expected result');
50
+ }
51
+
52
+ return end();
53
+ });
54
+ });
@@ -10,14 +10,14 @@ const tests = [
10
10
  {
11
11
  args: {},
12
12
  description: 'A public key is required',
13
- error: 'ExpectedPublicKeyToDeriveHashForP2wpkh',
13
+ error: 'ExpectedPublicKeyToDerivePublicKeyHash160',
14
14
  },
15
15
  {
16
16
  args: {
17
17
  key: bufferFromHex('0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
18
18
  },
19
19
  description: 'A compressed public key is required',
20
- error: 'ExpectedCompressedPublicKeyToDeriveHashForP2wpkh',
20
+ error: 'ExpectedCompressedPublicKeyToDerivePublicKeyHash160',
21
21
  },
22
22
  {
23
23
  args: {
@@ -0,0 +1,192 @@
1
+ const {deepStrictEqual} = require('node:assert').strict;
2
+ const {throws} = require('node:assert').strict;
3
+ const test = require('node:test');
4
+
5
+ const {componentsOfTransaction} = require('./../../');
6
+ const {transactionFromComponents} = require('./../../');
7
+
8
+ const tests = [
9
+ {
10
+ args: {},
11
+ description: 'An array of inputs is required',
12
+ error: 'ExpectedArrayOfInputsToFormTransactionFromComponents',
13
+ },
14
+ {
15
+ args: {inputs: [{id: '00'}]},
16
+ description: 'Inputs are required to have spending transaction ids',
17
+ error: 'ExpectedSpendingTransactionIdsToFormTransaction',
18
+ },
19
+ {
20
+ args: {
21
+ inputs: [{
22
+ id: Buffer.alloc(32).toString('hex'),
23
+ script: 'not hex',
24
+ }],
25
+ },
26
+ description: 'Inputs are required to have hex encoded scripts',
27
+ error: 'ExpectedHexEncodedInputScriptsToFormTransaction',
28
+ },
29
+ {
30
+ args: {
31
+ inputs: [{id: Buffer.alloc(32).toString('hex'), script: ''}],
32
+ },
33
+ description: 'A locktime is required',
34
+ error: 'ExpectedLocktimeToFormTransactionFromComponents',
35
+ },
36
+ {
37
+ args: {
38
+ inputs: [{id: Buffer.alloc(32).toString('hex'), script: ''}],
39
+ locktime: 0,
40
+ },
41
+ description: 'An array of outputs is required',
42
+ error: 'ExpectedArrayOfOutputsToFormTransactionFromComponents',
43
+ },
44
+ {
45
+ args: {
46
+ inputs: [{id: Buffer.alloc(32).toString('hex'), script: ''}],
47
+ locktime: 0,
48
+ outputs: [{script: 'not hex', tokens: 1}],
49
+ },
50
+ description: 'Outputs are required to have hex encoded scripts',
51
+ error: 'ExpectedHexEncodedOutputScriptsToFormTransaction',
52
+ },
53
+ {
54
+ args: {
55
+ inputs: [{id: Buffer.alloc(32).toString('hex'), script: ''}],
56
+ locktime: 0,
57
+ outputs: [],
58
+ },
59
+ description: 'A version number is required',
60
+ error: 'ExpectedVersionNumberToFormTransactionFromComponents',
61
+ },
62
+ {
63
+ args: {
64
+ inputs: [{
65
+ id: '0000000000000000000000000000000000000000000000000000000000000000',
66
+ script: '04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73',
67
+ sequence: 4294967295,
68
+ vout: 4294967295,
69
+ }],
70
+ locktime: 0,
71
+ outputs: [{
72
+ script: '4104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac',
73
+ tokens: 5000000000,
74
+ }],
75
+ version: 1,
76
+ },
77
+ description: 'A coinbase transaction is formed',
78
+ expected: {
79
+ transaction: '01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000',
80
+ },
81
+ },
82
+ {
83
+ args: {
84
+ inputs: [
85
+ {
86
+ id: '523e6d953a12ce92824c29d542455fa524f577639da29725146188ad3aaf8cae',
87
+ script: '',
88
+ sequence: 4294967295,
89
+ vout: 0,
90
+ witness: [
91
+ '30450221008ac71eff4d7e298941be012fc14f0ac9bf62ae6ffeac13522bb27b5b4108d3aa0220192a69ad6fdb86b1e09c7fdcaaafeb58d25060e44199c734dc0d7d385b5d800d01',
92
+ '029943eaccd3987fa495a6b4f47f2fafeb0521e4e12f39498d9465a564ef753296',
93
+ ],
94
+ },
95
+ {
96
+ id: '572477126b95bd17aacdb94a559ed4024fa198a1759d480cb977a631551cbb9c',
97
+ script: '',
98
+ sequence: 4294967295,
99
+ vout: 2,
100
+ witness: [
101
+ '3045022100f9cde9adb00c0a6c62dae8604ca750039201288c0dafff952461da3caf05e3ae0220679c01f2518413951de3b62531b1cf36bb92562e3bd4197f0fa6e6e3e231272e01',
102
+ '027326b48c9f2729597e328ab6d05f5af75866e1ffa203fadf78387a3b202ff80d',
103
+ ],
104
+ },
105
+ {
106
+ id: '572477126b95bd17aacdb94a559ed4024fa198a1759d480cb977a631551cbb9c',
107
+ script: '',
108
+ sequence: 4294967295,
109
+ vout: 1,
110
+ witness: [
111
+ '304402202550beec478845af2df929abf85708f9fcceaae31377f2e01d803e2acf7b426f022036c312b1e38ca333fe70aa37d3093387ac7486f08438eb8eed323699594468cb01',
112
+ '02275a197f7ccfece19cf0532b068b6e38ceceda146e791875ecbdc55500bb7efe',
113
+ ],
114
+ },
115
+ ],
116
+ locktime: 0,
117
+ outputs: [
118
+ {
119
+ script: '0014eaa9b76637b1ad340b6efadf773a73b53637d5b6',
120
+ tokens: 1000000,
121
+ },
122
+ {
123
+ script: '5120f4c82416bcb08422c195af995e1d248d1378d8b48dafa9f45bc213b83101d492',
124
+ tokens: 4998992350,
125
+ },
126
+ {
127
+ script: '00148729d17b2aa507ab19051a028384bc6e0ce25e45',
128
+ tokens: 1000000,
129
+ },
130
+ {
131
+ script: '51200249ccc5af06fa5642f12d42d2a34bfbb08688d54a9b99d07b98619b35df03b4',
132
+ tokens: 8992350,
133
+ },
134
+ {
135
+ script: '0014d2d59a8a59f997cbc8888411010faf1658e0e346',
136
+ tokens: 1000000,
137
+ },
138
+ {
139
+ script: '51207febd720c78518b52aa1a2443823cc8f55e373910f616e112d5d7bd622fe1ab2',
140
+ tokens: 8992350,
141
+ },
142
+ ],
143
+ version: 2,
144
+ },
145
+ description: 'A transaction with witnesses is formed',
146
+ expected: {
147
+ transaction: '02000000000103ae8caf3aad8861142597a29d6377f524a55f4542d5294c8292ce123a956d3e520000000000ffffffff9cbb1c5531a677b90c489d75a198a14f02d49e554ab9cdaa17bd956b127724570200000000ffffffff9cbb1c5531a677b90c489d75a198a14f02d49e554ab9cdaa17bd956b127724570100000000ffffffff0640420f0000000000160014eaa9b76637b1ad340b6efadf773a73b53637d5b6de91f62901000000225120f4c82416bcb08422c195af995e1d248d1378d8b48dafa9f45bc213b83101d49240420f00000000001600148729d17b2aa507ab19051a028384bc6e0ce25e455e368900000000002251200249ccc5af06fa5642f12d42d2a34bfbb08688d54a9b99d07b98619b35df03b440420f0000000000160014d2d59a8a59f997cbc8888411010faf1658e0e3465e368900000000002251207febd720c78518b52aa1a2443823cc8f55e373910f616e112d5d7bd622fe1ab2024830450221008ac71eff4d7e298941be012fc14f0ac9bf62ae6ffeac13522bb27b5b4108d3aa0220192a69ad6fdb86b1e09c7fdcaaafeb58d25060e44199c734dc0d7d385b5d800d0121029943eaccd3987fa495a6b4f47f2fafeb0521e4e12f39498d9465a564ef75329602483045022100f9cde9adb00c0a6c62dae8604ca750039201288c0dafff952461da3caf05e3ae0220679c01f2518413951de3b62531b1cf36bb92562e3bd4197f0fa6e6e3e231272e0121027326b48c9f2729597e328ab6d05f5af75866e1ffa203fadf78387a3b202ff80d0247304402202550beec478845af2df929abf85708f9fcceaae31377f2e01d803e2acf7b426f022036c312b1e38ca333fe70aa37d3093387ac7486f08438eb8eed323699594468cb012102275a197f7ccfece19cf0532b068b6e38ceceda146e791875ecbdc55500bb7efe00000000',
148
+ },
149
+ },
150
+ {
151
+ args: {
152
+ inputs: [{
153
+ id: 'cbebc4da731e8995fe97f6fadcd731b36ad40e5ecb31e38e904f6e5982fa09f7',
154
+ script: '20ca42095840735e89283fec298e62ac2ddea9b5f34a8cbb7097ad965b87568100201b1b01dc829177da4a14551d2fc96a9db00c6501edfa12f22cd9cefd335c227f483045022100a9df60536df5733dd0de6bc921fab0b3eee6426501b43a228afa2c90072eb5ca02201c78b74266fac7d1db5deff080d8a403743203f109fbcabf6d5a760bf87386d20100',
155
+ sequence: 4294967295,
156
+ vout: 0,
157
+ }],
158
+ locktime: 0,
159
+ outputs: [{
160
+ script: '2103611f9a45c18f28f06f19076ad571c344c82ce8fcfe34464cf8085217a2d294a6ac',
161
+ tokens: 7960000,
162
+ }],
163
+ version: 1,
164
+ },
165
+ description: 'A non-segwit transaction is formed',
166
+ expected: {
167
+ transaction: '0100000001f709fa82596e4f908ee331cb5e0ed46ab331d7dcfaf697fe95891e73dac4ebcb000000008c20ca42095840735e89283fec298e62ac2ddea9b5f34a8cbb7097ad965b87568100201b1b01dc829177da4a14551d2fc96a9db00c6501edfa12f22cd9cefd335c227f483045022100a9df60536df5733dd0de6bc921fab0b3eee6426501b43a228afa2c90072eb5ca02201c78b74266fac7d1db5deff080d8a403743203f109fbcabf6d5a760bf87386d20100ffffffff01c075790000000000232103611f9a45c18f28f06f19076ad571c344c82ce8fcfe34464cf8085217a2d294a6ac00000000',
168
+ },
169
+ },
170
+ ];
171
+
172
+ tests.forEach(({args, description, error, expected}) => {
173
+ return test(description, (t, end) => {
174
+ if (!!error) {
175
+ throws(() => transactionFromComponents(args), new Error(error), 'Err');
176
+ } else {
177
+ const res = transactionFromComponents(args);
178
+
179
+ deepStrictEqual(res, expected, 'Got expected result');
180
+
181
+ const components = componentsOfTransaction(res);
182
+
183
+ deepStrictEqual(
184
+ transactionFromComponents(components),
185
+ expected,
186
+ 'Components round trip back to the transaction'
187
+ );
188
+ }
189
+
190
+ return end();
191
+ });
192
+ });
@@ -4,6 +4,7 @@ const noLocktimeIdForTransaction = require('./no_locktime_id_for_transaction');
4
4
  const parseTransaction = require('./parse_transaction');
5
5
  const queryTransactions = require('./query_transactions');
6
6
  const sizeOfTransaction = require('./size_of_transaction');
7
+ const transactionFromComponents = require('./transaction_from_components');
7
8
  const unsignedTxFromPsbt = require('./unsigned_tx_from_psbt');
8
9
 
9
10
  module.exports = {
@@ -13,5 +14,6 @@ module.exports = {
13
14
  parseTransaction,
14
15
  queryTransactions,
15
16
  sizeOfTransaction,
17
+ transactionFromComponents,
16
18
  unsignedTxFromPsbt,
17
19
  };
@@ -0,0 +1,156 @@
1
+ const {numberAsCompactInt} = require('./../numbers');
2
+
3
+ const {alloc} = Buffer;
4
+ const bufferAsHex = buffer => buffer.toString('hex');
5
+ const byteCountInt32 = 4;
6
+ const byteCountInt64 = 8;
7
+ const {concat} = Buffer;
8
+ const encodeCount = number => numberAsCompactInt({number}).encoded;
9
+ const hexAsBuffer = hex => Buffer.from(hex, 'hex');
10
+ const {isArray} = Array;
11
+ const isHex = n => !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
12
+ const isTxId = n => /^[0-9A-F]{64}$/i.test(n);
13
+ const markerAndFlag = Buffer.from([0x00, 0x01]);
14
+ const txIdAsTxHash = id => hexAsBuffer(id).reverse();
15
+
16
+ /** Form a hex-encoded transaction from its component elements
17
+
18
+ {
19
+ inputs: [{
20
+ id: <Spending Transaction Id Hex String>
21
+ script: <ScriptSig Script Hex String>
22
+ sequence: <Sequence Number>
23
+ vout: <Spending Transaction Output Index Number>
24
+ [witness]: [<Script Stack Element Hex String>]
25
+ }]
26
+ locktime: <Timelock nLockTime Number>
27
+ outputs: [{
28
+ script: <ScriptPub Script Hex String>
29
+ tokens: <Tokens Count Number>
30
+ }]
31
+ version: <Version Number>
32
+ }
33
+
34
+ @throws
35
+ <Error>
36
+
37
+ @returns
38
+ {
39
+ transaction: <Hex Encoded Transaction String>
40
+ }
41
+ */
42
+ module.exports = ({inputs, locktime, outputs, version}) => {
43
+ if (!isArray(inputs)) {
44
+ throw new Error('ExpectedArrayOfInputsToFormTransactionFromComponents');
45
+ }
46
+
47
+ if (!!inputs.find(input => !input || !isTxId(input.id))) {
48
+ throw new Error('ExpectedSpendingTransactionIdsToFormTransaction');
49
+ }
50
+
51
+ if (!!inputs.find(input => !isHex(input.script || ''))) {
52
+ throw new Error('ExpectedHexEncodedInputScriptsToFormTransaction');
53
+ }
54
+
55
+ if (locktime === undefined) {
56
+ throw new Error('ExpectedLocktimeToFormTransactionFromComponents');
57
+ }
58
+
59
+ if (!isArray(outputs)) {
60
+ throw new Error('ExpectedArrayOfOutputsToFormTransactionFromComponents');
61
+ }
62
+
63
+ if (!!outputs.find(output => !output || !isHex(output.script || ''))) {
64
+ throw new Error('ExpectedHexEncodedOutputScriptsToFormTransaction');
65
+ }
66
+
67
+ if (version === undefined) {
68
+ throw new Error('ExpectedVersionNumberToFormTransactionFromComponents');
69
+ }
70
+
71
+ // The presence of any input witness indicates SegWit tx encoding
72
+ const isSegWit = !!inputs.find(input => isArray(input.witness));
73
+
74
+ const elements = [];
75
+
76
+ // Write the signed transaction version number
77
+ const ver = alloc(byteCountInt32);
78
+
79
+ ver.writeInt32LE(version);
80
+
81
+ elements.push(ver);
82
+
83
+ // SegWit transactions lead with marker and flag bytes
84
+ if (isSegWit) {
85
+ elements.push(markerAndFlag);
86
+ }
87
+
88
+ // Write how many inputs there are
89
+ elements.push(encodeCount(inputs.length));
90
+
91
+ // Write the inputs
92
+ elements.push(concat(inputs.map(input => {
93
+ const script = hexAsBuffer(input.script);
94
+
95
+ // Encode the sequence number
96
+ const sequence = alloc(byteCountInt32);
97
+
98
+ sequence.writeUInt32LE(input.sequence);
99
+
100
+ // Encode the spend output index
101
+ const vout = alloc(byteCountInt32);
102
+
103
+ vout.writeUInt32LE(input.vout);
104
+
105
+ // Write the spend outpoint, script sig, sequence number
106
+ return concat([
107
+ txIdAsTxHash(input.id),
108
+ vout,
109
+ encodeCount(script.length),
110
+ script,
111
+ sequence,
112
+ ]);
113
+ })));
114
+
115
+ // Write the outputs count
116
+ elements.push(encodeCount(outputs.length));
117
+
118
+ // Write the outputs
119
+ elements.push(concat(outputs.map(output => {
120
+ const script = hexAsBuffer(output.script);
121
+
122
+ // Encode the output value
123
+ const value = alloc(byteCountInt64);
124
+
125
+ value.writeBigUInt64LE(BigInt(output.tokens));
126
+
127
+ // Write the output value and output script
128
+ return concat([value, encodeCount(script.length), script]);
129
+ })));
130
+
131
+ // SegWit places the input witnesses after the outputs
132
+ if (isSegWit) {
133
+ elements.push(concat(inputs.map(input => {
134
+ const witness = input.witness || [];
135
+
136
+ // Write the witness stack element count and the stack elements
137
+ return concat([
138
+ encodeCount(witness.length),
139
+ concat(witness.map(element => {
140
+ const item = hexAsBuffer(element);
141
+
142
+ return concat([encodeCount(item.length), item]);
143
+ })),
144
+ ]);
145
+ })));
146
+ }
147
+
148
+ // The final element is the 4 byte transaction nLockTime
149
+ const timelock = alloc(byteCountInt32);
150
+
151
+ timelock.writeUInt32LE(locktime);
152
+
153
+ elements.push(timelock);
154
+
155
+ return {transaction: bufferAsHex(concat(elements))};
156
+ };