Merge pull request #6 from thofmann/master

Add some standard methods to Message
This commit is contained in:
Manuel Aráoz 2015-02-09 16:26:41 -03:00
commit 7969e1a7c7
2 changed files with 101 additions and 1 deletions

View File

@ -8,6 +8,7 @@ var BufferWriter = bitcore.encoding.BufferWriter;
var ECDSA = bitcore.crypto.ECDSA;
var Signature = bitcore.crypto.Signature;
var sha256sha256 = bitcore.crypto.Hash.sha256sha256;
var JSUtil = bitcore.util.js;
/**
* Will construct a new message to sign and verify.
@ -107,5 +108,61 @@ Message.prototype.verify = function verify(bitcoinAddress, signatureString) {
return this._verify(publicKey, signature);
};
module.exports = Message;
/**
* Instantiate a message from a message string
*
* @param {String} str - A string of the message
* @returns {Message} A new instance of a Message
*/
Message.fromString = function(str) {
return new Message(str);
};
/**
* Instantiate a message from JSON
*
* @param {String} json - An JSON string or Object with keys: message
* @returns {Message} A new instance of a Message
*/
Message.fromJSON = function fromJSON(json) {
if (JSUtil.isValidJSON(json)) {
json = JSON.parse(json);
}
return new Message(json.message);
};
/**
* @returns {Object} A plain object with the message information
*/
Message.prototype.toObject = function toObject() {
return {
message: this.message
};
};
/**
* @returns {String} A JSON representation of the message information
*/
Message.prototype.toJSON = function toJSON() {
return JSON.stringify(this.toObject());
};
/**
* Will return a the string representation of the message
*
* @returns {String} Message
*/
Message.prototype.toString = function() {
return this.message;
};
/**
* Will return a string formatted for the console
*
* @returns {String} Message
*/
Message.prototype.inspect = function() {
return '<Message: ' + this.toString() + '>';
};
module.exports = Message;

View File

@ -104,4 +104,47 @@ describe('Message', function() {
verified.should.equal(true);
});
describe('#json', function() {
it('roundtrip to-from-to', function() {
var json = new Message(text).toJSON();
var message = Message.fromJSON(json);
message.toString().should.equal(text);
});
it('checks that the string parameter is valid JSON', function() {
expect(function() {
return Message.fromJSON('¹');
}).to.throw();
});
});
describe('#toString', function() {
it('message string', function() {
var message = new Message(text);
message.toString().should.equal(text);
});
it('roundtrip to-from-to', function() {
var str = new Message(text).toString();
var message = Message.fromString(str);
message.toString().should.equal(text);
});
});
describe('#inspect', function() {
it('should output formatted output correctly', function() {
var message = new Message(text);
var output = '<Message: '+text+'>';
message.inspect().should.equal(output);
});
});
});