Skip to content

Commit

Permalink
remove native code and use bignum package
Browse files Browse the repository at this point in the history
  • Loading branch information
gasteve committed Jul 28, 2013
1 parent b779bb8 commit 9a3ecbc
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 280 deletions.
81 changes: 74 additions & 7 deletions base58.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,69 @@
var lib = require('bindings')('base58');
var crypto = require('crypto');
var bignum = require('bignum');

var globalBuffer = new Buffer(1024);
var zerobuf = new Buffer(0);
var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
var ALPHABET_ZERO = ALPHABET[0];
var ALPHABET_BUF = new Buffer(ALPHABET, 'ascii');
var ALPHABET_INV = {};
for(var i=0; i < ALPHABET.length; i++) {
ALPHABET_INV[ALPHABET[i]] = i;
};

// Vanilla Base58 Encoding
var base58 = {
encode: lib.base58_encode,
decode: lib.base58_decode,
encode: function(buf) {
var str;
var x = bignum.fromBuffer(buf);
var r;

if(buf.length < 512) {
str = globalBuffer;
} else {
str = new Buffer(buf.length << 1);
}
var i = str.length - 1;
while(x.gt(0)) {
r = x.mod(58);
x = x.div(58);
str[i] = ALPHABET_BUF[r.toNumber()];
i--;
}

// deal with leading zeros
var j=0;
while(buf[j] == 0) {
str[i] = ALPHABET_BUF[0];
j++; i--;
}

return str.slice(i+1,str.length).toString('ascii');
},

decode: function(str) {
if(str.length == 0) return zerobuf;
var answer = bignum(0);
for(var i=0; i<str.length; i++) {
answer.mul(58)
answer = answer.mul(58);
answer = answer.add(ALPHABET_INV[str[i]]);
};
var i = 0;
while(i < str.length && str[i] == ALPHABET_ZERO) {
i++;
}
if(i > 0) {
var zb = new Buffer(i);
zb.fill(0);
if(i == str.length) return zb;
answer = answer.toBuffer();
return Buffer.concat([zb, answer], i+answer.length);
} else {
return answer.toBuffer();
}
},
};
exports.base58 = base58;
exports.encode = base58.encode;
exports.decode = base58.decode;

// Base58Check Encoding
function sha256(data) {
Expand All @@ -19,7 +74,7 @@ function doubleSHA256(data) {
return sha256(sha256(data));
};

exports.base58Check = {
var base58Check = {
encode: function(buf) {
var checkedBuf = new Buffer(buf.length + 4);
var hash = doubleSHA256(buf);
Expand Down Expand Up @@ -47,3 +102,15 @@ exports.base58Check = {
return data;
},
};

// if you frequently do base58 encodings with data larger
// than 512 bytes, you can use this method to expand the
// size of the reusable buffer
exports.setBuffer = function(buf) {
globalBuffer = buf;
};

exports.base58 = base58;
exports.base58Check = base58Check;
exports.encode = base58.encode;
exports.decode = base58.decode;
35 changes: 0 additions & 35 deletions binding.gyp

This file was deleted.

221 changes: 0 additions & 221 deletions src/base58.cc

This file was deleted.

17 changes: 0 additions & 17 deletions src/common.h

This file was deleted.

0 comments on commit 9a3ecbc

Please sign in to comment.