@alexbosworth/blockchain 4.7.1 → 4.8.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,6 +1,10 @@
1
1
  # Versions
2
2
 
3
- ## 4.7.1
3
+ ## 4.8.0
4
+
5
+ - `decodeBase58`: Add method to decode a base58check string into its payload
6
+
7
+ ## 4.7.2
4
8
 
5
9
  - `nonWitnessHashToSign`: Add method to calculate the pre-SegWit hash to sign
6
10
 
package/README.md CHANGED
@@ -6,6 +6,7 @@ Utility methods for working with Blockchain data
6
6
 
7
7
  - [compactIntAsNumber](#compactintasnumber)
8
8
  - [componentsOfTransaction](#componentsoftransaction)
9
+ - [decodeBase58](#decodebase58)
9
10
  - [decodeBase58Address](#decodebase58address)
10
11
  - [decodeBech32Address](#decodebech32address)
11
12
  - [encodeBase58Address](#encodebase58address)
@@ -85,6 +86,22 @@ Get the components of a hex-encoded transaction
85
86
  version: <Version Number>
86
87
  }
87
88
 
89
+ ### decodeBase58
90
+
91
+ Decode a base58check encoded string into its payload
92
+
93
+ {
94
+ encoded: <Base58Check Encoded String>
95
+ }
96
+
97
+ @throws
98
+ <Error> when the string has invalid characters or a bad checksum
99
+
100
+ @returns
101
+ {
102
+ payload: <Decoded Payload Buffer Object>
103
+ }
104
+
88
105
  ### decodeBase58Address
89
106
 
90
107
  Derive output hash and version data from a base58 address string
@@ -0,0 +1,119 @@
1
+ const {createHash} = require('crypto');
2
+
3
+ const base58Alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
4
+ const byteMask = 0xff;
5
+ const {ceil} = Math;
6
+ const countChecksumBytes = 4;
7
+ const leadingZeroCharCode = 0x31;
8
+ const notFoundIndex = -1;
9
+ const sha256 = preimage => createHash('sha256').update(preimage).digest();
10
+
11
+ /** Decode a base58check encoded string into its payload
12
+
13
+ {
14
+ encoded: <Base58Check Encoded String>
15
+ }
16
+
17
+ @throws
18
+ <Error> when the string has invalid characters or a bad checksum
19
+
20
+ @returns
21
+ {
22
+ payload: <Decoded Payload Buffer Object>
23
+ }
24
+ */
25
+ module.exports = ({encoded}) => {
26
+ if (typeof encoded !== 'string') {
27
+ throw new Error('ExpectedBase58CheckStringToDecode');
28
+ }
29
+
30
+ // Ignore encoded string whitespace
31
+ const str = encoded.trim();
32
+
33
+ // Exit early with error on empty string, since there is nothing to decode
34
+ if (!str.length) {
35
+ throw new Error('ExpectedNonEmptyBase58CheckStringToDecode');
36
+ }
37
+
38
+ let bytesLength = 0;
39
+ let countLeadingZeros = 0;
40
+ let index = 0;
41
+
42
+ // Iterate to determine the number of leading zeros to preserve
43
+ while (index < str.length && str.charCodeAt(index) === leadingZeroCharCode) {
44
+ countLeadingZeros++;
45
+ index++;
46
+ }
47
+
48
+ // Total bytes needed are log(58) / log(256) (256 values in a byte) = 0.732..
49
+ const workingSize = ceil((str.length - index) * 733 / 1000);
50
+
51
+ // Working buffer for the base256 (byte) representation, right-aligned
52
+ const working = new Uint8Array(workingSize);
53
+
54
+ // Iterate through the encoded characters and grab the decoded bytes
55
+ while (index < str.length) {
56
+ const value = base58Alphabet.indexOf(str[index]);
57
+
58
+ if (value === notFoundIndex) {
59
+ throw new Error('ExpectedAllBase58CharactersInBase58CheckString');
60
+ }
61
+
62
+ let carry = value;
63
+ let i = 0;
64
+
65
+ for (
66
+ let position = workingSize - 1;
67
+ (carry !== 0 || i < bytesLength) && position >= 0;
68
+ --position, ++i
69
+ ) {
70
+ carry += base58Alphabet.length * working[position];
71
+
72
+ // Take the least-significant byte
73
+ working[position] = carry & byteMask;
74
+
75
+ // Carry forward the remaining bytes
76
+ carry = (carry / 256) | 0;
77
+ }
78
+
79
+ // Track the number of bytes being used
80
+ bytesLength = i;
81
+
82
+ // Move to the next character in the encoded string
83
+ index++;
84
+ }
85
+
86
+ // Meaningful bytes are right-aligned in working
87
+ const bytesStart = workingSize - bytesLength;
88
+ const meaningfulCount = workingSize - bytesStart;
89
+
90
+ // Final buffer: leading zeros plus meaningful bytes
91
+ const decoded = Buffer.alloc(countLeadingZeros + meaningfulCount);
92
+
93
+ // Make a view into the meaningful bytes
94
+ const dataBytes = working.subarray(bytesStart, bytesStart + meaningfulCount);
95
+
96
+ // Copy the meaningful bytes into the final decoded data
97
+ decoded.set(dataBytes, countLeadingZeros);
98
+
99
+ // Exit early with error when we don't have both a payload and checksum
100
+ if (decoded.length <= countChecksumBytes) {
101
+ throw new Error('ExpectedPayloadAndChecksumInBase58CheckString');
102
+ }
103
+
104
+ // The last bytes of a base58check string are a double sha256 checksum
105
+ const checksum = decoded.subarray(decoded.length - countChecksumBytes);
106
+
107
+ // Everything before the checksum is the payload
108
+ const payload = decoded.subarray(0, decoded.length - countChecksumBytes);
109
+
110
+ // Calculate the checksum for the given payload
111
+ const payloadCheck = sha256(sha256(payload)).subarray(0, countChecksumBytes);
112
+
113
+ // Exit early with error when the double SHA256 of payload doesn't match
114
+ if (!checksum.equals(payloadCheck)) {
115
+ throw new Error('ExpectedValidPayloadChecksumInBase58CheckString');
116
+ }
117
+
118
+ return {payload: Buffer.from(payload)};
119
+ };
@@ -1,14 +1,7 @@
1
- const {createHash} = require('crypto');
1
+ const decodeBase58 = require('./decode_base58');
2
2
 
3
- const base58Alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
4
- const byteMask = 0xff;
5
- const {ceil} = Math;
6
- const countChecksumBytes = 4;
7
3
  const countHashBytes = 20;
8
4
  const countVersionBytes = 1;
9
- const leadingZeroCharCode = 0x31;
10
- const notFoundIndex = -1;
11
- const sha256 = preimage => createHash('sha256').update(preimage).digest();
12
5
 
13
6
  /** Derive output hash and version data from a base58 address string
14
7
 
@@ -30,99 +23,14 @@ module.exports = ({address}) => {
30
23
  throw new Error('ExpectedBase58AddressStringToDecode');
31
24
  }
32
25
 
33
- // Ignore address string whitespace
34
- const str = address.trim();
35
-
36
- // Exit early with error on empty address, since it's not an address
37
- if (!str.length) {
38
- throw new Error('ExpectedNonEmptyBase58AddressToDecode');
39
- }
40
-
41
- let bytesLength = 0;
42
- let countLeadingZeros = 0;
43
- let index = 0;
44
-
45
- // Iterate to determine the number of leading zeros to preserve
46
- while (index < str.length && str.charCodeAt(index) === leadingZeroCharCode) {
47
- countLeadingZeros++;
48
- index++;
49
- }
50
-
51
- // Total bytes needed are log(58) / log(256) (256 values in a byte) = 0.732..
52
- const workingSize = ceil((str.length - index) * 733 / 1000);
53
-
54
- // Working buffer for the base256 (byte) representation, right-aligned
55
- const working = new Uint8Array(workingSize);
56
-
57
- // Iterate through the address characters and grab the decoded bytes
58
- while (index < str.length) {
59
- const value = base58Alphabet.indexOf(str[index]);
60
-
61
- if (value === notFoundIndex) {
62
- throw new Error('ExpectedAllBase58CharactersInBase58Address');
63
- }
64
-
65
- let carry = value;
66
- let i = 0;
67
-
68
- for (
69
- let position = workingSize - 1;
70
- (carry !== 0 || i < bytesLength) && position >= 0;
71
- --position, ++i
72
- ) {
73
- carry += base58Alphabet.length * working[position];
74
-
75
- // Take the least-significant byte
76
- working[position] = carry & byteMask;
77
-
78
- // Carry forward the remaining bytes
79
- carry = (carry / 256) | 0;
80
- }
81
-
82
- // Track the number of bytes being used
83
- bytesLength = i;
84
-
85
- // Move to the next character in the address
86
- index++;
87
- }
88
-
89
- // Meaningful bytes are right-aligned in working
90
- const bytesStart = workingSize - bytesLength;
91
- const meaningfulCount = workingSize - bytesStart;
92
-
93
- // Final buffer: leading zeros plus meaningful bytes
94
- const decoded = Buffer.alloc(countLeadingZeros + meaningfulCount);
95
-
96
- // Make a view into the meaningful bytes
97
- const dataBytes = working.subarray(bytesStart, bytesStart + meaningfulCount);
98
-
99
- // Copy the meaningful bytes into the final decoded data
100
- decoded.set(dataBytes, countLeadingZeros);
101
-
102
- // Exit early with error when we don't have both a payload and checksum
103
- if (decoded.length <= countChecksumBytes) {
104
- throw new Error('ExpectedPayloadAndChecksumInBase58Address');
105
- }
106
-
107
- // The last bytes of a base58 address are a double sha256 checksum
108
- const checksum = decoded.subarray(decoded.length - countChecksumBytes);
109
-
110
- // Aside from the checksum there is a version byte and then a hash
111
- const payload = decoded.subarray(0, decoded.length - countChecksumBytes);
26
+ // Decode the base58check string and validate its checksum
27
+ const {payload} = decodeBase58({encoded: address});
112
28
 
113
29
  // Make sure that we have a base58 payload that has the version and hash
114
30
  if (payload.length !== countVersionBytes + countHashBytes) {
115
31
  throw new Error('ExpectedVersionAnd20ByteHashInBase58AddressPayload');
116
32
  }
117
33
 
118
- // Calculate the checksum for the given payload
119
- const payloadCheck = sha256(sha256(payload)).subarray(0, countChecksumBytes);
120
-
121
- // Exit early with error when the double SHA256 of payload doesn't match
122
- if (!checksum.equals(payloadCheck)) {
123
- throw new Error('ExpectedValidPayloadChecksumInBase58Address');
124
- }
125
-
126
34
  const [version] = payload;
127
35
 
128
36
  return {version, hash: payload.subarray(countVersionBytes)};
@@ -1,9 +1,11 @@
1
+ const decodeBase58 = require('./decode_base58');
1
2
  const decodeBase58Address = require('./decode_base58_address');
2
3
  const decodeBech32Address = require('./decode_bech32_address');
3
4
  const encodeBase58Address = require('./encode_base58_address');
4
5
  const encodeBech32Address = require('./encode_bech32_address');
5
6
 
6
7
  module.exports = {
8
+ decodeBase58,
7
9
  decodeBase58Address,
8
10
  decodeBech32Address,
9
11
  encodeBase58Address,
package/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  const {compactIntAsNumber} = require('./numbers');
2
2
  const {componentsOfTransaction} = require('./transactions');
3
+ const {decodeBase58} = require('./addresses');
3
4
  const {decodeBase58Address} = require('./addresses');
4
5
  const {decodeBech32Address} = require('./addresses');
5
6
  const {encodeBase58Address} = require('./addresses');
@@ -30,6 +31,7 @@ const {v0HashToSign} = require('./transactions');
30
31
  module.exports = {
31
32
  compactIntAsNumber,
32
33
  componentsOfTransaction,
34
+ decodeBase58,
33
35
  decodeBase58Address,
34
36
  decodeBech32Address,
35
37
  encodeBase58Address,
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.7.1"
22
+ "version": "4.8.0"
23
23
  }
@@ -0,0 +1,109 @@
1
+ const {deepEqual} = require('node:assert').strict;
2
+ const test = require('node:test');
3
+ const {throws} = require('node:assert').strict;
4
+
5
+ const {decodeBase58} = require('./../../');
6
+
7
+ const hexAsBuffer = hex => Buffer.from(hex, 'hex');
8
+
9
+ const tests = [
10
+ {
11
+ args: {},
12
+ description: 'An encoded string is expected',
13
+ error: 'ExpectedBase58CheckStringToDecode',
14
+ },
15
+ {
16
+ args: {encoded: Buffer.alloc(1)},
17
+ description: 'A string type is expected',
18
+ error: 'ExpectedBase58CheckStringToDecode',
19
+ },
20
+ {
21
+ args: {encoded: ' '},
22
+ description: 'A non-empty encoded string is expected',
23
+ error: 'ExpectedNonEmptyBase58CheckStringToDecode',
24
+ },
25
+ {
26
+ args: {encoded: '16ro3Jptwo4asSevZnsRX6vfRS24TGE6u!'},
27
+ description: 'Characters must be base58 set',
28
+ error: 'ExpectedAllBase58CharactersInBase58CheckString',
29
+ },
30
+ {
31
+ args: {encoded: '16ro3Jptwo4asSevZnsRX6vfRS24TGE6uO'},
32
+ description: 'Ambiguous characters excluded from base58 are rejected',
33
+ error: 'ExpectedAllBase58CharactersInBase58CheckString',
34
+ },
35
+ {
36
+ args: {encoded: '16ro3Jptwo4asSevZnsRX6vfRS24TGE6ul'},
37
+ description: 'Lowercase L is not a base58 character',
38
+ error: 'ExpectedAllBase58CharactersInBase58CheckString',
39
+ },
40
+ {
41
+ args: {encoded: '16ro3Jptwo4asSev ZnsRX6vfRS24TGE6uK'},
42
+ description: 'Interior whitespace is not allowed',
43
+ error: 'ExpectedAllBase58CharactersInBase58CheckString',
44
+ },
45
+ {
46
+ args: {encoded: '1'},
47
+ description: 'Payload and checksum must be present',
48
+ error: 'ExpectedPayloadAndChecksumInBase58CheckString',
49
+ },
50
+ {
51
+ args: {encoded: '1111'},
52
+ description: 'A checksum alone with no payload is rejected',
53
+ error: 'ExpectedPayloadAndChecksumInBase58CheckString',
54
+ },
55
+ {
56
+ args: {encoded: '16ro3Jptwo4asSevZnsRX6vfRS24TGE6uP'},
57
+ description: 'Checksum must match',
58
+ error: 'ExpectedValidPayloadChecksumInBase58CheckString',
59
+ },
60
+ {
61
+ args: {encoded: '16ro3Jptwo4asSevZnsRX6vfRS24TGE6uK'},
62
+ description: 'A p2pkh address payload is decoded',
63
+ expected: {
64
+ payload: hexAsBuffer('00404371705fa9bd789a2fcd52d2c580b65d35549d'),
65
+ },
66
+ },
67
+ {
68
+ args: {encoded: ' 3P14159f73E4gFr7JterCCQh9QjiTjiZrG '},
69
+ description: 'Whitespace is ignored and a p2sh address payload is decoded',
70
+ expected: {
71
+ payload: hexAsBuffer('05e9c3dd0c07aac76179ebc76a6c78d4d67c6c160a'),
72
+ },
73
+ },
74
+ {
75
+ args: {encoded: '5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ'},
76
+ description: 'A WIF private key payload is decoded',
77
+ expected: {
78
+ payload: hexAsBuffer('800c28fca386c7a227600b2fe50b7cae11ec86d3bf1fbe471be89827e19d72aa1d'),
79
+ },
80
+ },
81
+ {
82
+ args: {
83
+ encoded: 'xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8',
84
+ },
85
+ description: 'An extended public key payload is decoded',
86
+ expected: {
87
+ payload: hexAsBuffer('0488b21e000000000000000000873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d5080339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2'),
88
+ },
89
+ },
90
+ {
91
+ args: {encoded: '11146EAsf'},
92
+ description: 'An all zero bytes payload is preserved',
93
+ expected: {payload: hexAsBuffer('000000')},
94
+ },
95
+ ];
96
+
97
+ tests.forEach(({args, description, error, expected}) => {
98
+ return test(description, (t, end) => {
99
+ if (!!error) {
100
+ throws(() => decodeBase58(args), new Error(error), 'Err');
101
+ } else {
102
+ const res = decodeBase58(args);
103
+
104
+ deepEqual(res, expected, 'Got expected result');
105
+ }
106
+
107
+ return end();
108
+ });
109
+ });
@@ -15,27 +15,27 @@ const tests = [
15
15
  {
16
16
  args: {address: ' '},
17
17
  description: 'A non-empty address is expected',
18
- error: 'ExpectedNonEmptyBase58AddressToDecode',
18
+ error: 'ExpectedNonEmptyBase58CheckStringToDecode',
19
19
  },
20
20
  {
21
21
  args: {address: '16ro3Jptwo4asSevZnsRX6vfRS24TGE6uP'},
22
22
  description: 'Address checksum must match',
23
- error: 'ExpectedValidPayloadChecksumInBase58Address',
23
+ error: 'ExpectedValidPayloadChecksumInBase58CheckString',
24
24
  },
25
25
  {
26
- args: {address: '16ro3Jptwo4asSevZnsRX6vfRS24TGE6'},
27
- description: 'Address checksum must be present',
26
+ args: {address: '5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ'},
27
+ description: 'Address payload must be a version and a 20 byte hash',
28
28
  error: 'ExpectedVersionAnd20ByteHashInBase58AddressPayload',
29
29
  },
30
30
  {
31
31
  args: {address: '1'},
32
32
  description: 'Address payload and checksum must be present',
33
- error: 'ExpectedPayloadAndChecksumInBase58Address',
33
+ error: 'ExpectedPayloadAndChecksumInBase58CheckString',
34
34
  },
35
35
  {
36
36
  args: {address: '16ro3Jptwo4asSevZnsRX6vfRS24TGE6u!'},
37
37
  description: 'Characters must be base58 set',
38
- error: 'ExpectedAllBase58CharactersInBase58Address',
38
+ error: 'ExpectedAllBase58CharactersInBase58CheckString',
39
39
  },
40
40
  {
41
41
  args: {address: '16ro3Jptwo4asSevZnsRX6vfRS24TGE6uK'},
@@ -45,6 +45,30 @@ const tests = [
45
45
  version: 0,
46
46
  },
47
47
  },
48
+ {
49
+ args: {address: ' 16ro3Jptwo4asSevZnsRX6vfRS24TGE6uK\n'},
50
+ description: 'Surrounding whitespace is ignored',
51
+ expected: {
52
+ hash: hexAsBuffer('404371705fa9bd789a2fcd52d2c580b65d35549d'),
53
+ version: 0,
54
+ },
55
+ },
56
+ {
57
+ args: {address: 'mipcBbFg9gMiCh81Kj8tqqdgoZub1ZJRfn'},
58
+ description: 'A hash and version are returned for a testnet p2pkh address',
59
+ expected: {
60
+ hash: hexAsBuffer('243f1394f44554f4ce3fd68649c19adc483ce924'),
61
+ version: 111,
62
+ },
63
+ },
64
+ {
65
+ args: {address: '2N3oefVeg6stiTb5Kh3ozCSkaqmx91FDbsm'},
66
+ description: 'A hash and version are returned for a testnet p2sh address',
67
+ expected: {
68
+ hash: hexAsBuffer('73d32ac9e4330a071ee1b3a9ccf3997bdd4174d0'),
69
+ version: 196,
70
+ },
71
+ },
48
72
  {
49
73
  args: {address: '3P14159f73E4gFr7JterCCQh9QjiTjiZrG'},
50
74
  description: 'A hash and version are returned for a p2sh address',
@@ -100,15 +100,20 @@ const tests = [
100
100
  args: {
101
101
  transaction: '010000000002010000000000000000000000000000000000000000000000000000000000000000ffffffff00ffffffff010100000000000000000101510000' + '0000',
102
102
  },
103
- description: 'A witness serialized tx with an unknown flag is rejected',
104
- error: 'UnexpectedWitnessFlagByteValueInTransaction',
103
+ description: 'A zero marker with unknown flag is legacy and has extra data',
104
+ error: 'UnexpectedDataAfterTransactionToGetComponentsOf',
105
105
  },
106
106
  {
107
107
  args: {
108
108
  transaction: '0100000000' + '02' + '01000000000000000151' + '020000000000000000' + '00000000',
109
109
  },
110
- description: 'A zero marker with a non-witness non-zero flag is rejected',
111
- error: 'UnexpectedWitnessFlagByteValueInTransaction',
110
+ description: 'A zero inputs tx with a non-witness flag byte is parsed as legacy',
111
+ expected: {
112
+ inputs: [],
113
+ locktime: 0,
114
+ outputs: [{script: '51', tokens: 1}, {script: '', tokens: 2}],
115
+ version: 1,
116
+ },
112
117
  },
113
118
  {
114
119
  args: {
@@ -17,7 +17,6 @@ const minByteLengthInput = 41;
17
17
  const minByteLengthOutput = 9;
18
18
  const times = n => [...Array(n).keys()];
19
19
  const witnessFlagValue = 1;
20
- const zeroFlagValue = 0;
21
20
 
22
21
  /** Parse a raw transaction out of a buffer at a specific offset start
23
22
 
@@ -87,14 +86,8 @@ module.exports = args => {
87
86
  // The presence of the marker and flag indicates SegWit tx encoding
88
87
  const isSegWit = !marker && flag === witnessFlagValue;
89
88
 
90
- // A zero marker with a zero flag is the legacy encoding of an empty tx: the
91
- // zero marker is an empty inputs count and the zero flag is an empty outputs
92
- // count. Any other flag value following a zero marker is unknown data.
93
- if (!marker && !isSegWit && flag !== zeroFlagValue) {
94
- throw new Error('UnexpectedWitnessFlagByteValueInTransaction');
95
- }
96
-
97
- // When tx isn't SegWit though, the bytes are not marker and flag
89
+ // When tx isn't SegWit though, the bytes are not marker and flag: a zero
90
+ // marker without the witness flag is a legacy tx with an empty inputs count
98
91
  offset += isSegWit ? byteCountMarkerFlag : byteCountNoMarkerFlag;
99
92
 
100
93
  const inputsCount = decodeCompactInt(args.buffer, offset);