This repository was archived by the owner on Feb 19, 2026. It is now read-only.
forked from bitcoinjs/bitcoinjs-message
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
233 lines (211 loc) · 6.37 KB
/
index.js
File metadata and controls
233 lines (211 loc) · 6.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
const bs58check = require('bs58check');
const bech32 = require('bech32');
const varuint = require('varuint-bitcoin');
const _ripemd160 = require('@noble/hashes/ripemd160').ripemd160;
const _sha256 = require('@noble/hashes/sha256').sha256;
const SEGWIT_TYPES = {
P2WPKH: 'p2wpkh',
P2SH_P2WPKH: 'p2sh(p2wpkh)',
};
function sha256(buffer) {
return Buffer.from(_sha256(Uint8Array.from(buffer)));
}
function hash160(buffer) {
return Buffer.from(_ripemd160(_sha256(Uint8Array.from(buffer))));
}
function hash256(buffer) {
return sha256(sha256(buffer));
}
function encodeSignature(signature, recovery, compressed, segwitType) {
if (segwitType !== undefined) {
recovery += 8;
if (segwitType === SEGWIT_TYPES.P2WPKH) recovery += 4;
} else {
if (compressed) recovery += 4;
}
return Buffer.concat([Buffer.alloc(1, recovery + 27), signature]);
}
function decodeSignature(buffer) {
if (buffer.length !== 65) throw new Error('Invalid signature length');
const flagByte = buffer.readUInt8(0) - 27;
if (flagByte > 15 || flagByte < 0) {
throw new Error('Invalid signature parameter');
}
return {
compressed: !!(flagByte & 12),
segwitType: !(flagByte & 8)
? null
: !(flagByte & 4)
? SEGWIT_TYPES.P2SH_P2WPKH
: SEGWIT_TYPES.P2WPKH,
recovery: flagByte & 3,
signature: buffer.slice(1),
};
}
function isSigner(obj) {
return obj && typeof obj.signRecoverable === 'function';
}
function segwitRedeemHash(publicKeyHash) {
const redeemScript = Buffer.concat([
Buffer.from('0014', 'hex'),
publicKeyHash,
]);
return hash160(redeemScript);
}
function decodeBech32(address) {
const result = bech32.decode(address);
const data = bech32.fromWords(result.words.slice(1));
return Buffer.from(data);
}
function MessageFactory(secp256k1) {
function magicHash(message, messagePrefix) {
messagePrefix = messagePrefix || '\u0018Bitcoin Signed Message:\n';
if (!Buffer.isBuffer(messagePrefix)) {
messagePrefix = Buffer.from(messagePrefix, 'utf8');
}
if (!Buffer.isBuffer(message)) {
message = Buffer.from(message, 'utf8');
}
const messageVISize = varuint.encodingLength(message.length);
const buffer = Buffer.allocUnsafe(
messagePrefix.length + messageVISize + message.length,
);
messagePrefix.copy(buffer, 0);
varuint.encode(message.length, buffer, messagePrefix.length);
message.copy(buffer, messagePrefix.length + messageVISize);
return hash256(buffer);
}
function prepareSign(messagePrefixArg, sigOptions) {
if (typeof messagePrefixArg === 'object' && sigOptions === undefined) {
sigOptions = messagePrefixArg;
messagePrefixArg = undefined;
}
let { segwitType, extraEntropy } = sigOptions || {};
if (
segwitType &&
(typeof segwitType === 'string' || segwitType instanceof String)
) {
segwitType = segwitType.toLowerCase();
}
if (
segwitType &&
segwitType !== SEGWIT_TYPES.P2SH_P2WPKH &&
segwitType !== SEGWIT_TYPES.P2WPKH
) {
throw new Error(
'Unrecognized segwitType: use "' +
SEGWIT_TYPES.P2SH_P2WPKH +
'" or "' +
SEGWIT_TYPES.P2WPKH +
'"',
);
}
return {
messagePrefixArg,
segwitType,
extraEntropy,
};
}
function sign(message, privateKey, compressed, messagePrefix, sigOptions) {
const { messagePrefixArg, segwitType, extraEntropy } = prepareSign(
messagePrefix,
sigOptions,
);
const hash = magicHash(message, messagePrefixArg);
const sigObj = isSigner(privateKey)
? privateKey.signRecoverable(hash, extraEntropy)
: secp256k1.signRecoverable(hash, privateKey, extraEntropy);
return encodeSignature(
sigObj.signature,
sigObj.recoveryId,
compressed,
segwitType,
);
}
function signAsync(
message,
privateKey,
compressed,
messagePrefix,
sigOptions,
) {
let messagePrefixArg, segwitType, extraEntropy;
return Promise.resolve()
.then(() => {
({ messagePrefixArg, segwitType, extraEntropy } = prepareSign(
messagePrefix,
sigOptions,
));
const hash = magicHash(message, messagePrefixArg);
return isSigner(privateKey)
? privateKey.signRecoverable(hash, extraEntropy)
: secp256k1.signRecoverable(hash, privateKey, extraEntropy);
})
.then(sigObj => {
return encodeSignature(
sigObj.signature,
sigObj.recoveryId,
compressed,
segwitType,
);
});
}
function verify(
message,
address,
signature,
messagePrefix,
checkSegwitAlways,
) {
if (!Buffer.isBuffer(signature))
signature = Buffer.from(signature, 'base64');
const parsed = decodeSignature(signature);
if (checkSegwitAlways && !parsed.compressed) {
throw new Error(
'checkSegwitAlways can only be used with a compressed pubkey signature flagbyte',
);
}
const hash = magicHash(message, messagePrefix);
const publicKey = secp256k1.recover(
hash,
parsed.signature,
parsed.recovery,
parsed.compressed,
);
const publicKeyHash = hash160(publicKey);
let actual, expected;
if (parsed.segwitType) {
if (parsed.segwitType === SEGWIT_TYPES.P2SH_P2WPKH) {
actual = segwitRedeemHash(publicKeyHash);
expected = bs58check.decode(address).slice(1);
} else {
// parsed.segwitType === SEGWIT_TYPES.P2WPKH
// must be true since we only return null, P2SH_P2WPKH, or P2WPKH
// from the decodeSignature function.
actual = publicKeyHash;
expected = decodeBech32(address);
}
} else {
if (checkSegwitAlways) {
try {
expected = decodeBech32(address);
// if address is bech32 it is not p2sh
return publicKeyHash.equals(expected);
} catch (e) {
const redeemHash = segwitRedeemHash(publicKeyHash);
expected = bs58check.decode(address).slice(1);
// base58 can be p2pkh or p2sh-p2wpkh
return publicKeyHash.equals(expected) || redeemHash.equals(expected);
}
} else {
actual = publicKeyHash;
expected = bs58check.decode(address).slice(1);
}
}
return actual.equals(expected);
}
return { magicHash, sign, signAsync, verify };
}
module.exports = {
MessageFactory: MessageFactory,
};