Added isHexString and sha256 to utils.
This commit is contained in:
parent
4dbce955ee
commit
d0a822f02a
27
lib/utils.js
27
lib/utils.js
|
@ -1,5 +1,6 @@
|
|||
|
||||
var BN = require('../node_modules/elliptic/node_modules/bn.js/lib/bn.js');
|
||||
var hash = require('../node_modules/elliptic/node_modules/hash.js/lib/hash.js');
|
||||
|
||||
|
||||
// See: https://github.com/emn178/js-sha3
|
||||
|
@ -180,8 +181,18 @@ function keccak(message) {
|
|||
};
|
||||
|
||||
// Quick sanity check
|
||||
if (keccak(new Buffer('ricmoo')) !== 'b05e424817fb90aa7a79e9da5c5f94070a316219c6ebb863a9ff7ca357dc9fa9') {
|
||||
throw new Error('problem with sh3?!');
|
||||
//if (keccak(new Buffer('ricmoo')) !== 'b05e424817fb90aa7a79e9da5c5f94070a316219c6ebb863a9ff7ca357dc9fa9') {
|
||||
// throw new Error('problem with sh3?!');
|
||||
//}
|
||||
|
||||
function sha256(data) {
|
||||
if (typeof(data) === 'string') {
|
||||
data = new Buffer(data, 'utf8');
|
||||
} else if (!Buffer.isBuffer(data)) {
|
||||
throw new Error('must be a sting');
|
||||
}
|
||||
|
||||
return (new Buffer(hash.sha256().update(data).digest('hex'), 'hex'));
|
||||
}
|
||||
|
||||
function sha3(data) {
|
||||
|
@ -215,9 +226,17 @@ function bnToBuffer(bn) {
|
|||
return stripZeros(new Buffer(hex, 'hex'));
|
||||
}
|
||||
|
||||
function isHexString(value, length) {
|
||||
if (typeof(value) !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) {
|
||||
return false
|
||||
}
|
||||
if (length && value.length !== 2 + 2 * length) { return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
function hexOrBuffer(value, name) {
|
||||
if (!Buffer.isBuffer(value)) {
|
||||
if (typeof(value) !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) {
|
||||
if (!isHexString(value)) {
|
||||
var error = new Error(name ? ('invalid ' + name) : 'invalid hex or buffer');
|
||||
error.reason = 'invalid hex string';
|
||||
error.value = value;
|
||||
|
@ -250,9 +269,11 @@ module.exports = {
|
|||
defineProperty: defineProperty,
|
||||
|
||||
bnToBuffer: bnToBuffer,
|
||||
isHexString: isHexString,
|
||||
hexOrBuffer: hexOrBuffer,
|
||||
hexlify: hexlify,
|
||||
stripZeros: stripZeros,
|
||||
|
||||
sha256: sha256,
|
||||
sha3: sha3,
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue