diff --git a/lib/bip32.js b/lib/bip32.js index 4891417..e552269 100644 --- a/lib/bip32.js +++ b/lib/bip32.js @@ -308,6 +308,16 @@ BIP32.prototype.deriveChild = function(i) { return ret; } +BIP32.prototype.toString = function() { + var isPrivate = + (this.version == constants.mainnet.bip32privkey || + this.version == constants.testnet.bip32privkey); + + if (isPrivate) + return this.extendedPrivateKeyString(); + else + return this.extendedPublicKeyString(); +}; function uint(f, size) { if (f.length < size) diff --git a/test/test.bip32.js b/test/test.bip32.js index 6f08d8e..971318f 100644 --- a/test/test.bip32.js +++ b/test/test.bip32.js @@ -1,4 +1,5 @@ var should = require('chai').should(); +var constants = require('../lib/constants'); var BIP32 = require('../lib/bip32'); describe('BIP32', function() { @@ -299,4 +300,31 @@ describe('BIP32', function() { }); }); + describe('#toString', function() { + var bip32 = new BIP32(); + bip32.fromRandom('mainnet'); + var tip32 = new BIP32(); + tip32.fromRandom('testnet'); + + it('should return an xprv string', function() { + bip32.toString().slice(0, 4).should.equal('xprv'); + }); + + it('should return an xpub string', function() { + var bip32b = new BIP32(bip32.extendedPublicKeyString()); + bip32b.toString().slice(0, 4).should.equal('xpub'); + }); + + it('should return a tprv string', function() { + tip32.toString().slice(0, 4).should.equal('tprv'); + }); + + it('should return a tpub string', function() { + var tip32b = new BIP32(tip32.extendedPublicKeyString()); + tip32b.toString().slice(0, 4).should.equal('tpub'); + }); + + + }); + });