bitcoinjs-lib/src/eckey.js

78 lines
1.8 KiB
JavaScript
Raw Normal View History

var assert = require('assert')
var base58check = require('./base58check')
var ecdsa = require('./ecdsa')
var networks = require('./networks')
2014-04-17 19:08:16 +10:00
var secureRandom = require('secure-random')
2014-05-13 16:44:29 +10:00
var BigInteger = require('bigi')
var ECPubKey = require('./ecpubkey')
2014-04-22 02:19:30 +10:00
var sec = require('./sec')
2014-04-18 06:17:41 +10:00
var ecparams = sec('secp256k1')
2014-04-17 19:08:16 +10:00
function ECKey(D, compressed) {
2014-05-31 11:24:00 +10:00
assert(D.signum() > 0, 'Private key must be greater than 0')
2014-04-18 06:17:41 +10:00
assert(D.compareTo(ecparams.getN()) < 0, 'Private key must be less than the curve order')
2014-04-17 19:08:16 +10:00
var Q = ecparams.getG().multiply(D)
2014-04-17 19:08:16 +10:00
this.D = D
this.pub = new ECPubKey(Q, compressed)
}
2014-04-17 19:08:16 +10:00
// Static constructors
ECKey.fromWIF = function(string) {
var payload = base58check.decode(string)
var compressed = false
// Ignore the version byte
payload = payload.slice(1)
2014-04-17 19:08:16 +10:00
if (payload.length === 33) {
assert.strictEqual(payload[32], 0x01, 'Invalid compression flag')
// Truncate the compression flag
payload = payload.slice(0, -1)
compressed = true
2014-04-17 19:08:16 +10:00
}
assert.equal(payload.length, 32, 'Invalid WIF payload length')
2014-05-17 17:06:02 +10:00
var D = BigInteger.fromBuffer(payload)
return new ECKey(D, compressed)
}
2014-04-17 19:08:16 +10:00
ECKey.makeRandom = function(compressed, rng) {
rng = rng || secureRandom
2014-04-17 19:08:16 +10:00
var buffer = new Buffer(rng(32))
2014-04-22 02:19:30 +10:00
var D = BigInteger.fromBuffer(buffer)
2014-04-17 19:08:16 +10:00
D = D.mod(ecparams.getN())
2014-04-17 19:08:16 +10:00
return new ECKey(D, compressed)
2013-11-18 23:47:56 -05:00
}
2014-04-17 19:08:16 +10:00
// Export functions
ECKey.prototype.toWIF = function(version) {
version = version || networks.bitcoin.wif
2014-03-25 02:44:43 +11:00
var bufferLen = this.pub.compressed ? 34 : 33
var buffer = new Buffer(bufferLen)
buffer.writeUInt8(version, 0)
this.D.toBuffer(32).copy(buffer, 1)
2014-04-17 19:08:16 +10:00
if (this.pub.compressed) {
buffer.writeUInt8(0x01, 33)
}
return base58check.encode(buffer)
2014-01-08 17:13:26 -05:00
}
// Operations
ECKey.prototype.sign = function(hash) {
2014-05-17 15:06:52 +10:00
return ecdsa.sign(ecparams, hash, this.D)
}
2014-05-13 16:44:29 +10:00
module.exports = ECKey