@alexbosworth/blockchain 4.1.1 → 4.2.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.
@@ -0,0 +1,48 @@
1
+ const bitsPerByte = 8;
2
+ const bitsPerWord = 5;
3
+ const {isBuffer} = Buffer;
4
+ const wordMask = 31;
5
+
6
+ /** Map 8 bit bytes to 5 bit data words, zero padding the remaining bits
7
+
8
+ {
9
+ bytes: <Data Bytes Buffer Object>
10
+ }
11
+
12
+ @throws
13
+ <Error>
14
+
15
+ @returns
16
+ {
17
+ words: [<5-Bit Data Word Number>]
18
+ }
19
+ */
20
+ module.exports = ({bytes}) => {
21
+ if (!isBuffer(bytes)) {
22
+ throw new Error('ExpectedDataBytesToConvertToDataWords');
23
+ }
24
+
25
+ let bits = 0;
26
+ let carry = 0;
27
+ const words = [];
28
+
29
+ // Convert the 8 bit (ie bytes) data into 5 bit words
30
+ bytes.forEach(byte => {
31
+ carry = (carry << bitsPerByte) | byte;
32
+
33
+ bits += bitsPerByte;
34
+
35
+ while (bits >= bitsPerWord) {
36
+ bits -= bitsPerWord;
37
+
38
+ words.push((carry >> bits) & wordMask);
39
+ }
40
+ });
41
+
42
+ // Zero pad the final bits into a trailing word
43
+ if (!!bits) {
44
+ words.push((carry << (bitsPerWord - bits)) & wordMask);
45
+ }
46
+
47
+ return {words};
48
+ };
package/5bit/index.js ADDED
@@ -0,0 +1,4 @@
1
+ const bytesAsWords = require('./bytes_as_words');
2
+ const wordsAsBytes = require('./words_as_bytes');
3
+
4
+ module.exports = {bytesAsWords, wordsAsBytes};
@@ -0,0 +1,66 @@
1
+ const bitsPerByte = 8;
2
+ const bitsPerWord = 5;
3
+ const byteMask = 0xff;
4
+ const bytesArrayAsBuffer = arr => Buffer.from(arr);
5
+ const {isArray} = Array;
6
+ const {isInteger} = Number;
7
+ const maximumWordValue = 31;
8
+ const minimumWordValue = 0;
9
+ const zeroPadding = 0;
10
+
11
+ /** Map 5 bit data words to 8 bit bytes, expecting only zero bit padding
12
+
13
+ {
14
+ words: [<5-Bit Data Word Number>]
15
+ }
16
+
17
+ @throws
18
+ <Error>
19
+
20
+ @returns
21
+ {
22
+ bytes: <Data Bytes Buffer Object>
23
+ }
24
+ */
25
+ module.exports = ({words}) => {
26
+ if (!isArray(words)) {
27
+ throw new Error('ExpectedArrayOfDataWordsToConvertToDataBytes');
28
+ }
29
+
30
+ if (!!words.find(n => !isInteger(n))) {
31
+ throw new Error('ExpectedIntegerDataWordsToConvertToDataBytes');
32
+ }
33
+
34
+ if (!!words.find(n => n < minimumWordValue || n > maximumWordValue)) {
35
+ throw new Error('Expected5BitDataWordValuesToConvertToDataBytes');
36
+ }
37
+
38
+ let bits = 0;
39
+ const bytes = [];
40
+ let carry = 0;
41
+
42
+ // Convert the 5 bit words into 8 bit (ie bytes) data
43
+ words.forEach(word => {
44
+ carry = (carry << bitsPerWord) | word;
45
+
46
+ bits += bitsPerWord;
47
+
48
+ while (bits >= bitsPerByte) {
49
+ bits -= bitsPerByte;
50
+
51
+ bytes.push((carry >> bits) & byteMask);
52
+ }
53
+ });
54
+
55
+ // A full extra word of padding bits is never expected
56
+ if (bits >= bitsPerWord) {
57
+ throw new Error('ExpectedNoPaddingWordsToConvertToDataBytes');
58
+ }
59
+
60
+ // The remaining padding bits are expected to be zeros
61
+ if (((carry << (bitsPerByte - bits)) & byteMask) !== zeroPadding) {
62
+ throw new Error('UnexpectedNonZeroPadding');
63
+ }
64
+
65
+ return {bytes: bytesArrayAsBuffer(bytes)};
66
+ };
package/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Versions
2
2
 
3
+ ## 4.2.0
4
+
5
+ - `encodeBech32Address`: Add method to encode a bech32/bech32m address string
6
+ - `hashForP2wpkh`: Add method to get the p2wpkh hash160 for a public key
7
+
3
8
  ## 4.1.1
4
9
 
5
10
  - `p2msScript`: Add method to get pay to multi-sig script for keys + required
package/README.md CHANGED
@@ -8,6 +8,8 @@ Utility methods for working with Blockchain data
8
8
  - [componentsOfTransaction](#componentsoftransaction)
9
9
  - [decodeBase58Address](#decodebase58address)
10
10
  - [decodeBech32Address](#decodebech32address)
11
+ - [encodeBech32Address](#encodebech32address)
12
+ - [hashForP2wpkh](#hashforp2wpkh)
11
13
  - [idForBlock](#idforblock)
12
14
  - [idForTransaction](#idfortransaction)
13
15
  - [idForTransactionComponents](#idfortransactioncomponents)
@@ -108,11 +110,63 @@ Decode a bech32 address string to derive the address details
108
110
 
109
111
  @returns
110
112
  {
111
- data: <Output Data Buffer Object>
112
113
  prefix: <Human Readable Prefix String>
114
+ program: <Output Data Buffer Object>
113
115
  version: <Witness Version Number>
114
116
  }
115
117
 
118
+ ### encodeBech32Address
119
+
120
+ Encode address details as a bech32 address string
121
+
122
+ {
123
+ prefix: <Human Readable Prefix String>
124
+ program: <Output Data Buffer Object>
125
+ version: <Witness Version Number>
126
+ }
127
+
128
+ @throws
129
+ <Error>
130
+
131
+ @returns
132
+ {
133
+ address: <Bech32 Encoded Address String>
134
+ }
135
+
136
+ Example:
137
+
138
+ ```node
139
+ const {encodeBech32Address, hashForP2wpkh} = require('@alexbosworth/blockchain');
140
+
141
+ // The P2WPKH witness program is the hash160 of the compressed public key
142
+ const {hash} = hashForP2wpkh({key: publicKey});
143
+
144
+ // Encode the P2WPKH address paying to the public key hash
145
+ const {address} = encodeBech32Address({
146
+ prefix: 'bc',
147
+ program: hash,
148
+ version: 0,
149
+ });
150
+ ```
151
+
152
+ ### hashForP2wpkh
153
+
154
+ Get the hash160 of a public key to pay to via P2WPKH
155
+
156
+ Use `hash` with `p2wpkhOutputScript` for a P2WPKH output script
157
+
158
+ {
159
+ key: <Public Key Buffer Object>
160
+ }
161
+
162
+ @throws
163
+ <Error>
164
+
165
+ @returns
166
+ {
167
+ hash: <Public Key Hash160 Buffer Object>
168
+ }
169
+
116
170
  ### idForBlock
117
171
 
118
172
  Get an id for a block: the double sha256 hash of the block header
@@ -4,6 +4,8 @@ const codeForBech32 = 1;
4
4
  const codeForBech32m = 0x2bc830a3;
5
5
  const {from} = Array;
6
6
  const separator = 0;
7
+ const wordBits = 5;
8
+ const wordMask = 31;
7
9
 
8
10
  /** Determine the type of bech32 data being represented and verify checksum
9
11
 
@@ -26,17 +28,17 @@ module.exports = ({prefix, words}) => {
26
28
  // Collect the high bits
27
29
  const highBits = from(
28
30
  {length: prefix.length},
29
- (_, i) => prefix.charCodeAt(i) >> 5
31
+ (_, i) => prefix.charCodeAt(i) >> wordBits
30
32
  );
31
33
 
32
34
  // Collect the low bits
33
35
  const lowBits = from(
34
36
  {length: prefix.length},
35
- (_, i) => prefix.charCodeAt(i) & 31
37
+ (_, i) => prefix.charCodeAt(i) & wordMask
36
38
  );
37
39
 
38
40
  [...highBits, separator, ...lowBits, ...words].forEach(v => {
39
- return accumulator = modifyBech32Accumulator(accumulator) ^ (v & 31);
41
+ return accumulator = modifyBech32Accumulator(accumulator) ^ (v & wordMask);
40
42
  });
41
43
 
42
44
  switch (accumulator) {
@@ -1,9 +1,6 @@
1
1
  const decodeBech32 = require('./decode_bech32');
2
+ const {wordsAsBytes} = require('./../5bit');
2
3
 
3
- const bitsPerBech32Word = 5;
4
- const bitsPerByte = 8;
5
- const byteMask = 0xff;
6
- const bytesArrayAsBuffer = arr => Buffer.from(arr);
7
4
  const knownV0ProgramLengths = [20, 32];
8
5
  const maxProgLength = 40;
9
6
  const maximumSegwitVersion = 16;
@@ -49,38 +46,16 @@ module.exports = ({address}) => {
49
46
  throw new Error('ExpectedUseOfLaterVersionBech32PostInitialSegwit');
50
47
  }
51
48
 
52
- let bits = 0;
53
- let carry = 0;
54
- const program = [];
55
-
56
49
  // Convert the 5 bit bech32 words into 8 bit (ie bytes) data
57
- data.forEach(value => {
58
- carry = (carry << bitsPerBech32Word) | value;
59
-
60
- bits += bitsPerBech32Word;
61
-
62
- while (bits >= bitsPerByte) {
63
- bits -= bitsPerByte;
64
-
65
- program.push((carry >> bits) & byteMask);
66
- }
67
- });
68
-
69
- if (bits >= bitsPerBech32Word) {
70
- throw new Error('ExpectedNoPaddingOnBech32Address');
71
- };
72
-
73
- if (((carry << (bitsPerByte - bits)) & byteMask) !== 0) {
74
- throw new Error('UnexpectedNonZeroPadding');
75
- }
50
+ const {bytes} = wordsAsBytes({words: data});
76
51
 
77
- if (program.length < minimumProgLength || program.length > maxProgLength) {
52
+ if (bytes.length < minimumProgLength || bytes.length > maxProgLength) {
78
53
  throw new Error('UnexpectedSizeOfBech32AddressProgram');
79
54
  }
80
55
 
81
- if (version === 0 && !knownV0ProgramLengths.includes(program.length)) {
56
+ if (version === 0 && !knownV0ProgramLengths.includes(bytes.length)) {
82
57
  throw new Error('UnexpectedBech32AddressProgramSizeForV0Address')
83
58
  }
84
59
 
85
- return {version, prefix, program: bytesArrayAsBuffer(program)};
60
+ return {version, prefix, program: bytes};
86
61
  };
@@ -0,0 +1,92 @@
1
+ const modifyBech32Accumulator = require('./modify_bech32_accumulator');
2
+
3
+ const alphabet = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
4
+ const checksumLength = 6;
5
+ const codeForBech32 = 1;
6
+ const codeForBech32m = 0x2bc830a3;
7
+ const emptySum = [0, 0, 0, 0, 0, 0];
8
+ const {from} = Array;
9
+ const {isArray} = Array;
10
+ const {isInteger} = Number;
11
+ const join = arr => arr.join('');
12
+ const knownPrefixes = ['bc', 'tb', 'bcrt'];
13
+ const knownTypes = ['bech32', 'bech32m'];
14
+ const maximumWordValue = 31;
15
+ const minimumWordValue = 0;
16
+ const prefixDividerCharacter = '1';
17
+ const separator = 0;
18
+ const typeInitialSegwit = 'bech32';
19
+ const wordBits = 5;
20
+ const wordMask = 31;
21
+
22
+ /** Encode data words as a Bech32/Bech32m string with a checksum
23
+
24
+ {
25
+ prefix: <Lowercase Human Readable Prefix String>
26
+ type: <Bech32 Type String>
27
+ words: [<Bech32 5-Bit Data Number>]
28
+ }
29
+
30
+ @throws
31
+ <Error>
32
+
33
+ @returns
34
+ {
35
+ encoded: <Bech32/Bech32m Encoded String>
36
+ }
37
+ */
38
+ module.exports = ({prefix, type, words}) => {
39
+ if (!knownPrefixes.includes(prefix)) {
40
+ throw new Error('ExpectedKnownBech32AddressPrefixToEncodeBech32');
41
+ }
42
+
43
+ if (!knownTypes.includes(type)) {
44
+ throw new Error('ExpectedKnownBech32TypeToEncodeBech32String');
45
+ }
46
+
47
+ if (!isArray(words)) {
48
+ throw new Error('ExpectedArrayOfDataWordsToEncodeBech32String');
49
+ }
50
+
51
+ if (!!words.find(n => !isInteger(n))) {
52
+ throw new Error('ExpectedIntegerDataWordsToEncodeBech32String');
53
+ }
54
+
55
+ if (!!words.find(n => n < minimumWordValue || n > maximumWordValue)) {
56
+ throw new Error('Expected5BitDataWordValuesToEncodeBech32String');
57
+ }
58
+
59
+ let accumulator = 1;
60
+ const code = type === typeInitialSegwit ? codeForBech32 : codeForBech32m;
61
+
62
+ // Collect the high bits
63
+ const highBits = from(
64
+ {length: prefix.length},
65
+ (_, i) => prefix.charCodeAt(i) >> wordBits
66
+ );
67
+
68
+ // Collect the low bits
69
+ const lowBits = from(
70
+ {length: prefix.length},
71
+ (_, i) => prefix.charCodeAt(i) & wordMask
72
+ );
73
+
74
+ // Run the checksum calculation with an empty checksum placeholder
75
+ [...highBits, separator, ...lowBits, ...words, ...emptySum].forEach(v => {
76
+ return accumulator = modifyBech32Accumulator(accumulator) ^ (v & wordMask);
77
+ });
78
+
79
+ // Finalize the checksum for the bech32 type
80
+ const checksum = accumulator ^ code;
81
+
82
+ // Pull the checksum words out of the checksum value, highest bits first
83
+ const checksumWords = from(
84
+ {length: checksumLength},
85
+ (_, i) => (checksum >> ((checksumLength - 1 - i) * wordBits)) & wordMask
86
+ );
87
+
88
+ // Map the data and checksum words to alphabet characters
89
+ const data = [...words, ...checksumWords].map(word => alphabet[word]);
90
+
91
+ return {encoded: prefix + prefixDividerCharacter + join(data)};
92
+ };
@@ -0,0 +1,62 @@
1
+ const {bytesAsWords} = require('./../5bit');
2
+ const encodeBech32 = require('./encode_bech32');
3
+
4
+ const {isBuffer} = Buffer;
5
+ const {isInteger} = Number;
6
+ const knownV0ProgramLengths = [20, 32];
7
+ const maximumSegwitVersion = 16;
8
+ const maxProgLength = 40;
9
+ const minimumProgLength = 2;
10
+ const typeBech32V1 = 'bech32m';
11
+ const typeInitialSegwit = 'bech32';
12
+ const versionInitialSegwit = 0;
13
+
14
+ /** Encode address details as a bech32 address string
15
+
16
+ {
17
+ prefix: <Human Readable Prefix String>
18
+ program: <Output Data Buffer Object>
19
+ version: <Witness Version Number>
20
+ }
21
+
22
+ @throws
23
+ <Error>
24
+
25
+ @returns
26
+ {
27
+ address: <Bech32 Encoded Address String>
28
+ }
29
+ */
30
+ module.exports = ({prefix, program, version}) => {
31
+ if (!isBuffer(program)) {
32
+ throw new Error('ExpectedWitnessProgramToEncodeBech32Address');
33
+ }
34
+
35
+ if (program.length < minimumProgLength || program.length > maxProgLength) {
36
+ throw new Error('UnexpectedSizeOfProgramToEncodeBech32Address');
37
+ }
38
+
39
+ if (!isInteger(version) || version < versionInitialSegwit) {
40
+ throw new Error('ExpectedKnownWitnessVersionToEncodeBech32Address');
41
+ }
42
+
43
+ if (version > maximumSegwitVersion) {
44
+ throw new Error('UnexpectedHighSegwitWitnessVersion');
45
+ }
46
+
47
+ const isV0 = version === versionInitialSegwit;
48
+
49
+ if (isV0 && !knownV0ProgramLengths.includes(program.length)) {
50
+ throw new Error('UnexpectedBech32AddressProgramSizeForV0Address');
51
+ }
52
+
53
+ // Initial segwit uses bech32, later witness versions use bech32m
54
+ const type = isV0 ? typeInitialSegwit : typeBech32V1;
55
+
56
+ // Convert the 8 bit (ie bytes) data into 5 bit bech32 words
57
+ const {words} = bytesAsWords({bytes: program});
58
+
59
+ const {encoded} = encodeBech32({prefix, type, words: [version, ...words]});
60
+
61
+ return {address: encoded};
62
+ };
@@ -1,4 +1,9 @@
1
1
  const decodeBase58Address = require('./decode_base58_address');
2
2
  const decodeBech32Address = require('./decode_bech32_address');
3
+ const encodeBech32Address = require('./encode_bech32_address');
3
4
 
4
- module.exports = {decodeBase58Address, decodeBech32Address};
5
+ module.exports = {
6
+ decodeBase58Address,
7
+ decodeBech32Address,
8
+ encodeBech32Address,
9
+ };
@@ -0,0 +1,34 @@
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 to pay to via P2WPKH
9
+
10
+ Use `hash` with `p2wpkhOutputScript` for a P2WPKH output script
11
+
12
+ {
13
+ key: <Public Key Buffer Object>
14
+ }
15
+
16
+ @throws
17
+ <Error>
18
+
19
+ @returns
20
+ {
21
+ hash: <Public Key Hash160 Buffer Object>
22
+ }
23
+ */
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
+ };
package/hashes/index.js CHANGED
@@ -1,8 +1,10 @@
1
+ const hashForP2wpkh = require('./hash_for_p2wpkh');
1
2
  const idForBlock = require('./id_for_block');
2
3
  const idForTransactionComponents = require('./id_for_transaction_components');
3
4
  const previousBlockId = require('./previous_block_id');
4
5
 
5
6
  module.exports = {
7
+ hashForP2wpkh,
6
8
  idForBlock,
7
9
  idForTransactionComponents,
8
10
  previousBlockId,
package/index.js CHANGED
@@ -2,6 +2,8 @@ const {compactIntAsNumber} = require('./numbers');
2
2
  const {componentsOfTransaction} = require('./transactions');
3
3
  const {decodeBase58Address} = require('./addresses');
4
4
  const {decodeBech32Address} = require('./addresses');
5
+ const {encodeBech32Address} = require('./addresses');
6
+ const {hashForP2wpkh} = require('./hashes');
5
7
  const {idForBlock} = require('./hashes');
6
8
  const {idForTransaction} = require('./transactions');
7
9
  const {idForTransactionComponents} = require('./hashes');
@@ -25,6 +27,8 @@ module.exports = {
25
27
  componentsOfTransaction,
26
28
  decodeBase58Address,
27
29
  decodeBech32Address,
30
+ encodeBech32Address,
31
+ hashForP2wpkh,
28
32
  idForBlock,
29
33
  idForTransaction,
30
34
  idForTransactionComponents,
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "url": "https://github.com/alexbosworth/blockchain.git"
18
18
  },
19
19
  "scripts": {
20
- "test": "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/5bit/*.js test/addresses/*.js test/hashes/*.js test/numbers/*.js test/script/*.js test/transactions/*.js"
21
21
  },
22
- "version": "4.1.1"
22
+ "version": "4.2.0"
23
23
  }
@@ -0,0 +1,49 @@
1
+ const {deepEqual} = require('node:assert').strict;
2
+ const test = require('node:test');
3
+ const {throws} = require('node:assert').strict;
4
+
5
+ const bytesAsWords = require('./../../5bit/bytes_as_words');
6
+
7
+ const hexAsBuffer = hex => Buffer.from(hex, 'hex');
8
+
9
+ const tests = [
10
+ {
11
+ args: {},
12
+ description: 'Data bytes are expected',
13
+ error: 'ExpectedDataBytesToConvertToDataWords',
14
+ },
15
+ {
16
+ args: {bytes: hexAsBuffer('')},
17
+ description: 'No bytes are mapped to no words',
18
+ expected: {words: []},
19
+ },
20
+ {
21
+ args: {bytes: hexAsBuffer('ff')},
22
+ description: 'A single byte is mapped to words with zero padding',
23
+ expected: {words: [31, 28]},
24
+ },
25
+ {
26
+ args: {bytes: hexAsBuffer('751e76e8199196d454941c45d1b3a323f1433bd6')},
27
+ description: 'Bytes are mapped to words',
28
+ expected: {
29
+ words: [
30
+ 14, 20, 15, 7, 13, 26, 0, 25, 18, 6, 11, 13, 8, 21, 4, 20, 3, 17, 2,
31
+ 29, 3, 12, 29, 3, 4, 15, 24, 20, 6, 14, 30, 22,
32
+ ],
33
+ },
34
+ },
35
+ ];
36
+
37
+ tests.forEach(({args, description, error, expected}) => {
38
+ return test(description, (t, end) => {
39
+ if (!!error) {
40
+ throws(() => bytesAsWords(args), new Error(error), 'Err');
41
+ } else {
42
+ const res = bytesAsWords(args);
43
+
44
+ deepEqual(res, expected, 'Got expected result');
45
+ }
46
+
47
+ return end();
48
+ });
49
+ });
@@ -0,0 +1,74 @@
1
+ const {deepEqual} = require('node:assert').strict;
2
+ const test = require('node:test');
3
+ const {throws} = require('node:assert').strict;
4
+
5
+ const wordsAsBytes = require('./../../5bit/words_as_bytes');
6
+
7
+ const hexAsBuffer = hex => Buffer.from(hex, 'hex');
8
+
9
+ const tests = [
10
+ {
11
+ args: {},
12
+ description: 'An array of data words is expected',
13
+ error: 'ExpectedArrayOfDataWordsToConvertToDataBytes',
14
+ },
15
+ {
16
+ args: {words: [1.5]},
17
+ description: 'Integer data words are expected',
18
+ error: 'ExpectedIntegerDataWordsToConvertToDataBytes',
19
+ },
20
+ {
21
+ args: {words: [32]},
22
+ description: 'Data words within the word value range are expected',
23
+ error: 'Expected5BitDataWordValuesToConvertToDataBytes',
24
+ },
25
+ {
26
+ args: {words: [-1]},
27
+ description: 'Unsigned data words are expected',
28
+ error: 'Expected5BitDataWordValuesToConvertToDataBytes',
29
+ },
30
+ {
31
+ args: {words: [31, 28, 0]},
32
+ description: 'A full extra word of padding is not expected',
33
+ error: 'ExpectedNoPaddingWordsToConvertToDataBytes',
34
+ },
35
+ {
36
+ args: {words: [31, 31]},
37
+ description: 'Non-zero padding bits are not expected',
38
+ error: 'UnexpectedNonZeroPadding',
39
+ },
40
+ {
41
+ args: {words: []},
42
+ description: 'No words are mapped to no bytes',
43
+ expected: {bytes: hexAsBuffer('')},
44
+ },
45
+ {
46
+ args: {words: [31, 28]},
47
+ description: 'Words are mapped to a byte, removing zero padding',
48
+ expected: {bytes: hexAsBuffer('ff')},
49
+ },
50
+ {
51
+ args: {
52
+ words: [
53
+ 14, 20, 15, 7, 13, 26, 0, 25, 18, 6, 11, 13, 8, 21, 4, 20, 3, 17, 2,
54
+ 29, 3, 12, 29, 3, 4, 15, 24, 20, 6, 14, 30, 22,
55
+ ],
56
+ },
57
+ description: 'Words are mapped to bytes',
58
+ expected: {bytes: hexAsBuffer('751e76e8199196d454941c45d1b3a323f1433bd6')},
59
+ },
60
+ ];
61
+
62
+ tests.forEach(({args, description, error, expected}) => {
63
+ return test(description, (t, end) => {
64
+ if (!!error) {
65
+ throws(() => wordsAsBytes(args), new Error(error), 'Err');
66
+ } else {
67
+ const res = wordsAsBytes(args);
68
+
69
+ deepEqual(res, expected, 'Got expected result');
70
+ }
71
+
72
+ return end();
73
+ });
74
+ });
@@ -90,7 +90,7 @@ const tests = [
90
90
  address: 'bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7v07qwwzcrf',
91
91
  },
92
92
  description: 'zero padding of more than 4 bits',
93
- error: 'ExpectedNoPaddingOnBech32Address',
93
+ error: 'ExpectedNoPaddingWordsToConvertToDataBytes',
94
94
  },
95
95
  {
96
96
  args: {
@@ -0,0 +1,64 @@
1
+ const {deepEqual} = require('node:assert').strict;
2
+ const test = require('node:test');
3
+ const {throws} = require('node:assert').strict;
4
+
5
+ const encodeBech32 = require('./../../addresses/encode_bech32');
6
+
7
+ const tests = [
8
+ {
9
+ args: {prefix: 'tc', type: 'bech32', words: [0]},
10
+ description: 'A known prefix is expected',
11
+ error: 'ExpectedKnownBech32AddressPrefixToEncodeBech32',
12
+ },
13
+ {
14
+ args: {prefix: 'bc', type: 'bech32k', words: [0]},
15
+ description: 'A known bech32 type is expected',
16
+ error: 'ExpectedKnownBech32TypeToEncodeBech32String',
17
+ },
18
+ {
19
+ args: {prefix: 'bc', type: 'bech32'},
20
+ description: 'An array of data words is expected',
21
+ error: 'ExpectedArrayOfDataWordsToEncodeBech32String',
22
+ },
23
+ {
24
+ args: {prefix: 'bc', type: 'bech32', words: [1.5]},
25
+ description: 'Integer data words are expected',
26
+ error: 'ExpectedIntegerDataWordsToEncodeBech32String',
27
+ },
28
+ {
29
+ args: {prefix: 'bc', type: 'bech32', words: [32]},
30
+ description: 'Data words within the word value range are expected',
31
+ error: 'Expected5BitDataWordValuesToEncodeBech32String',
32
+ },
33
+ {
34
+ args: {
35
+ prefix: 'bc',
36
+ type: 'bech32',
37
+ words: [
38
+ 0, 14, 20, 15, 7, 13, 26, 0, 25, 18, 6, 11, 13, 8, 21, 4, 20, 3, 17,
39
+ 2, 29, 3, 12, 29, 3, 4, 15, 24, 20, 6, 14, 30, 22,
40
+ ],
41
+ },
42
+ description: 'Words are encoded as a bech32 string',
43
+ expected: {encoded: 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4'},
44
+ },
45
+ {
46
+ args: {prefix: 'bc', type: 'bech32m', words: [16, 14, 20, 15, 0]},
47
+ description: 'Words are encoded as a bech32m string',
48
+ expected: {encoded: 'bc1sw50qgdz25j'},
49
+ },
50
+ ];
51
+
52
+ tests.forEach(({args, description, error, expected}) => {
53
+ return test(description, (t, end) => {
54
+ if (!!error) {
55
+ throws(() => encodeBech32(args), new Error(error), 'Err');
56
+ } else {
57
+ const res = encodeBech32(args);
58
+
59
+ deepEqual(res, expected, 'Got expected result');
60
+ }
61
+
62
+ return end();
63
+ });
64
+ });
@@ -0,0 +1,145 @@
1
+ const {deepEqual} = require('node:assert').strict;
2
+ const test = require('node:test');
3
+ const {throws} = require('node:assert').strict;
4
+
5
+ const {encodeBech32Address} = require('./../../');
6
+
7
+ const hexAsBuffer = hex => Buffer.from(hex, 'hex');
8
+
9
+ const tests = [
10
+ {
11
+ args: {prefix: 'bc', version: 0},
12
+ description: 'A witness program is expected',
13
+ error: 'ExpectedWitnessProgramToEncodeBech32Address',
14
+ },
15
+ {
16
+ args: {prefix: 'bc', program: hexAsBuffer('75'), version: 16},
17
+ description: 'A minimum length witness program is expected',
18
+ error: 'UnexpectedSizeOfProgramToEncodeBech32Address',
19
+ },
20
+ {
21
+ args: {
22
+ prefix: 'bc',
23
+ program: hexAsBuffer('751e76e8199196d454941c45d1b3a323f1433bd6751e76e8199196d454941c45d1b3a323f1433bd675'),
24
+ version: 1,
25
+ },
26
+ description: 'A maximum length witness program is expected',
27
+ error: 'UnexpectedSizeOfProgramToEncodeBech32Address',
28
+ },
29
+ {
30
+ args: {
31
+ prefix: 'bc',
32
+ program: hexAsBuffer('751e76e8199196d454941c45d1b3a323f1433bd6'),
33
+ },
34
+ description: 'A witness version is expected',
35
+ error: 'ExpectedKnownWitnessVersionToEncodeBech32Address',
36
+ },
37
+ {
38
+ args: {
39
+ prefix: 'bc',
40
+ program: hexAsBuffer('751e76e8199196d454941c45d1b3a323f1433bd6'),
41
+ version: 17,
42
+ },
43
+ description: 'A witness version within the known range is expected',
44
+ error: 'UnexpectedHighSegwitWitnessVersion',
45
+ },
46
+ {
47
+ args: {
48
+ prefix: 'bc',
49
+ program: hexAsBuffer('751e76e8199196d454941c45d1b3a323f1433b'),
50
+ version: 0,
51
+ },
52
+ description: 'A known program length for witness version 0 is expected',
53
+ error: 'UnexpectedBech32AddressProgramSizeForV0Address',
54
+ },
55
+ {
56
+ args: {
57
+ prefix: 'tc',
58
+ program: hexAsBuffer('751e76e8199196d454941c45d1b3a323f1433bd6'),
59
+ version: 0,
60
+ },
61
+ description: 'A known human readable prefix is expected',
62
+ error: 'ExpectedKnownBech32AddressPrefixToEncodeBech32',
63
+ },
64
+ {
65
+ args: {
66
+ prefix: 'bc',
67
+ program: hexAsBuffer('751e76e8199196d454941c45d1b3a323f1433bd6'),
68
+ version: 0,
69
+ },
70
+ description: 'An address is encoded for a bc1q output',
71
+ expected: {address: 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4'},
72
+ },
73
+ {
74
+ args: {
75
+ prefix: 'tb',
76
+ program: hexAsBuffer('1863143c14c5166804bd19203356da136c985678cd4d27a1b8c6329604903262'),
77
+ version: 0,
78
+ },
79
+ description: 'An address is encoded for a tb1q output',
80
+ expected: {
81
+ address: 'tb1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3q0sl5k7',
82
+ },
83
+ },
84
+ {
85
+ args: {
86
+ prefix: 'bc',
87
+ program: hexAsBuffer('751e76e8199196d454941c45d1b3a323f1433bd6751e76e8199196d454941c45d1b3a323f1433bd6'),
88
+ version: 1,
89
+ },
90
+ description: 'An address is encoded for a bc1p output',
91
+ expected: {
92
+ address: 'bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kt5nd6y',
93
+ },
94
+ },
95
+ {
96
+ args: {prefix: 'bc', program: hexAsBuffer('751e'), version: 16},
97
+ description: 'An address is encoded for a short bc1 output',
98
+ expected: {address: 'bc1sw50qgdz25j'},
99
+ },
100
+ {
101
+ args: {
102
+ prefix: 'bc',
103
+ program: hexAsBuffer('751e76e8199196d454941c45d1b3a323'),
104
+ version: 2,
105
+ },
106
+ description: 'An address is encoded for a midsize bc1 output',
107
+ expected: {address: 'bc1zw508d6qejxtdg4y5r3zarvaryvaxxpcs'},
108
+ },
109
+ {
110
+ args: {
111
+ prefix: 'tb',
112
+ program: hexAsBuffer('000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433'),
113
+ version: 0,
114
+ },
115
+ description: 'An address is encoded for a zero starting tb output',
116
+ expected: {
117
+ address: 'tb1qqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesrxh6hy',
118
+ },
119
+ },
120
+ {
121
+ args: {
122
+ prefix: 'bc',
123
+ program: hexAsBuffer('79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),
124
+ version: 1,
125
+ },
126
+ description: 'An address is encoded for a bc1 v1 output',
127
+ expected: {
128
+ address: 'bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0',
129
+ },
130
+ },
131
+ ];
132
+
133
+ tests.forEach(({args, description, error, expected}) => {
134
+ return test(description, (t, end) => {
135
+ if (!!error) {
136
+ throws(() => encodeBech32Address(args), new Error(error), 'Err');
137
+ } else {
138
+ const res = encodeBech32Address(args);
139
+
140
+ deepEqual(res, expected, 'Got expected result');
141
+ }
142
+
143
+ return end();
144
+ });
145
+ });
@@ -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 {hashForP2wpkh} = 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: 'ExpectedPublicKeyToDeriveHashForP2wpkh',
14
+ },
15
+ {
16
+ args: {
17
+ key: bufferFromHex('0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),
18
+ },
19
+ description: 'A compressed public key is required',
20
+ error: 'ExpectedCompressedPublicKeyToDeriveHashForP2wpkh',
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(() => hashForP2wpkh(args), new Error(error), 'Got err');
46
+ } else {
47
+ const res = hashForP2wpkh(args);
48
+
49
+ deepStrictEqual(res, expected, 'Got expected result');
50
+ }
51
+
52
+ return end();
53
+ });
54
+ });