Skip to content

Commit 12dbe57

Browse files
committed
Merge pull request bitcoinjs#385 from bitcoinjs/ecpair
ECPair
2 parents c66b888 + e106d02 commit 12dbe57

23 files changed

+753
-670
lines changed

src/ecpair.js

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
var assert = require('assert')
2+
var base58check = require('bs58check')
3+
var bcrypto = require('./crypto')
4+
var ecdsa = require('./ecdsa')
5+
var ecurve = require('ecurve')
6+
var networks = require('./networks')
7+
var randomBytes = require('randombytes')
8+
var typeForce = require('typeforce')
9+
10+
var Address = require('./address')
11+
var BigInteger = require('bigi')
12+
13+
function findNetworkByWIFVersion (version) {
14+
for (var networkName in networks) {
15+
var network = networks[networkName]
16+
17+
if (network.wif === version) return network
18+
}
19+
20+
assert(false, 'Unknown network')
21+
}
22+
23+
function ECPair (d, Q, options) {
24+
options = options || {}
25+
26+
var compressed = options.compressed === undefined ? true : options.compressed
27+
var network = options.network === undefined ? networks.bitcoin : options.network
28+
29+
typeForce('Boolean', compressed)
30+
assert('pubKeyHash' in network, 'Unknown pubKeyHash constants for network')
31+
32+
if (d) {
33+
assert(d.signum() > 0, 'Private key must be greater than 0')
34+
assert(d.compareTo(ECPair.curve.n) < 0, 'Private key must be less than the curve order')
35+
36+
assert(!Q, 'Unexpected publicKey parameter')
37+
this.d = d
38+
39+
// enforce Q is a public key if no private key given
40+
} else {
41+
typeForce('Point', Q)
42+
this.__Q = Q
43+
}
44+
45+
this.compressed = compressed
46+
this.network = network
47+
}
48+
49+
Object.defineProperty(ECPair.prototype, 'Q', {
50+
get: function () {
51+
if (!this.__Q && this.d) {
52+
this.__Q = ECPair.curve.G.multiply(this.d)
53+
}
54+
55+
return this.__Q
56+
}
57+
})
58+
59+
// Public access to secp256k1 curve
60+
ECPair.curve = ecurve.getCurveByName('secp256k1')
61+
62+
ECPair.fromPublicKeyBuffer = function (buffer, network) {
63+
var Q = ecurve.Point.decodeFrom(ECPair.curve, buffer)
64+
65+
return new ECPair(null, Q, {
66+
compressed: Q.compressed,
67+
network: network
68+
})
69+
}
70+
71+
ECPair.fromWIF = function (string) {
72+
var payload = base58check.decode(string)
73+
var version = payload.readUInt8(0)
74+
var compressed
75+
76+
if (payload.length === 34) {
77+
assert.strictEqual(payload[33], 0x01, 'Invalid compression flag')
78+
79+
// truncate the version/compression bytes
80+
payload = payload.slice(1, -1)
81+
compressed = true
82+
83+
// no compression flag
84+
} else {
85+
assert.equal(payload.length, 33, 'Invalid WIF payload length')
86+
87+
// Truncate the version byte
88+
payload = payload.slice(1)
89+
compressed = false
90+
}
91+
92+
var network = findNetworkByWIFVersion(version)
93+
var d = BigInteger.fromBuffer(payload)
94+
95+
return new ECPair(d, null, {
96+
compressed: compressed,
97+
network: network
98+
})
99+
}
100+
101+
ECPair.makeRandom = function (options) {
102+
options = options || {}
103+
104+
var rng = options.rng || randomBytes
105+
var buffer = rng(32)
106+
typeForce('Buffer', buffer)
107+
assert.equal(buffer.length, 32, 'Expected 256-bit Buffer from RNG')
108+
109+
var d = BigInteger.fromBuffer(buffer)
110+
d = d.mod(ECPair.curve.n)
111+
112+
return new ECPair(d, null, options)
113+
}
114+
115+
ECPair.prototype.toWIF = function () {
116+
assert(this.d, 'Missing private key')
117+
118+
var bufferLen = this.compressed ? 34 : 33
119+
var buffer = new Buffer(bufferLen)
120+
121+
buffer.writeUInt8(this.network.wif, 0)
122+
this.d.toBuffer(32).copy(buffer, 1)
123+
124+
if (this.compressed) {
125+
buffer.writeUInt8(0x01, 33)
126+
}
127+
128+
return base58check.encode(buffer)
129+
}
130+
131+
ECPair.prototype.getAddress = function () {
132+
var pubKey = this.getPublicKeyBuffer()
133+
134+
return new Address(bcrypto.hash160(pubKey), this.network.pubKeyHash)
135+
}
136+
137+
ECPair.prototype.getPublicKeyBuffer = function () {
138+
return this.Q.getEncoded(this.compressed)
139+
}
140+
141+
ECPair.prototype.sign = function (hash) {
142+
assert(this.d, 'Missing private key')
143+
144+
return ecdsa.sign(ECPair.curve, hash, this.d)
145+
}
146+
147+
ECPair.prototype.verify = function (hash, signature) {
148+
return ecdsa.verify(ECPair.curve, hash, signature, this.Q)
149+
}
150+
151+
module.exports = ECPair

src/hdnode.js

Lines changed: 47 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@ var typeForce = require('typeforce')
66
var networks = require('./networks')
77

88
var BigInteger = require('bigi')
9-
var ECKey = require('./eckey')
10-
var ECPubKey = require('./ecpubkey')
9+
var ECPair = require('./ecpair')
1110

1211
var ecurve = require('ecurve')
1312
var curve = ecurve.getCurveByName('secp256k1')
@@ -24,32 +23,19 @@ function findBIP32NetworkByVersion (version) {
2423
assert(false, 'Could not find network for ' + version.toString(16))
2524
}
2625

27-
function HDNode (K, chainCode, network) {
28-
network = network || networks.bitcoin
29-
26+
function HDNode (keyPair, chainCode) {
27+
typeForce('ECPair', keyPair)
3028
typeForce('Buffer', chainCode)
3129

3230
assert.equal(chainCode.length, 32, 'Expected chainCode length of 32, got ' + chainCode.length)
33-
assert(network.bip32, 'Unknown BIP32 constants for network')
31+
assert('bip32' in keyPair.network, 'Unknown BIP32 constants for network')
32+
assert.equal(keyPair.compressed, true, 'BIP32 only allows compressed keyPairs')
3433

34+
this.keyPair = keyPair
3535
this.chainCode = chainCode
3636
this.depth = 0
3737
this.index = 0
3838
this.parentFingerprint = 0x00000000
39-
this.network = network
40-
41-
if (K instanceof BigInteger) {
42-
this.privKey = new ECKey(K, true)
43-
this.pubKey = this.privKey.pub
44-
} else if (K instanceof ECKey) {
45-
assert(K.pub.compressed, 'ECKey must be compressed')
46-
this.privKey = K
47-
} else if (K instanceof ECPubKey) {
48-
assert(K.compressed, 'ECPubKey must be compressed')
49-
this.pubKey = K
50-
} else {
51-
this.pubKey = new ECPubKey(K, true)
52-
}
5339
}
5440

5541
HDNode.MASTER_SECRET = new Buffer('Bitcoin seed')
@@ -67,10 +53,13 @@ HDNode.fromSeedBuffer = function (seed, network) {
6753
var IR = I.slice(32)
6854

6955
// In case IL is 0 or >= n, the master key is invalid
70-
// This is handled by `new ECKey` in the HDNode constructor
56+
// This is handled by the ECPair constructor
7157
var pIL = BigInteger.fromBuffer(IL)
58+
var keyPair = new ECPair(pIL, null, {
59+
network: network
60+
})
7261

73-
return new HDNode(pIL, IR, network)
62+
return new HDNode(keyPair, IR)
7463
}
7564

7665
HDNode.fromSeedHex = function (hex, network) {
@@ -108,14 +97,17 @@ HDNode.fromBase58 = function (string, network) {
10897

10998
// 32 bytes: the chain code
11099
var chainCode = buffer.slice(13, 45)
111-
var data, hd
100+
var data, keyPair
112101

113102
// 33 bytes: private key data (0x00 + k)
114103
if (version === network.bip32.private) {
115104
assert.strictEqual(buffer.readUInt8(45), 0x00, 'Invalid private key')
116105
data = buffer.slice(46, 78)
117106
var d = BigInteger.fromBuffer(data)
118-
hd = new HDNode(d, chainCode, network)
107+
108+
keyPair = new ECPair(d, null, {
109+
network: network
110+
})
119111

120112
// 33 bytes: public key data (0x02 + X or 0x03 + X)
121113
} else {
@@ -127,9 +119,12 @@ HDNode.fromBase58 = function (string, network) {
127119
// If not, the extended public key is invalid.
128120
curve.validate(Q)
129121

130-
hd = new HDNode(Q, chainCode, network)
122+
keyPair = new ECPair(null, Q, {
123+
network: network
124+
})
131125
}
132126

127+
var hd = new HDNode(keyPair, chainCode)
133128
hd.depth = depth
134129
hd.index = index
135130
hd.parentFingerprint = parentFingerprint
@@ -138,19 +133,23 @@ HDNode.fromBase58 = function (string, network) {
138133
}
139134

140135
HDNode.prototype.getIdentifier = function () {
141-
return bcrypto.hash160(this.pubKey.toBuffer())
136+
return bcrypto.hash160(this.keyPair.getPublicKeyBuffer())
142137
}
143138

144139
HDNode.prototype.getFingerprint = function () {
145140
return this.getIdentifier().slice(0, 4)
146141
}
147142

148143
HDNode.prototype.getAddress = function () {
149-
return this.pubKey.getAddress(this.network)
144+
return this.keyPair.getAddress()
150145
}
151146

152147
HDNode.prototype.neutered = function () {
153-
var neutered = new HDNode(this.pubKey.Q, this.chainCode, this.network)
148+
var neuteredKeyPair = new ECPair(null, this.keyPair.Q, {
149+
network: this.keyPair.network
150+
})
151+
152+
var neutered = new HDNode(neuteredKeyPair, this.chainCode)
154153
neutered.depth = this.depth
155154
neutered.index = this.index
156155
neutered.parentFingerprint = this.parentFingerprint
@@ -162,7 +161,8 @@ HDNode.prototype.toBase58 = function (__isPrivate) {
162161
assert.strictEqual(__isPrivate, undefined, 'Unsupported argument in 2.0.0')
163162

164163
// Version
165-
var version = this.privKey ? this.network.bip32.private : this.network.bip32.public
164+
var network = this.keyPair.network
165+
var version = this.keyPair.d ? network.bip32.private : network.bip32.public
166166
var buffer = new Buffer(HDNode.LENGTH)
167167

168168
// 4 bytes: version bytes
@@ -182,16 +182,16 @@ HDNode.prototype.toBase58 = function (__isPrivate) {
182182
// 32 bytes: the chain code
183183
this.chainCode.copy(buffer, 13)
184184

185-
// 33 bytes: the private key, or
186-
if (this.privKey) {
185+
// 33 bytes: the public key or private key data
186+
if (this.keyPair.d) {
187187
// 0x00 + k for private keys
188188
buffer.writeUInt8(0, 45)
189-
this.privKey.d.toBuffer(32).copy(buffer, 46)
189+
this.keyPair.d.toBuffer(32).copy(buffer, 46)
190190

191191
// 33 bytes: the public key
192192
} else {
193193
// X9.62 encoding for public keys
194-
this.pubKey.toBuffer().copy(buffer, 45)
194+
this.keyPair.getPublicKeyBuffer().copy(buffer, 45)
195195
}
196196

197197
return base58check.encode(buffer)
@@ -207,11 +207,11 @@ HDNode.prototype.derive = function (index) {
207207

208208
// Hardened child
209209
if (isHardened) {
210-
assert(this.privKey, 'Could not derive hardened child key')
210+
assert(this.keyPair.d, 'Could not derive hardened child key')
211211

212212
// data = 0x00 || ser256(kpar) || ser32(index)
213213
data = Buffer.concat([
214-
this.privKey.d.toBuffer(33),
214+
this.keyPair.d.toBuffer(33),
215215
indexBuffer
216216
])
217217

@@ -220,7 +220,7 @@ HDNode.prototype.derive = function (index) {
220220
// data = serP(point(kpar)) || ser32(index)
221221
// = serP(Kpar) || ser32(index)
222222
data = Buffer.concat([
223-
this.pubKey.toBuffer(),
223+
this.keyPair.getPublicKeyBuffer(),
224224
indexBuffer
225225
])
226226
}
@@ -237,32 +237,37 @@ HDNode.prototype.derive = function (index) {
237237
}
238238

239239
// Private parent key -> private child key
240-
var hd
241-
if (this.privKey) {
240+
var derivedKeyPair
241+
if (this.keyPair.d) {
242242
// ki = parse256(IL) + kpar (mod n)
243-
var ki = pIL.add(this.privKey.d).mod(curve.n)
243+
var ki = pIL.add(this.keyPair.d).mod(curve.n)
244244

245245
// In case ki == 0, proceed with the next value for i
246246
if (ki.signum() === 0) {
247247
return this.derive(index + 1)
248248
}
249249

250-
hd = new HDNode(ki, IR, this.network)
250+
derivedKeyPair = new ECPair(ki, null, {
251+
network: this.keyPair.network
252+
})
251253

252254
// Public parent key -> public child key
253255
} else {
254256
// Ki = point(parse256(IL)) + Kpar
255257
// = G*IL + Kpar
256-
var Ki = curve.G.multiply(pIL).add(this.pubKey.Q)
258+
var Ki = curve.G.multiply(pIL).add(this.keyPair.Q)
257259

258260
// In case Ki is the point at infinity, proceed with the next value for i
259261
if (curve.isInfinity(Ki)) {
260262
return this.derive(index + 1)
261263
}
262264

263-
hd = new HDNode(Ki, IR, this.network)
265+
derivedKeyPair = new ECPair(null, Ki, {
266+
network: this.keyPair.network
267+
})
264268
}
265269

270+
var hd = new HDNode(derivedKeyPair, IR)
266271
hd.depth = this.depth + 1
267272
hd.index = index
268273
hd.parentFingerprint = this.getFingerprint().readUInt32BE(0)

src/index.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ module.exports = {
44
bufferutils: require('./bufferutils'),
55
crypto: require('./crypto'),
66
ecdsa: require('./ecdsa'),
7-
ECKey: require('./eckey'),
8-
ECPubKey: require('./ecpubkey'),
7+
ECPair: require('./ecpair'),
98
ECSignature: require('./ecsignature'),
109
message: require('./message'),
1110
opcodes: require('./opcodes'),

0 commit comments

Comments
 (0)