@alexbosworth/blockchain 4.6.0 → 4.7.1

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,203 @@
1
+ const {createHash} = require('crypto');
2
+
3
+ const {numberAsCompactInt} = require('./../numbers');
4
+ const {numberAsLittleEndian} = require('./../numbers');
5
+ const {parsePushBytesCount} = require('./../numbers');
6
+ const parseTransaction = require('./parse_transaction');
7
+
8
+ const anyOnePaysFlag = 0x80;
9
+ const blankedOutput = Buffer.from('ffffffffffffffff00', 'hex');
10
+ const bufferAsHex = buffer => buffer.toString('hex');
11
+ const {concat} = Buffer;
12
+ const countOf = number => numberAsCompactInt({number}).encoded;
13
+ const defaultHashType = 0x01;
14
+ const hashTypes = [0x01, 0x02, 0x03, 0x81, 0x82, 0x83];
15
+ const hexAsBuffer = hex => Buffer.from(hex, 'hex');
16
+ const isHex = n => !!n && !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
17
+ const {isInteger} = Number;
18
+ const isString = n => typeof n === 'string';
19
+ const opCodeSeparator = 0xab;
20
+ const opPushData4 = 78;
21
+ const opZero = 0;
22
+ const outputTypeMask = 0x1f;
23
+ const sha256 = preimage => createHash('sha256').update(preimage).digest();
24
+ const sigHashNone = 2;
25
+ const sigHashSingle = 3;
26
+ const singleByte = 1;
27
+ const sizeOf = script => numberAsCompactInt({number: script.length}).encoded;
28
+ const start = 0;
29
+ const uint32 = n => numberAsLittleEndian({bytes: 4, number: n}).encoded;
30
+ const uint64 = n => numberAsLittleEndian({bytes: 8, number: n}).encoded;
31
+ const zeroSequence = 0;
32
+
33
+ /** Calculate the pre-SegWit transaction hash to sign
34
+
35
+ For P2PK, P2PKH, or bare multisig the script is the output script being spent
36
+
37
+ For P2SH the script is the redeem script that hashes to the output script
38
+
39
+ When a code separator was executed, pass only the script following it, any
40
+ remaining code separators are removed from the script before hashing
41
+
42
+ Signing for a single output requires an output matching the input index
43
+
44
+ {
45
+ script: <Signing Input Script Hex String>
46
+ [sighash]: <Signature Hash Type Number>
47
+ transaction: <Raw Transaction Hex String>
48
+ vin: <Signing Transaction Input Index Number>
49
+ }
50
+
51
+ @throws
52
+ <Error>
53
+
54
+ @returns
55
+ {
56
+ hash: <Hash to Sign Hex String>
57
+ }
58
+ */
59
+ module.exports = ({script, sighash, transaction, vin}) => {
60
+ if (!isString(script) || !isHex(script)) {
61
+ throw new Error('ExpectedScriptCodeHexToCalculateNonWitnessHashToSign');
62
+ }
63
+
64
+ if (!!sighash && !hashTypes.includes(sighash)) {
65
+ throw new Error('ExpectedValidSigHashTypeForNonWitnessHashToSign');
66
+ }
67
+
68
+ if (!isString(transaction) || !isHex(transaction)) {
69
+ throw new Error('ExpectedTransactionHexToCalculateNonWitnessHashToSign');
70
+ }
71
+
72
+ if (!isInteger(vin)) {
73
+ throw new Error('ExpectedInputIndexToCalculateNonWitnessHashToSign');
74
+ }
75
+
76
+ const data = hexAsBuffer(script);
77
+ const decoded = parseTransaction({buffer: hexAsBuffer(transaction)});
78
+ const hashType = sighash || defaultHashType;
79
+ const parts = [];
80
+
81
+ // The signing input is expected to be present in the transaction
82
+ if (!decoded.inputs[vin]) {
83
+ throw new Error('ExpectedMatchingInputToCalculateNonWitnessHashToSign');
84
+ }
85
+
86
+ const isAnyOnePays = !!(hashType & anyOnePaysFlag);
87
+ const outputType = hashType & outputTypeMask;
88
+
89
+ // Signing for a single output requires an output at the input index
90
+ if (outputType === sigHashSingle && !decoded.outputs[vin]) {
91
+ throw new Error('ExpectedMatchingOutputForSingleNonWitnessHashToSign');
92
+ }
93
+
94
+ // Signing for all outputs is any type that isn't for none or a single one
95
+ const isAllOutputs = ![sigHashNone, sigHashSingle].includes(outputType);
96
+
97
+ let offset = start;
98
+
99
+ // The script code is committed to with its code separators removed
100
+ while (offset < data.length) {
101
+ const code = data.readUInt8(offset);
102
+
103
+ // Code separators are dropped from the committed script code
104
+ if (code === opCodeSeparator) {
105
+ offset += singleByte;
106
+
107
+ continue;
108
+ }
109
+
110
+ // Exit early when the code is a simple op code and not a data push
111
+ if (code === opZero || code > opPushData4) {
112
+ parts.push(data.subarray(offset, offset + singleByte));
113
+
114
+ offset += singleByte;
115
+
116
+ continue;
117
+ }
118
+
119
+ const push = parsePushBytesCount({offset, script: data});
120
+
121
+ // The pushed data bytes are expected to be present in the script
122
+ if (!push.bytes || offset + push.bytes.length + push.count > data.length) {
123
+ throw new Error('ExpectedValidScriptCodeForNonWitnessHashToSign');
124
+ }
125
+
126
+ parts.push(data.subarray(offset, offset + push.bytes.length + push.count));
127
+
128
+ offset += push.bytes.length + push.count;
129
+ }
130
+
131
+ const scriptCode = concat(parts);
132
+
133
+ // Only the signing input is committed to when anyone can pay
134
+ const committed = decoded.inputs
135
+ .map(({hash, sequence, vout}, index) => ({hash, index, sequence, vout}))
136
+ .filter(({index}) => !isAnyOnePays || index === vin);
137
+
138
+ // The transaction version number is a signed integer
139
+ const version = numberAsLittleEndian({
140
+ bytes: 4,
141
+ is_signed: true,
142
+ number: decoded.version,
143
+ });
144
+
145
+ // Elements to hash over start with the signed transaction version number
146
+ const elements = [version.encoded];
147
+
148
+ // Write how many inputs there are
149
+ elements.push(countOf(committed.length));
150
+
151
+ // Write the inputs
152
+ committed.forEach(({hash, index, sequence, vout}) => {
153
+ // Write the outpoint being spent
154
+ elements.push(hash);
155
+ elements.push(uint32(vout));
156
+
157
+ // The signing input commits to the script code, others are blanked
158
+ if (index === vin) {
159
+ elements.push(sizeOf(scriptCode));
160
+ elements.push(scriptCode);
161
+ } else {
162
+ elements.push(sizeOf(hexAsBuffer(String())));
163
+ }
164
+
165
+ // Other input sequence numbers are zeroed unless signing for all outputs
166
+ if (index === vin || isAllOutputs) {
167
+ elements.push(uint32(sequence));
168
+ } else {
169
+ elements.push(uint32(zeroSequence));
170
+ }
171
+ });
172
+
173
+ // Signing for a single output only commits up to the matching output
174
+ const outputs = decoded.outputs.slice(
175
+ start,
176
+ outputType === sigHashSingle ? vin + [vin].length : decoded.outputs.length
177
+ );
178
+
179
+ // Write how many outputs there are, none commits to no outputs at all
180
+ elements.push(countOf(outputType === sigHashNone ? start : outputs.length));
181
+
182
+ // Write the outputs, blanking outputs before the single matching output
183
+ if (outputType !== sigHashNone) {
184
+ outputs.forEach(({script, tokens}, index) => {
185
+ // Outputs before the single matching output have negative one values
186
+ if (outputType === sigHashSingle && index < vin) {
187
+ return elements.push(blankedOutput);
188
+ }
189
+
190
+ elements.push(uint64(tokens));
191
+ elements.push(sizeOf(script));
192
+
193
+ return elements.push(script);
194
+ });
195
+ }
196
+
197
+ // Commit to the transaction locktime and the signature hash type
198
+ elements.push(uint32(decoded.locktime));
199
+ elements.push(uint32(hashType));
200
+
201
+ // The hash to sign is the double sha256 hash of the elements
202
+ return {hash: bufferAsHex(sha256(sha256(concat(elements))))};
203
+ };
@@ -12,10 +12,12 @@ const defaultLocktime = 0;
12
12
  const defaultStartIndex = 0;
13
13
  const defaultWitnessCount = 0;
14
14
  const {isBuffer} = Buffer;
15
+ const maxTokens = BigInt(Number.MAX_SAFE_INTEGER);
15
16
  const minByteLengthInput = 41;
16
17
  const minByteLengthOutput = 9;
17
18
  const times = n => [...Array(n).keys()];
18
19
  const witnessFlagValue = 1;
20
+ const zeroFlagValue = 0;
19
21
 
20
22
  /** Parse a raw transaction out of a buffer at a specific offset start
21
23
 
@@ -85,8 +87,10 @@ module.exports = args => {
85
87
  // The presence of the marker and flag indicates SegWit tx encoding
86
88
  const isSegWit = !marker && flag === witnessFlagValue;
87
89
 
88
- // A zero marker byte requires the BIP 144 witness flag value to follow
89
- if (!marker && !isSegWit) {
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) {
90
94
  throw new Error('UnexpectedWitnessFlagByteValueInTransaction');
91
95
  }
92
96
 
@@ -160,6 +164,11 @@ module.exports = args => {
160
164
 
161
165
  offset += byteCountInt64;
162
166
 
167
+ // Values beyond the safe integer range cannot be represented as a Number
168
+ if (value > maxTokens) {
169
+ throw new Error('UnexpectedOutputValueInTransaction');
170
+ }
171
+
163
172
  // The script being spent to has a variable length
164
173
  const scriptLength = decodeCompactInt(args.buffer, offset);
165
174
 
@@ -4,28 +4,23 @@ const {numberAsCompactInt} = require('./../numbers');
4
4
  const {numberAsLittleEndian} = require('./../numbers');
5
5
  const parseTransaction = require('./parse_transaction');
6
6
 
7
- const {alloc} = Buffer;
8
7
  const anyOnePaysFlag = 0x80;
9
8
  const bufferAsHex = buffer => buffer.toString('hex');
10
- const byteCountHash = 32;
11
9
  const {concat} = Buffer;
12
10
  const defaultHashType = 0x01;
13
- const hash256 = preimage => sha256(sha256(preimage));
14
11
  const hashTypes = [0x01, 0x02, 0x03, 0x81, 0x82, 0x83];
15
12
  const hexAsBuffer = hex => Buffer.from(hex, 'hex');
16
- const int32 = number => littleEndian({number, bytes: 4, is_signed: true});
17
13
  const isHex = n => !!n && !(n.length % 2) && /^[0-9A-F]*$/i.test(n);
18
14
  const {isInteger} = Number;
19
15
  const isString = n => typeof n === 'string';
20
- const littleEndian = args => numberAsLittleEndian(args).encoded;
21
16
  const outputTypeMask = 0x1f;
22
17
  const sha256 = preimage => createHash('sha256').update(preimage).digest();
23
18
  const sigHashNone = 2;
24
19
  const sigHashSingle = 3;
25
20
  const sizeOf = script => numberAsCompactInt({number: script.length}).encoded;
26
- const uint32 = number => littleEndian({number, bytes: 4});
27
- const uint64 = number => littleEndian({number, bytes: 8});
28
- const zeroHash = alloc(byteCountHash);
21
+ const uint32 = n => numberAsLittleEndian({bytes: 4, number: n}).encoded;
22
+ const uint64 = n => numberAsLittleEndian({bytes: 8, number: n}).encoded;
23
+ const zeroHash = Buffer.alloc(32);
29
24
 
30
25
  /** Calculate the v0 witness transaction hash to sign
31
26
 
@@ -36,7 +31,7 @@ const zeroHash = alloc(byteCountHash);
36
31
  For P2WSH the script code is the witness script
37
32
 
38
33
  {
39
- script: <Signing Input Script Code Hex String>
34
+ script: <Signing Input Script Hex String>
40
35
  [sighash]: <Signature Hash Type Number>
41
36
  tokens: <Spending Output Tokens Number>
42
37
  transaction: <Raw Transaction Hex String>
@@ -95,19 +90,30 @@ module.exports = ({script, sighash, tokens, transaction, vin}) => {
95
90
 
96
91
  const spend = spending[vin];
97
92
 
93
+ // The transaction version number is a signed integer
94
+ const version = numberAsLittleEndian({
95
+ bytes: 4,
96
+ is_signed: true,
97
+ number: decoded.version,
98
+ });
99
+
98
100
  // Elements to hash over start with the signed transaction version number
99
- const elements = [int32(decoded.version)];
101
+ const elements = [version.encoded];
100
102
 
101
103
  // Commit to all of the outpoints being spent unless anyone can pay
102
104
  if (!isAnyOnePays) {
103
- elements.push(hash256(concat(spending.map(({outpoint}) => outpoint))));
105
+ const outpoints = spending.map(({outpoint}) => outpoint);
106
+
107
+ elements.push(sha256(sha256(concat(outpoints))));
104
108
  } else {
105
109
  elements.push(zeroHash);
106
110
  }
107
111
 
108
112
  // Commit to all input sequence numbers when signing for all outputs
109
113
  if (!isAnyOnePays && isAllOutputs) {
110
- elements.push(hash256(concat(spending.map(({sequence}) => sequence))));
114
+ const sequences = spending.map(({sequence}) => sequence);
115
+
116
+ elements.push(sha256(sha256(concat(sequences))));
111
117
  } else {
112
118
  elements.push(zeroHash);
113
119
  }
@@ -127,14 +133,14 @@ module.exports = ({script, sighash, tokens, transaction, vin}) => {
127
133
  return concat([uint64(tokens), sizeOf(script), script]);
128
134
  });
129
135
 
130
- elements.push(hash256(concat(outputs)));
136
+ elements.push(sha256(sha256(concat(outputs))));
131
137
  } else if (outputType === sigHashSingle && !!output) {
132
138
  // Commit to the matching output when signing for a single output
133
- elements.push(hash256(concat([
139
+ elements.push(sha256(sha256(concat([
134
140
  uint64(output.tokens),
135
141
  sizeOf(output.script),
136
142
  output.script,
137
- ])));
143
+ ]))));
138
144
  } else {
139
145
  // There are no outputs committed to when signing for none
140
146
  elements.push(zeroHash);
@@ -145,5 +151,5 @@ module.exports = ({script, sighash, tokens, transaction, vin}) => {
145
151
  elements.push(uint32(hashType));
146
152
 
147
153
  // The hash to sign is the double sha256 hash of the elements
148
- return {hash: bufferAsHex(hash256(concat(elements)))};
154
+ return {hash: bufferAsHex(sha256(sha256(concat(elements))))};
149
155
  };