chore: bump babel to v7

pull/481/head
Yannick Huard 3 years ago
parent f2ed39850f
commit 874c9cccaa
  1. 55
      .babelrc
  2. 7
      dist/es/calculate-contract-address.js
  3. 49
      dist/es/cipher.js
  4. 39
      dist/es/create-identity.js
  5. 27
      dist/es/decrypt-with-private-key.js
  6. 28
      dist/es/encrypt-with-public-key.js
  7. 28
      dist/es/hash.js
  8. 70
      dist/es/hex.js
  9. 35
      dist/es/index.js
  10. 8
      dist/es/public-key-by-private-key.js
  11. 41
      dist/es/public-key.js
  12. 19
      dist/es/recover-public-key.js
  13. 8
      dist/es/recover.js
  14. 26
      dist/es/sign-transaction.js
  15. 17
      dist/es/sign.js
  16. 24
      dist/es/tx-data-by-compiled.js
  17. 11
      dist/es/util.js
  18. 20
      dist/es/vrs.js
  19. 2
      dist/lib/browserify.index.js
  20. 16
      dist/lib/calculate-contract-address.js
  21. 53
      dist/lib/cipher.js
  22. 61
      dist/lib/create-identity.js
  23. 40
      dist/lib/decrypt-with-private-key.js
  24. 37
      dist/lib/encrypt-with-public-key.js
  25. 37
      dist/lib/hash.js
  26. 84
      dist/lib/hex.js
  27. 193
      dist/lib/index.js
  28. 16
      dist/lib/public-key-by-private-key.js
  29. 48
      dist/lib/public-key.js
  30. 27
      dist/lib/recover-public-key.js
  31. 20
      dist/lib/recover.js
  32. 42
      dist/lib/sign-transaction.js
  33. 25
      dist/lib/sign.js
  34. 30
      dist/lib/tx-data-by-compiled.js
  35. 13
      dist/lib/util.js
  36. 25
      dist/lib/vrs.js
  37. 26
      package.json

@ -1,46 +1,15 @@
{
"plugins": [
["transform-es2015-template-literals", {
"loose": true
}],
"transform-es2015-literals",
"transform-es2015-function-name",
"transform-es2015-arrow-functions",
"transform-es2015-block-scoped-functions", ["transform-es2015-classes", {
"loose": true
}],
"transform-es2015-object-super",
"transform-es2015-shorthand-properties", ["transform-es2015-computed-properties", {
"loose": true
}],
["transform-es2015-for-of", {
"loose": true
}],
"transform-es2015-sticky-regex",
"transform-es2015-unicode-regex",
"check-es2015-constants", ["transform-es2015-spread", {
"loose": true
}],
"transform-es2015-parameters", ["transform-es2015-destructuring", {
"loose": true
}],
"transform-es2015-block-scoping",
"transform-object-rest-spread",
"transform-es3-member-expression-literals",
"transform-es3-property-literals",
"transform-async-to-generator",
"transform-regenerator",
["transform-runtime", {
"polyfill": true,
"regenerator": true
}]
],
"env": {
"es5": {
"presets": ["es2015"]
},
"es6": {
"presets": ["es2017"]
}
"presets": ["@babel/preset-env"],
"env": {
"es6": {
"presets": [
[
"@babel/preset-env",
{
"modules": false
}
]
]
}
}
}

@ -1,8 +1,7 @@
import { generateAddress, toChecksumAddress, toBuffer } from 'ethereumjs-util';
import { addLeading0x } from './util';
export default function calculateContractAddress(creatorAddress, nonce) {
var addressBuffer = generateAddress(toBuffer(addLeading0x(creatorAddress)), toBuffer(nonce));
var address = addressBuffer.toString('hex');
return toChecksumAddress(addLeading0x(address));
var addressBuffer = generateAddress(toBuffer(addLeading0x(creatorAddress)), toBuffer(nonce));
var address = addressBuffer.toString('hex');
return toChecksumAddress(addLeading0x(address));
}

49
dist/es/cipher.js vendored

@ -1,34 +1,25 @@
import { compress, decompress } from './public-key';
export function stringify(cipher) {
if (typeof cipher === 'string') return cipher;
// use compressed key because it's smaller
var compressedKey = compress(cipher.ephemPublicKey);
var ret = Buffer.concat([Buffer.from(cipher.iv, 'hex'), // 16bit
Buffer.from(compressedKey, 'hex'), // 33bit
Buffer.from(cipher.mac, 'hex'), // 32bit
Buffer.from(cipher.ciphertext, 'hex') // var bit
]);
return ret.toString('hex');
if (typeof cipher === 'string') return cipher; // use compressed key because it's smaller
var compressedKey = compress(cipher.ephemPublicKey);
var ret = Buffer.concat([Buffer.from(cipher.iv, 'hex'), // 16bit
Buffer.from(compressedKey, 'hex'), // 33bit
Buffer.from(cipher.mac, 'hex'), // 32bit
Buffer.from(cipher.ciphertext, 'hex') // var bit
]);
return ret.toString('hex');
}
export function parse(str) {
if (typeof str !== 'string') return str;
var buf = Buffer.from(str, 'hex');
var ret = {
iv: buf.toString('hex', 0, 16),
ephemPublicKey: buf.toString('hex', 16, 49),
mac: buf.toString('hex', 49, 81),
ciphertext: buf.toString('hex', 81, buf.length)
};
// decompress publicKey
ret.ephemPublicKey = '04' + decompress(ret.ephemPublicKey);
return ret;
if (typeof str !== 'string') return str;
var buf = Buffer.from(str, 'hex');
var ret = {
iv: buf.toString('hex', 0, 16),
ephemPublicKey: buf.toString('hex', 16, 49),
mac: buf.toString('hex', 49, 81),
ciphertext: buf.toString('hex', 81, buf.length)
}; // decompress publicKey
ret.ephemPublicKey = '04' + decompress(ret.ephemPublicKey);
return ret;
}

@ -1,40 +1,39 @@
import publicKeyByPrivateKey from './public-key-by-private-key';
import { fromPrivate } from 'eth-lib/lib/account';
import { keccak256 } from 'eth-lib/lib/hash';
import Bytes from 'eth-lib/lib/bytes';
var MIN_ENTROPY_SIZE = 128;
/**
* create a privateKey from the given entropy or a new one
* @param {Buffer} entropy
* @return {string}
*/
export function createPrivateKey(entropy) {
if (entropy) {
if (!Buffer.isBuffer(entropy)) throw new Error('EthCrypto.createPrivateKey(): given entropy is no Buffer');
if (Buffer.byteLength(entropy, 'utf8') < MIN_ENTROPY_SIZE) throw new Error('EthCrypto.createPrivateKey(): Entropy-size must be at least ' + MIN_ENTROPY_SIZE);
if (entropy) {
if (!Buffer.isBuffer(entropy)) throw new Error('EthCrypto.createPrivateKey(): given entropy is no Buffer');
if (Buffer.byteLength(entropy, 'utf8') < MIN_ENTROPY_SIZE) throw new Error('EthCrypto.createPrivateKey(): Entropy-size must be at least ' + MIN_ENTROPY_SIZE);
var outerHex = keccak256(entropy);
return outerHex;
} else {
// @link https://github.com/MaiaVictor/eth-lib/blob/master/lib/account.js#L8
var innerHex = keccak256(Bytes.concat(Bytes.random(32), Bytes.random(32)));
var middleHex = Bytes.concat(Bytes.concat(Bytes.random(32), innerHex), Bytes.random(32));
var outerHex = keccak256(entropy);
return outerHex;
} else {
// @link https://github.com/MaiaVictor/eth-lib/blob/master/lib/account.js#L8
var innerHex = keccak256(Bytes.concat(Bytes.random(32), Bytes.random(32)));
var middleHex = Bytes.concat(Bytes.concat(Bytes.random(32), innerHex), Bytes.random(32));
var _outerHex = keccak256(middleHex);
return _outerHex;
}
}
var _outerHex = keccak256(middleHex);
return _outerHex;
}
}
/**
* creates a new object with
* private-, public-Key and address
* @param {Buffer?} entropy if provided, will use that as single random-source
*/
export default function createIdentity(entropy) {
var privateKey = createPrivateKey(entropy);
var identity = fromPrivate(privateKey);
identity.publicKey = publicKeyByPrivateKey(identity.privateKey);
return identity;
var privateKey = createPrivateKey(entropy);
var identity = fromPrivate(privateKey);
identity.publicKey = publicKeyByPrivateKey(identity.privateKey);
return identity;
}

@ -1,22 +1,17 @@
import { decrypt } from 'eccrypto';
import { parse } from './cipher';
import { removeLeading0x } from './util';
export default function decryptWithPrivateKey(privateKey, encrypted) {
encrypted = parse(encrypted); // remove trailing '0x' from privateKey
encrypted = parse(encrypted);
// remove trailing '0x' from privateKey
var twoStripped = removeLeading0x(privateKey);
var encryptedBuffer = {
iv: Buffer.from(encrypted.iv, 'hex'),
ephemPublicKey: Buffer.from(encrypted.ephemPublicKey, 'hex'),
ciphertext: Buffer.from(encrypted.ciphertext, 'hex'),
mac: Buffer.from(encrypted.mac, 'hex')
};
return decrypt(Buffer.from(twoStripped, 'hex'), encryptedBuffer).then(function (decryptedBuffer) {
return decryptedBuffer.toString();
});
var twoStripped = removeLeading0x(privateKey);
var encryptedBuffer = {
iv: Buffer.from(encrypted.iv, 'hex'),
ephemPublicKey: Buffer.from(encrypted.ephemPublicKey, 'hex'),
ciphertext: Buffer.from(encrypted.ciphertext, 'hex'),
mac: Buffer.from(encrypted.mac, 'hex')
};
return decrypt(Buffer.from(twoStripped, 'hex'), encryptedBuffer).then(function (decryptedBuffer) {
return decryptedBuffer.toString();
});
}

@ -1,21 +1,17 @@
import { encrypt } from 'eccrypto';
import { decompress } from './public-key';
export default function encryptWithPublicKey(publicKey, message) {
// ensure its an uncompressed publicKey
publicKey = decompress(publicKey); // re-add the compression-flag
// ensure its an uncompressed publicKey
publicKey = decompress(publicKey);
// re-add the compression-flag
var pubString = '04' + publicKey;
return encrypt(Buffer.from(pubString, 'hex'), Buffer.from(message)).then(function (encryptedBuffers) {
var encrypted = {
iv: encryptedBuffers.iv.toString('hex'),
ephemPublicKey: encryptedBuffers.ephemPublicKey.toString('hex'),
ciphertext: encryptedBuffers.ciphertext.toString('hex'),
mac: encryptedBuffers.mac.toString('hex')
};
return encrypted;
});
var pubString = '04' + publicKey;
return encrypt(Buffer.from(pubString, 'hex'), Buffer.from(message)).then(function (encryptedBuffers) {
var encrypted = {
iv: encryptedBuffers.iv.toString('hex'),
ephemPublicKey: encryptedBuffers.ephemPublicKey.toString('hex'),
ciphertext: encryptedBuffers.ciphertext.toString('hex'),
mac: encryptedBuffers.mac.toString('hex')
};
return encrypted;
});
}

28
dist/es/hash.js vendored

@ -1,18 +1,18 @@
import { utils as ethersUtils } from 'ethers';
export function keccak256(params) {
var types = [];
var values = [];
if (!Array.isArray(params)) {
types.push('string');
values.push(params);
} else {
params.forEach(function (p) {
types.push(p.type);
values.push(p.value);
});
}
return ethersUtils.solidityKeccak256(types, values);
}
var types = [];
var values = [];
if (!Array.isArray(params)) {
types.push('string');
values.push(params);
} else {
params.forEach(function (p) {
types.push(p.type);
values.push(p.value);
});
}
return ethersUtils.solidityKeccak256(types, values);
}
export var SIGN_PREFIX = '\x19Ethereum Signed Message:\n32';

70
dist/es/hex.js vendored

@ -3,44 +3,42 @@
* thx @juvian
* @link https://stackoverflow.com/a/40471908/3443137
*/
import { removeLeading0x, addLeading0x } from './util';
export function compress(hex) {
var base64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
hex = removeLeading0x(hex);
// if base64:true, we use our own function because it results in a smaller output
if (base64 === true) return Buffer.from(hex, 'hex').toString('base64');
var string = '';
while (hex.length % 4 != 0) {
// we need it to be multiple of 4
hex = '0' + hex;
}
for (var i = 0; i < hex.length; i += 4) {
// get char from ascii code which goes from 0 to 65536
string += String.fromCharCode(parseInt(hex.substring(i, i + 4), 16));
}
return string;
}
var base64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
hex = removeLeading0x(hex); // if base64:true, we use our own function because it results in a smaller output
if (base64 === true) return Buffer.from(hex, 'hex').toString('base64');
var string = '';
while (hex.length % 4 != 0) {
// we need it to be multiple of 4
hex = '0' + hex;
}
for (var i = 0; i < hex.length; i += 4) {
// get char from ascii code which goes from 0 to 65536
string += String.fromCharCode(parseInt(hex.substring(i, i + 4), 16));
}
return string;
}
export function decompress(compressedString) {
var base64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
// if base64:true, we use our own function because it results in a smaller output
if (base64 === true) {
var ret = Buffer.from(compressedString, 'base64').toString('hex');
return addLeading0x(ret);
}
var hex = '';
for (var i = 0; i < compressedString.length; i++) {
// get character ascii code and convert to hexa string, adding necessary 0s
hex += ((i == 0 ? '' : '000') + compressedString.charCodeAt(i).toString(16)).slice(-4);
}
hex = hex.toLowerCase();
return addLeading0x(hex);
var base64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
// if base64:true, we use our own function because it results in a smaller output
if (base64 === true) {
var ret = Buffer.from(compressedString, 'base64').toString('hex');
return addLeading0x(ret);
}
var hex = '';
for (var i = 0; i < compressedString.length; i++) {
// get character ascii code and convert to hexa string, adding necessary 0s
hex += ((i == 0 ? '' : '000') + compressedString.charCodeAt(i).toString(16)).slice(-4);
}
hex = hex.toLowerCase();
return addLeading0x(hex);
}

35
dist/es/index.js vendored

@ -1,4 +1,3 @@
import createIdentity from './create-identity';
import * as publicKey from './public-key';
import decryptWithPrivateKey from './decrypt-with-private-key';
@ -15,24 +14,22 @@ import * as hash from './hash';
import * as hex from './hex';
import * as vrs from './vrs';
import * as util from './util';
export { createIdentity, publicKey, decryptWithPrivateKey, encryptWithPublicKey, cipher, publicKeyByPrivateKey, recover, recoverPublicKey, sign, signTransaction, txDataByCompiled, calculateContractAddress, hash, hex, vrs, util };
export default {
createIdentity: createIdentity,
publicKey: publicKey,
decryptWithPrivateKey: decryptWithPrivateKey,
encryptWithPublicKey: encryptWithPublicKey,
cipher: cipher,
publicKeyByPrivateKey: publicKeyByPrivateKey,
recover: recover,
recoverPublicKey: recoverPublicKey,
sign: sign,
signTransaction: signTransaction,
txDataByCompiled: txDataByCompiled,
calculateContractAddress: calculateContractAddress,
hash: hash,
hex: hex,
vrs: vrs,
util: util
createIdentity: createIdentity,
publicKey: publicKey,
decryptWithPrivateKey: decryptWithPrivateKey,
encryptWithPublicKey: encryptWithPublicKey,
cipher: cipher,
publicKeyByPrivateKey: publicKeyByPrivateKey,
recover: recover,
recoverPublicKey: recoverPublicKey,
sign: sign,
signTransaction: signTransaction,
txDataByCompiled: txDataByCompiled,
calculateContractAddress: calculateContractAddress,
hash: hash,
hex: hex,
vrs: vrs,
util: util
};

@ -1,14 +1,14 @@
import { privateToPublic, toBuffer } from 'ethereumjs-util';
import { addLeading0x } from './util';
/**
* Generate publicKey from the privateKey.
* This creates the uncompressed publicKey,
* where 04 has stripped from left
* @returns {string}
*/
export default function publicKeyOfPrivateKey(privateKey) {
privateKey = addLeading0x(privateKey);
var publicKeyBuffer = privateToPublic(toBuffer(privateKey));
return publicKeyBuffer.toString('hex');
privateKey = addLeading0x(privateKey);
var publicKeyBuffer = privateToPublic(toBuffer(privateKey));
return publicKeyBuffer.toString('hex');
}

@ -1,40 +1,31 @@
import { publicKeyConvert } from 'secp256k1';
import { pubToAddress, toChecksumAddress, toBuffer } from 'ethereumjs-util';
import { hexToUnit8Array, uint8ArrayToHex, addLeading0x } from './util';
export function compress(startsWith04) {
// add trailing 04 if not done before
var testBuffer = Buffer.from(startsWith04, 'hex');
if (testBuffer.length === 64) startsWith04 = '04' + startsWith04;
return uint8ArrayToHex(publicKeyConvert(hexToUnit8Array(startsWith04), true));
// add trailing 04 if not done before
var testBuffer = Buffer.from(startsWith04, 'hex');
if (testBuffer.length === 64) startsWith04 = '04' + startsWith04;
return uint8ArrayToHex(publicKeyConvert(hexToUnit8Array(startsWith04), true));
}
export function decompress(startsWith02Or03) {
// if already decompressed an not has trailing 04
var testBuffer = Buffer.from(startsWith02Or03, 'hex');
if (testBuffer.length === 64) startsWith02Or03 = '04' + startsWith02Or03;
var decompressed = uint8ArrayToHex(publicKeyConvert(hexToUnit8Array(startsWith02Or03), false)); // remove trailing 04
// if already decompressed an not has trailing 04
var testBuffer = Buffer.from(startsWith02Or03, 'hex');
if (testBuffer.length === 64) startsWith02Or03 = '04' + startsWith02Or03;
var decompressed = uint8ArrayToHex(publicKeyConvert(hexToUnit8Array(startsWith02Or03), false));
// remove trailing 04
decompressed = decompressed.substring(2);
return decompressed;
decompressed = decompressed.substring(2);
return decompressed;
}
/**
* generates the ethereum-adress of the publicKey
* We create the checksum-adress which is case-sensitive
* @returns {string} address
*/
export function toAddress(publicKey) {
// normalize key
publicKey = decompress(publicKey);
var addressBuffer = pubToAddress(toBuffer(addLeading0x(publicKey)));
var checkSumAdress = toChecksumAddress(addLeading0x(addressBuffer.toString('hex')));
return checkSumAdress;
export function toAddress(publicKey) {
// normalize key
publicKey = decompress(publicKey);
var addressBuffer = pubToAddress(toBuffer(addLeading0x(publicKey)));
var checkSumAdress = toChecksumAddress(addLeading0x(addressBuffer.toString('hex')));
return checkSumAdress;
}

@ -1,25 +1,22 @@
import { ecdsaRecover } from 'secp256k1';
import { removeLeading0x, hexToUnit8Array, uint8ArrayToHex } from './util';
/**
* returns the publicKey for the privateKey with which the messageHash was signed
* @param {string} signature
* @param {string} hash
* @return {string} publicKey
*/
export default function recoverPublicKey(signature, hash) {
signature = removeLeading0x(signature);
// split into v-value and sig
var sigOnly = signature.substring(0, signature.length - 2); // all but last 2 chars
var vValue = signature.slice(-2); // last 2 chars
export default function recoverPublicKey(signature, hash) {
signature = removeLeading0x(signature); // split into v-value and sig
var recoveryNumber = vValue === '1c' ? 1 : 0;
var sigOnly = signature.substring(0, signature.length - 2); // all but last 2 chars
var pubKey = uint8ArrayToHex(ecdsaRecover(hexToUnit8Array(sigOnly), recoveryNumber, hexToUnit8Array(removeLeading0x(hash)), false));
var vValue = signature.slice(-2); // last 2 chars
// remove trailing '04'
pubKey = pubKey.slice(2);
var recoveryNumber = vValue === '1c' ? 1 : 0;
var pubKey = uint8ArrayToHex(ecdsaRecover(hexToUnit8Array(sigOnly), recoveryNumber, hexToUnit8Array(removeLeading0x(hash)), false)); // remove trailing '04'
return pubKey;
pubKey = pubKey.slice(2);
return pubKey;
}

@ -1,14 +1,14 @@
import recoverPublicKey from './recover-public-key';
import { toAddress as addressByPublicKey } from './public-key';
/**
* returns the adress with which the messageHash was signed
* @param {string} sigString
* @param {string} hash
* @return {string} address
*/
export default function recover(sigString, hash) {
var pubkey = recoverPublicKey(sigString, hash);
var address = addressByPublicKey(pubkey);
return address;
var pubkey = recoverPublicKey(sigString, hash);
var address = addressByPublicKey(pubkey);
return address;
}

@ -1,21 +1,15 @@
import { Transaction } from '@ethereumjs/tx';
import publicKeyByPrivateKey from './public-key-by-private-key';
import { toAddress as addressByPublicKey } from './public-key';
export default function signTransaction(rawTx, privateKey) {
var txOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
// check if privateKey->address matches rawTx.from
var publicKey = publicKeyByPrivateKey(privateKey);
var address = addressByPublicKey(publicKey);
if (address != rawTx.from) throw new Error('EthCrypto.signTransaction(): rawTx.from does not match the address of the privateKey');
var privateKeyBuffer = Buffer.from(privateKey.replace(/^.{2}/g, ''), 'hex');
var tx = Transaction.fromTxData(rawTx, txOptions);
var signedTx = tx.sign(privateKeyBuffer);
var serializedTx = signedTx.serialize().toString('hex');
return serializedTx;
var txOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
// check if privateKey->address matches rawTx.from
var publicKey = publicKeyByPrivateKey(privateKey);
var address = addressByPublicKey(publicKey);
if (address != rawTx.from) throw new Error('EthCrypto.signTransaction(): rawTx.from does not match the address of the privateKey');
var privateKeyBuffer = Buffer.from(privateKey.replace(/^.{2}/g, ''), 'hex');
var tx = Transaction.fromTxData(rawTx, txOptions);
var signedTx = tx.sign(privateKeyBuffer);
var serializedTx = signedTx.serialize().toString('hex');
return serializedTx;
}

17
dist/es/sign.js vendored

@ -1,6 +1,5 @@
import { ecdsaSign as secp256k1_sign } from 'secp256k1';
import { addLeading0x, removeLeading0x } from './util';
/**
* signs the given message
* we do not use sign from eth-lib because the pure secp256k1-version is 90% faster
@ -8,14 +7,12 @@ import { addLeading0x, removeLeading0x } from './util';
* @param {string} hash
* @return {string} hexString
*/
export default function sign(privateKey, hash) {
hash = addLeading0x(hash);
if (hash.length !== 66) throw new Error('EthCrypto.sign(): Can only sign hashes, given: ' + hash);
var sigObj = secp256k1_sign(new Uint8Array(Buffer.from(removeLeading0x(hash), 'hex')), new Uint8Array(Buffer.from(removeLeading0x(privateKey), 'hex')));
var recoveryId = sigObj.recid === 1 ? '1c' : '1b';
var newSignature = '0x' + Buffer.from(sigObj.signature).toString('hex') + recoveryId;
return newSignature;
export default function sign(privateKey, hash) {
hash = addLeading0x(hash);
if (hash.length !== 66) throw new Error('EthCrypto.sign(): Can only sign hashes, given: ' + hash);
var sigObj = secp256k1_sign(new Uint8Array(Buffer.from(removeLeading0x(hash), 'hex')), new Uint8Array(Buffer.from(removeLeading0x(privateKey), 'hex')));
var recoveryId = sigObj.recid === 1 ? '1c' : '1b';
var newSignature = '0x' + Buffer.from(sigObj.signature).toString('hex') + recoveryId;
return newSignature;
}

@ -1,13 +1,21 @@
import { ContractFactory } from 'ethers';
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
export default function txDataByCompiled(abi, bytecode, args) {
// solc returns a string which is often passed instead of the json
if (typeof abi === 'string') abi = JSON.parse(abi);
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
// Construct a Contract Factory
var factory = new ContractFactory(abi, '0x' + bytecode);
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
var deployTransaction = factory.getDeployTransaction.apply(factory, args);
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
import { ContractFactory } from 'ethers';
export default function txDataByCompiled(abi, bytecode, args) {
// solc returns a string which is often passed instead of the json
if (typeof abi === 'string') abi = JSON.parse(abi); // Construct a Contract Factory
return deployTransaction.data;
var factory = new ContractFactory(abi, '0x' + bytecode);
var deployTransaction = factory.getDeployTransaction.apply(factory, _toConsumableArray(args));
return deployTransaction.data;
}

11
dist/es/util.js vendored

@ -1,15 +1,12 @@
export function removeLeading0x(str) {
if (str.startsWith('0x')) return str.substring(2);else return str;
if (str.startsWith('0x')) return str.substring(2);else return str;
}
export function addLeading0x(str) {
if (!str.startsWith('0x')) return '0x' + str;else return str;
if (!str.startsWith('0x')) return '0x' + str;else return str;
}
export function uint8ArrayToHex(arr) {
return Buffer.from(arr).toString('hex');
return Buffer.from(arr).toString('hex');
}
export function hexToUnit8Array(str) {
return new Uint8Array(Buffer.from(str, 'hex'));
return new Uint8Array(Buffer.from(str, 'hex'));
}

20
dist/es/vrs.js vendored

@ -1,25 +1,25 @@
import { decodeSignature, encodeSignature } from 'eth-lib/lib/account';
/**
* split signature-hex into parts
* @param {string} hexString
* @return {{v: string, r: string, s: string}}
*/
export function fromString(hexString) {
var arr = decodeSignature(hexString);
return {
v: arr[0],
r: arr[1],
s: arr[2]
};
var arr = decodeSignature(hexString);
return {
v: arr[0],
r: arr[1],
s: arr[2]
};
}
/**
* merge signature-parts to one string
* @param {{v: string, r: string, s: string}} sig
* @return {string} hexString
*/
export function toString(sig) {
var partsArray = [sig.v, sig.r, sig.s];
return encodeSignature(partsArray);
var partsArray = [sig.v, sig.r, sig.s];
return encodeSignature(partsArray);
}

@ -1,4 +1,4 @@
'use strict';
"use strict";
var EthCrypto = require('./index.js');

@ -1,16 +1,16 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports['default'] = calculateContractAddress;
exports["default"] = calculateContractAddress;
var _ethereumjsUtil = require('ethereumjs-util');
var _ethereumjsUtil = require("ethereumjs-util");
var _util = require('./util');
var _util = require("./util");
function calculateContractAddress(creatorAddress, nonce) {
var addressBuffer = (0, _ethereumjsUtil.generateAddress)((0, _ethereumjsUtil.toBuffer)((0, _util.addLeading0x)(creatorAddress)), (0, _ethereumjsUtil.toBuffer)(nonce));
var address = addressBuffer.toString('hex');
return (0, _ethereumjsUtil.toChecksumAddress)((0, _util.addLeading0x)(address));
var addressBuffer = (0, _ethereumjsUtil.generateAddress)((0, _ethereumjsUtil.toBuffer)((0, _util.addLeading0x)(creatorAddress)), (0, _ethereumjsUtil.toBuffer)(nonce));
var address = addressBuffer.toString('hex');
return (0, _ethereumjsUtil.toChecksumAddress)((0, _util.addLeading0x)(address));
}

53
dist/lib/cipher.js vendored

@ -1,42 +1,35 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports.stringify = stringify;
exports.parse = parse;
var _publicKey = require('./public-key');
var _publicKey = require("./public-key");
function stringify(cipher) {
if (typeof cipher === 'string') return cipher;
// use compressed key because it's smaller
var compressedKey = (0, _publicKey.compress)(cipher.ephemPublicKey);
var ret = Buffer.concat([Buffer.from(cipher.iv, 'hex'), // 16bit
Buffer.from(compressedKey, 'hex'), // 33bit
Buffer.from(cipher.mac, 'hex'), // 32bit
Buffer.from(cipher.ciphertext, 'hex') // var bit
]);
return ret.toString('hex');
if (typeof cipher === 'string') return cipher; // use compressed key because it's smaller
var compressedKey = (0, _publicKey.compress)(cipher.ephemPublicKey);
var ret = Buffer.concat([Buffer.from(cipher.iv, 'hex'), // 16bit
Buffer.from(compressedKey, 'hex'), // 33bit
Buffer.from(cipher.mac, 'hex'), // 32bit
Buffer.from(cipher.ciphertext, 'hex') // var bit
]);
return ret.toString('hex');
}
function parse(str) {
if (typeof str !== 'string') return str;
var buf = Buffer.from(str, 'hex');
var ret = {
iv: buf.toString('hex', 0, 16),
ephemPublicKey: buf.toString('hex', 16, 49),
mac: buf.toString('hex', 49, 81),
ciphertext: buf.toString('hex', 81, buf.length)
};
// decompress publicKey
ret.ephemPublicKey = '04' + (0, _publicKey.decompress)(ret.ephemPublicKey);
return ret;
if (typeof str !== 'string') return str;
var buf = Buffer.from(str, 'hex');
var ret = {
iv: buf.toString('hex', 0, 16),
ephemPublicKey: buf.toString('hex', 16, 49),
mac: buf.toString('hex', 49, 81),
ciphertext: buf.toString('hex', 81, buf.length)
}; // decompress publicKey
ret.ephemPublicKey = '04' + (0, _publicKey.decompress)(ret.ephemPublicKey);
return ret;
}

@ -1,56 +1,55 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports.createPrivateKey = createPrivateKey;
exports['default'] = createIdentity;
exports["default"] = createIdentity;
var _publicKeyByPrivateKey = require('./public-key-by-private-key');
var _publicKeyByPrivateKey = _interopRequireDefault(require("./public-key-by-private-key"));
var _publicKeyByPrivateKey2 = _interopRequireDefault(_publicKeyByPrivateKey);
var _account = require("eth-lib/lib/account");
var _account = require('eth-lib/lib/account');
var _hash = require("eth-lib/lib/hash");
var _hash = require('eth-lib/lib/hash');
var _bytes = _interopRequireDefault(require("eth-lib/lib/bytes"));
var _bytes = require('eth-lib/lib/bytes');
var _bytes2 = _interopRequireDefault(_bytes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var MIN_ENTROPY_SIZE = 128;
/**
* create a privateKey from the given entropy or a new one
* @param {Buffer} entropy
* @return {string}
*/
function createPrivateKey(entropy) {
if (entropy) {
if (!Buffer.isBuffer(entropy)) throw new Error('EthCrypto.createPrivateKey(): given entropy is no Buffer');
if (Buffer.byteLength(entropy, 'utf8') < MIN_ENTROPY_SIZE) throw new Error('EthCrypto.createPrivateKey(): Entropy-size must be at least ' + MIN_ENTROPY_SIZE);
var outerHex = (0, _hash.keccak256)(entropy);
return outerHex;
} else {
// @link https://github.com/MaiaVictor/eth-lib/blob/master/lib/account.js#L8
var innerHex = (0, _hash.keccak256)(_bytes2['default'].concat(_bytes2['default'].random(32), _bytes2['default'].random(32)));
var middleHex = _bytes2['default'].concat(_bytes2['default'].concat(_bytes2['default'].random(32), innerHex), _bytes2['default'].random(32));
var _outerHex = (0, _hash.keccak256)(middleHex);
return _outerHex;
}
}
if (entropy) {
if (!Buffer.isBuffer(entropy)) throw new Error('EthCrypto.createPrivateKey(): given entropy is no Buffer');
if (Buffer.byteLength(entropy, 'utf8') < MIN_ENTROPY_SIZE) throw new Error('EthCrypto.createPrivateKey(): Entropy-size must be at least ' + MIN_ENTROPY_SIZE);
var outerHex = (0, _hash.keccak256)(entropy);
return outerHex;
} else {
// @link https://github.com/MaiaVictor/eth-lib/blob/master/lib/account.js#L8
var innerHex = (0, _hash.keccak256)(_bytes["default"].concat(_bytes["default"].random(32), _bytes["default"].random(32)));
var middleHex = _bytes["default"].concat(_bytes["default"].concat(_bytes["default"].random(32), innerHex), _bytes["default"].random(32));
var _outerHex = (0, _hash.keccak256)(middleHex);
return _outerHex;
}
}
/**
* creates a new object with
* private-, public-Key and address
* @param {Buffer?} entropy if provided, will use that as single random-source
*/
function createIdentity(entropy) {
var privateKey = createPrivateKey(entropy);
var identity = (0, _account.fromPrivate)(privateKey);
identity.publicKey = (0, _publicKeyByPrivateKey2['default'])(identity.privateKey);
return identity;
var privateKey = createPrivateKey(entropy);
var identity = (0, _account.fromPrivate)(privateKey);
identity.publicKey = (0, _publicKeyByPrivateKey["default"])(identity.privateKey);
return identity;
}

@ -1,31 +1,27 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports['default'] = decryptWithPrivateKey;
exports["default"] = decryptWithPrivateKey;
var _eccrypto = require('eccrypto');
var _eccrypto = require("eccrypto");
var _cipher = require('./cipher');
var _cipher = require("./cipher");
var _util = require('./util');
var _util = require("./util");
function decryptWithPrivateKey(privateKey, encrypted) {
encrypted = (0, _cipher.parse)(encrypted);
// remove trailing '0x' from privateKey
var twoStripped = (0, _util.removeLeading0x)(privateKey);
var encryptedBuffer = {
iv: Buffer.from(encrypted.iv, 'hex'),
ephemPublicKey: Buffer.from(encrypted.ephemPublicKey, 'hex'),
ciphertext: Buffer.from(encrypted.ciphertext, 'hex'),
mac: Buffer.from(encrypted.mac, 'hex')
};
return (0, _eccrypto.decrypt)(Buffer.from(twoStripped, 'hex'), encryptedBuffer).then(function (decryptedBuffer) {
return decryptedBuffer.toString();
});
encrypted = (0, _cipher.parse)(encrypted); // remove trailing '0x' from privateKey
var twoStripped = (0, _util.removeLeading0x)(privateKey);
var encryptedBuffer = {
iv: Buffer.from(encrypted.iv, 'hex'),
ephemPublicKey: Buffer.from(encrypted.ephemPublicKey, 'hex'),
ciphertext: Buffer.from(encrypted.ciphertext, 'hex'),
mac: Buffer.from(encrypted.mac, 'hex')
};
return (0, _eccrypto.decrypt)(Buffer.from(twoStripped, 'hex'), encryptedBuffer).then(function (decryptedBuffer) {
return decryptedBuffer.toString();
});
}

@ -1,29 +1,26 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports['default'] = encryptWithPublicKey;
exports["default"] = encryptWithPublicKey;
var _eccrypto = require('eccrypto');
var _eccrypto = require("eccrypto");
var _publicKey = require('./public-key');
var _publicKey = require("./public-key");
function encryptWithPublicKey(publicKey, message) {
// ensure its an uncompressed publicKey
publicKey = (0, _publicKey.decompress)(publicKey); // re-add the compression-flag
// ensure its an uncompressed publicKey
publicKey = (0, _publicKey.decompress)(publicKey);
// re-add the compression-flag
var pubString = '04' + publicKey;
return (0, _eccrypto.encrypt)(Buffer.from(pubString, 'hex'), Buffer.from(message)).then(function (encryptedBuffers) {
var encrypted = {
iv: encryptedBuffers.iv.toString('hex'),
ephemPublicKey: encryptedBuffers.ephemPublicKey.toString('hex'),
ciphertext: encryptedBuffers.ciphertext.toString('hex'),
mac: encryptedBuffers.mac.toString('hex')
};
return encrypted;
});
var pubString = '04' + publicKey;
return (0, _eccrypto.encrypt)(Buffer.from(pubString, 'hex'), Buffer.from(message)).then(function (encryptedBuffers) {
var encrypted = {
iv: encryptedBuffers.iv.toString('hex'),
ephemPublicKey: encryptedBuffers.ephemPublicKey.toString('hex'),
ciphertext: encryptedBuffers.ciphertext.toString('hex'),
mac: encryptedBuffers.mac.toString('hex')
};
return encrypted;
});
}

37
dist/lib/hash.js vendored

@ -1,26 +1,29 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports.SIGN_PREFIX = undefined;
exports.keccak256 = keccak256;
exports.SIGN_PREFIX = void 0;
var _ethers = require('ethers');
var _ethers = require("ethers");
function keccak256(params) {
var types = [];
var values = [];
if (!Array.isArray(params)) {
types.push('string');
values.push(params);
} else {
params.forEach(function (p) {
types.push(p.type);
values.push(p.value);
});
}
return _ethers.utils.solidityKeccak256(types, values);
var types = [];
var values = [];
if (!Array.isArray(params)) {
types.push('string');
values.push(params);
} else {
params.forEach(function (p) {
types.push(p.type);
values.push(p.value);
});
}
return _ethers.utils.solidityKeccak256(types, values);
}
var SIGN_PREFIX = exports.SIGN_PREFIX = '\x19Ethereum Signed Message:\n32';
var SIGN_PREFIX = '\x19Ethereum Signed Message:\n32';
exports.SIGN_PREFIX = SIGN_PREFIX;

84
dist/lib/hex.js vendored

@ -1,52 +1,54 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports.compress = compress;
exports.decompress = decompress;
var _util = require('./util');
var _util = require("./util");
/**
* compress/decompress hex-strings to utf16 or base64
* thx @juvian
* @link https://stackoverflow.com/a/40471908/3443137
*/
function compress(hex) {
var base64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
hex = (0, _util.removeLeading0x)(hex);
// if base64:true, we use our own function because it results in a smaller output
if (base64 === true) return Buffer.from(hex, 'hex').toString('base64');
var string = '';
while (hex.length % 4 != 0) {
// we need it to be multiple of 4
hex = '0' + hex;
}
for (var i = 0; i < hex.length; i += 4) {
// get char from ascii code which goes from 0 to 65536
string += String.fromCharCode(parseInt(hex.substring(i, i + 4), 16));
}
return string;
} /**
* compress/decompress hex-strings to utf16 or base64
* thx @juvian
* @link https://stackoverflow.com/a/40471908/3443137
*/
var base64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
hex = (0, _util.removeLeading0x)(hex); // if base64:true, we use our own function because it results in a smaller output
if (base64 === true) return Buffer.from(hex, 'hex').toString('base64');
var string = '';
while (hex.length % 4 != 0) {
// we need it to be multiple of 4
hex = '0' + hex;
}
for (var i = 0; i < hex.length; i += 4) {
// get char from ascii code which goes from 0 to 65536
string += String.fromCharCode(parseInt(hex.substring(i, i + 4), 16));
}
return string;
}
function decompress(compressedString) {
var base64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
// if base64:true, we use our own function because it results in a smaller output
if (base64 === true) {
var ret = Buffer.from(compressedString, 'base64').toString('hex');
return (0, _util.addLeading0x)(ret);
}
var hex = '';
for (var i = 0; i < compressedString.length; i++) {
// get character ascii code and convert to hexa string, adding necessary 0s
hex += ((i == 0 ? '' : '000') + compressedString.charCodeAt(i).toString(16)).slice(-4);
}
hex = hex.toLowerCase();
return (0, _util.addLeading0x)(hex);
var base64 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
// if base64:true, we use our own function because it results in a smaller output
if (base64 === true) {
var ret = Buffer.from(compressedString, 'base64').toString('hex');
return (0, _util.addLeading0x)(ret);
}
var hex = '';
for (var i = 0; i < compressedString.length; i++) {
// get character ascii code and convert to hexa string, adding necessary 0s
hex += ((i == 0 ? '' : '000') + compressedString.charCodeAt(i).toString(16)).slice(-4);
}
hex = hex.toLowerCase();
return (0, _util.addLeading0x)(hex);
}

193
dist/lib/index.js vendored

@ -1,109 +1,138 @@
'use strict';
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports.util = exports.vrs = exports.hex = exports.hash = exports.calculateContractAddress = exports.txDataByCompiled = exports.signTransaction = exports.sign = exports.recoverPublicKey = exports.recover = exports.publicKeyByPrivateKey = exports.cipher = exports.encryptWithPublicKey = exports.decryptWithPrivateKey = exports.publicKey = exports.createIdentity = undefined;
var _createIdentity = require('./create-identity');
var _createIdentity2 = _interopRequireDefault(_createIdentity);
var _publicKey = require('./public-key');
var publicKey = _interopRequireWildcard(_publicKey);
var _decryptWithPrivateKey = require('./decrypt-with-private-key');
var _decryptWithPrivateKey2 = _interopRequireDefault(_decryptWithPrivateKey);
var _encryptWithPublicKey = require('./encrypt-with-public-key');
var _encryptWithPublicKey2 = _interopRequireDefault(_encryptWithPublicKey);
var _cipher = require('./cipher');
var cipher = _interopRequireWildcard(_cipher);
var _publicKeyByPrivateKey = require('./public-key-by-private-key');
var _publicKeyByPrivateKey2 = _interopRequireDefault(_publicKeyByPrivateKey);
var _recover = require('./recover');
Object.defineProperty(exports, "createIdentity", {
enumerable: true,
get: function get() {
return _createIdentity["default"];
}
});
Object.defineProperty(exports, "decryptWithPrivateKey", {
enumerable: true,
get: function get() {
return _decryptWithPrivateKey["default"];
}
});
Object.defineProperty(exports, "encryptWithPublicKey", {
enumerable: true,
get: function get() {
return _encryptWithPublicKey["default"];
}
});
Object.defineProperty(exports, "publicKeyByPrivateKey", {
enumerable: true,
get: function get() {
return _publicKeyByPrivateKey["default"];
}
});
Object.defineProperty(exports, "recover", {
enumerable: true,
get: function get() {
return _recover["default"];
}
});
Object.defineProperty(exports, "recoverPublicKey", {
enumerable: true,
get: function get() {
return _recoverPublicKey["default"];
}
});
Object.defineProperty(exports, "sign", {
enumerable: true,
get: function get() {
return _sign["default"];
}
});
Object.defineProperty(exports, "signTransaction", {
enumerable: true,
get: function get() {
return _signTransaction["default"];
}
});
Object.defineProperty(exports, "txDataByCompiled", {
enumerable: true,
get: function get() {
return _txDataByCompiled["default"];
}
});
Object.defineProperty(exports, "calculateContractAddress", {
enumerable: true,
get: function get() {
return _calculateContractAddress["default"];
}
});
exports.util = exports.vrs = exports.hex = exports.hash = exports.cipher = exports.publicKey = exports["default"] = void 0;
var _recover2 = _interopRequireDefault(_recover);
var _createIdentity = _interopRequireDefault(require("./create-identity"));
var _recoverPublicKey = require('./recover-public-key');
var publicKey = _interopRequireWildcard(require("./public-key"));
var _recoverPublicKey2 = _interopRequireDefault(_recoverPublicKey);
exports.publicKey = publicKey;
var _sign = require('./sign');
var _decryptWithPrivateKey = _interopRequireDefault(require("./decrypt-with-private-key"));
var _sign2 = _interopRequireDefault(_sign);
var _encryptWithPublicKey = _interopRequireDefault(require("./encrypt-with-public-key"));
var _signTransaction = require('./sign-transaction');
var cipher = _interopRequireWildcard(require("./cipher"));
var _signTransaction2 = _interopRequireDefault(_signTransaction);
exports.cipher = cipher;
var _txDataByCompiled = require('./tx-data-by-compiled');
var _publicKeyByPrivateKey = _interopRequireDefault(require("./public-key-by-private-key"));
var _txDataByCompiled2 = _interopRequireDefault(_txDataByCompiled);
var _recover = _interopRequireDefault(require("./recover"));
var _calculateContractAddress = require('./calculate-contract-address');
var _recoverPublicKey = _interopRequireDefault(require("./recover-public-key"));
var _calculateContractAddress2 = _interopRequireDefault(_calculateContractAddress);
var _sign = _interopRequireDefault(require("./sign"));
var _hash = require('./hash');
var _signTransaction = _interopRequireDefault(require("./sign-transaction"));
var hash = _interopRequireWildcard(_hash);
var _txDataByCompiled = _interopRequireDefault(require("./tx-data-by-compiled"));
var _hex = require('./hex');
var _calculateContractAddress = _interopRequireDefault(require("./calculate-contract-address"));
var hex = _interopRequireWildcard(_hex);
var hash = _interopRequireWildcard(require("./hash"));
var _vrs = require('./vrs');
exports.hash = hash;
var vrs = _interopRequireWildcard(_vrs);
var hex = _interopRequireWildcard(require("./hex"));
var _util = require('./util');
exports.hex = hex;
var util = _interopRequireWildcard(_util);
var vrs = _interopRequireWildcard(require("./vrs"));
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
exports.vrs = vrs;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var util = _interopRequireWildcard(require("./util"));
exports.createIdentity = _createIdentity2['default'];
exports.publicKey = publicKey;
exports.decryptWithPrivateKey = _decryptWithPrivateKey2['default'];
exports.encryptWithPublicKey = _encryptWithPublicKey2['default'];
exports.cipher = cipher;
exports.publicKeyByPrivateKey = _publicKeyByPrivateKey2['default'];
exports.recover = _recover2['default'];
exports.recoverPublicKey = _recoverPublicKey2['default'];
exports.sign = _sign2['default'];
exports.signTransaction = _signTransaction2['default'];
exports.txDataByCompiled = _txDataByCompiled2['default'];
exports.calculateContractAddress = _calculateContractAddress2['default'];
exports.hash = hash;
exports.hex = hex;
exports.vrs = vrs;
exports.util = util;
exports['default'] = {
createIdentity: _createIdentity2['default'],
publicKey: publicKey,
decryptWithPrivateKey: _decryptWithPrivateKey2['default'],
encryptWithPublicKey: _encryptWithPublicKey2['default'],
cipher: cipher,
publicKeyByPrivateKey: _publicKeyByPrivateKey2['default'],
recover: _recover2['default'],
recoverPublicKey: _recoverPublicKey2['default'],
sign: _sign2['default'],
signTransaction: _signTransaction2['default'],
txDataByCompiled: _txDataByCompiled2['default'],
calculateContractAddress: _calculateContractAddress2['default'],
hash: hash,
hex: hex,
vrs: vrs,
util: util
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var _default = {
createIdentity: _createIdentity["default"],
publicKey: publicKey,
decryptWithPrivateKey: _decryptWithPrivateKey["default"],
encryptWithPublicKey: _encryptWithPublicKey["default"],
cipher: cipher,
publicKeyByPrivateKey: _publicKeyByPrivateKey["default"],
recover: _recover["default"],
recoverPublicKey: _recoverPublicKey["default"],
sign: _sign["default"],
signTransaction: _signTransaction["default"],
txDataByCompiled: _txDataByCompiled["default"],
calculateContractAddress: _calculateContractAddress["default"],
hash: hash,
hex: hex,
vrs: vrs,
util: util
};
exports["default"] = _default;

@ -1,13 +1,13 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports['default'] = publicKeyOfPrivateKey;
exports["default"] = publicKeyOfPrivateKey;
var _ethereumjsUtil = require('ethereumjs-util');
var _ethereumjsUtil = require("ethereumjs-util");
var _util = require('./util');
var _util = require("./util");
/**
* Generate publicKey from the privateKey.
@ -16,7 +16,7 @@ var _util = require('./util');
* @returns {string}
*/
function publicKeyOfPrivateKey(privateKey) {
privateKey = (0, _util.addLeading0x)(privateKey);
var publicKeyBuffer = (0, _ethereumjsUtil.privateToPublic)((0, _ethereumjsUtil.toBuffer)(privateKey));
return publicKeyBuffer.toString('hex');
privateKey = (0, _util.addLeading0x)(privateKey);
var publicKeyBuffer = (0, _ethereumjsUtil.privateToPublic)((0, _ethereumjsUtil.toBuffer)(privateKey));
return publicKeyBuffer.toString('hex');
}

@ -1,51 +1,45 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports.compress = compress;
exports.decompress = decompress;
exports.toAddress = toAddress;
var _secp256k = require('secp256k1');
var _secp256k = require("secp256k1");
var _ethereumjsUtil = require('ethereumjs-util');
var _ethereumjsUtil = require("ethereumjs-util");
var _util = require('./util');
var _util = require("./util");
function compress(startsWith04) {
// add trailing 04 if not done before
var testBuffer = Buffer.from(startsWith04, 'hex');
if (testBuffer.length === 64) startsWith04 = '04' + startsWith04;
return (0, _util.uint8ArrayToHex)((0, _secp256k.publicKeyConvert)((0, _util.hexToUnit8Array)(startsWith04), true));
// add trailing 04 if not done before
var testBuffer = Buffer.from(startsWith04, 'hex');
if (testBuffer.length === 64) startsWith04 = '04' + startsWith04;
return (0, _util.uint8ArrayToHex)((0, _secp256k.publicKeyConvert)((0, _util.hexToUnit8Array)(startsWith04), true));
}
function decompress(startsWith02Or03) {
// if already decompressed an not has trailing 04
var testBuffer = Buffer.from(startsWith02Or03, 'hex');
if (testBuffer.length === 64) startsWith02Or03 = '04' + startsWith02Or03;
var decompressed = (0, _util.uint8ArrayToHex)((0, _secp256k.publicKeyConvert)((0, _util.hexToUnit8Array)(startsWith02Or03), false)); // remove trailing 04
// if already decompressed an not has trailing 04
var testBuffer = Buffer.from(startsWith02Or03, 'hex');
if (testBuffer.length === 64) startsWith02Or03 = '04' + startsWith02Or03;
var decompressed = (0, _util.uint8ArrayToHex)((0, _secp256k.publicKeyConvert)((0, _util.hexToUnit8Array)(startsWith02Or03), false));
// remove trailing 04
decompressed = decompressed.substring(2);
return decompressed;
decompressed = decompressed.substring(2);
return decompressed;
}
/**
* generates the ethereum-adress of the publicKey
* We create the checksum-adress which is case-sensitive
* @returns {string} address
*/
function toAddress(publicKey) {
// normalize key
publicKey = decompress(publicKey);
var addressBuffer = (0, _ethereumjsUtil.pubToAddress)((0, _ethereumjsUtil.toBuffer)((0, _util.addLeading0x)(publicKey)));
var checkSumAdress = (0, _ethereumjsUtil.toChecksumAddress)((0, _util.addLeading0x)(addressBuffer.toString('hex')));
return checkSumAdress;
function toAddress(publicKey) {
// normalize key
publicKey = decompress(publicKey);
var addressBuffer = (0, _ethereumjsUtil.pubToAddress)((0, _ethereumjsUtil.toBuffer)((0, _util.addLeading0x)(publicKey)));
var checkSumAdress = (0, _ethereumjsUtil.toChecksumAddress)((0, _util.addLeading0x)(addressBuffer.toString('hex')));
return checkSumAdress;
}

@ -1,13 +1,13 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports['default'] = recoverPublicKey;
exports["default"] = recoverPublicKey;
var _secp256k = require('secp256k1');
var _secp256k = require("secp256k1");
var _util = require('./util');
var _util = require("./util");
/**
* returns the publicKey for the privateKey with which the messageHash was signed
@ -16,18 +16,15 @@ var _util = require('./util');
* @return {string} publicKey
*/
function recoverPublicKey(signature, hash) {
signature = (0, _util.removeLeading0x)(signature);
signature = (0, _util.removeLeading0x)(signature); // split into v-value and sig
// split into v-value and sig
var sigOnly = signature.substring(0, signature.length - 2); // all but last 2 chars
var vValue = signature.slice(-2); // last 2 chars
var sigOnly = signature.substring(0, signature.length - 2); // all but last 2 chars
var recoveryNumber = vValue === '1c' ? 1 : 0;
var vValue = signature.slice(-2); // last 2 chars
var pubKey = (0, _util.uint8ArrayToHex)((0, _secp256k.ecdsaRecover)((0, _util.hexToUnit8Array)(sigOnly), recoveryNumber, (0, _util.hexToUnit8Array)((0, _util.removeLeading0x)(hash)), false));
var recoveryNumber = vValue === '1c' ? 1 : 0;
var pubKey = (0, _util.uint8ArrayToHex)((0, _secp256k.ecdsaRecover)((0, _util.hexToUnit8Array)(sigOnly), recoveryNumber, (0, _util.hexToUnit8Array)((0, _util.removeLeading0x)(hash)), false)); // remove trailing '04'
// remove trailing '04'
pubKey = pubKey.slice(2);
return pubKey;
pubKey = pubKey.slice(2);
return pubKey;
}

@ -1,17 +1,15 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports['default'] = recover;
exports["default"] = recover;
var _recoverPublicKey = require('./recover-public-key');
var _recoverPublicKey = _interopRequireDefault(require("./recover-public-key"));
var _recoverPublicKey2 = _interopRequireDefault(_recoverPublicKey);
var _publicKey = require("./public-key");
var _publicKey = require('./public-key');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* returns the adress with which the messageHash was signed
@ -20,7 +18,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'd
* @return {string} address
*/
function recover(sigString, hash) {
var pubkey = (0, _recoverPublicKey2['default'])(sigString, hash);
var address = (0, _publicKey.toAddress)(pubkey);
return address;
var pubkey = (0, _recoverPublicKey["default"])(sigString, hash);
var address = (0, _publicKey.toAddress)(pubkey);
return address;
}

@ -1,33 +1,29 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports['default'] = signTransaction;
exports["default"] = signTransaction;
var _tx = require('@ethereumjs/tx');
var _tx = require("@ethereumjs/tx");
var _publicKeyByPrivateKey = require('./public-key-by-private-key');
var _publicKeyByPrivateKey = _interopRequireDefault(require("./public-key-by-private-key"));
var _publicKeyByPrivateKey2 = _interopRequireDefault(_publicKeyByPrivateKey);
var _publicKey = require("./public-key");
var _publicKey = require('./public-key');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function signTransaction(rawTx, privateKey) {
var txOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
// check if privateKey->address matches rawTx.from
var publicKey = (0, _publicKeyByPrivateKey2['default'])(privateKey);
var address = (0, _publicKey.toAddress)(publicKey);
if (address != rawTx.from) throw new Error('EthCrypto.signTransaction(): rawTx.from does not match the address of the privateKey');
var privateKeyBuffer = Buffer.from(privateKey.replace(/^.{2}/g, ''), 'hex');
var tx = _tx.Transaction.fromTxData(rawTx, txOptions);
var signedTx = tx.sign(privateKeyBuffer);
var serializedTx = signedTx.serialize().toString('hex');
return serializedTx;
var txOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
// check if privateKey->address matches rawTx.from
var publicKey = (0, _publicKeyByPrivateKey["default"])(privateKey);
var address = (0, _publicKey.toAddress)(publicKey);
if (address != rawTx.from) throw new Error('EthCrypto.signTransaction(): rawTx.from does not match the address of the privateKey');
var privateKeyBuffer = Buffer.from(privateKey.replace(/^.{2}/g, ''), 'hex');
var tx = _tx.Transaction.fromTxData(rawTx, txOptions);
var signedTx = tx.sign(privateKeyBuffer);
var serializedTx = signedTx.serialize().toString('hex');
return serializedTx;
}

25
dist/lib/sign.js vendored

@ -1,13 +1,13 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports['default'] = sign;
exports["default"] = sign;
var _secp256k = require('secp256k1');
var _secp256k = require("secp256k1");
var _util = require('./util');
var _util = require("./util");
/**
* signs the given message
@ -17,13 +17,10 @@ var _util = require('./util');
* @return {string} hexString
*/
function sign(privateKey, hash) {
hash = (0, _util.addLeading0x)(hash);
if (hash.length !== 66) throw new Error('EthCrypto.sign(): Can only sign hashes, given: ' + hash);
var sigObj = (0, _secp256k.ecdsaSign)(new Uint8Array(Buffer.from((0, _util.removeLeading0x)(hash), 'hex')), new Uint8Array(Buffer.from((0, _util.removeLeading0x)(privateKey), 'hex')));
var recoveryId = sigObj.recid === 1 ? '1c' : '1b';
var newSignature = '0x' + Buffer.from(sigObj.signature).toString('hex') + recoveryId;
return newSignature;
hash = (0, _util.addLeading0x)(hash);
if (hash.length !== 66) throw new Error('EthCrypto.sign(): Can only sign hashes, given: ' + hash);
var sigObj = (0, _secp256k.ecdsaSign)(new Uint8Array(Buffer.from((0, _util.removeLeading0x)(hash), 'hex')), new Uint8Array(Buffer.from((0, _util.removeLeading0x)(privateKey), 'hex')));
var recoveryId = sigObj.recid === 1 ? '1c' : '1b';
var newSignature = '0x' + Buffer.from(sigObj.signature).toString('hex') + recoveryId;
return newSignature;
}

@ -1,27 +1,29 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports["default"] = txDataByCompiled;
var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');
var _ethers = require("ethers");
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
exports['default'] = txDataByCompiled;
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
var _ethers = require('ethers');
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function txDataByCompiled(abi, bytecode, args) {
// solc returns a string which is often passed instead of the json
if (typeof abi === 'string') abi = JSON.parse(abi);
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
// Construct a Contract Factory
var factory = new _ethers.ContractFactory(abi, '0x' + bytecode);
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
var deployTransaction = factory.getDeployTransaction.apply(factory, (0, _toConsumableArray3['default'])(args));
function txDataByCompiled(abi, bytecode, args) {
// solc returns a string which is often passed instead of the json
if (typeof abi === 'string') abi = JSON.parse(abi); // Construct a Contract Factory
return deployTransaction.data;
var factory = new _ethers.ContractFactory(abi, '0x' + bytecode);
var deployTransaction = factory.getDeployTransaction.apply(factory, _toConsumableArray(args));
return deployTransaction.data;
}

13
dist/lib/util.js vendored

@ -1,24 +1,25 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports.removeLeading0x = removeLeading0x;
exports.addLeading0x = addLeading0x;
exports.uint8ArrayToHex = uint8ArrayToHex;
exports.hexToUnit8Array = hexToUnit8Array;
function removeLeading0x(str) {
if (str.startsWith('0x')) return str.substring(2);else return str;
if (str.startsWith('0x')) return str.substring(2);else return str;
}
function addLeading0x(str) {
if (!str.startsWith('0x')) return '0x' + str;else return str;
if (!str.startsWith('0x')) return '0x' + str;else return str;
}
function uint8ArrayToHex(arr) {
return Buffer.from(arr).toString('hex');
return Buffer.from(arr).toString('hex');
}
function hexToUnit8Array(str) {
return new Uint8Array(Buffer.from(str, 'hex'));
return new Uint8Array(Buffer.from(str, 'hex'));
}

25
dist/lib/vrs.js vendored

@ -1,12 +1,12 @@
'use strict';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
value: true
});
exports.fromString = fromString;
exports.toString = toString;
var _account = require('eth-lib/lib/account');
var _account = require("eth-lib/lib/account");
/**
* split signature-hex into parts
@ -14,20 +14,21 @@ var _account = require('eth-lib/lib/account');
* @return {{v: string, r: string, s: string}}
*/
function fromString(hexString) {
var arr = (0, _account.decodeSignature)(hexString);
return {
v: arr[0],
r: arr[1],
s: arr[2]
};
var arr = (0, _account.decodeSignature)(hexString);
return {
v: arr[0],
r: arr[1],
s: arr[2]
};
}
/**
* merge signature-parts to one string
* @param {{v: string, r: string, s: string}} sig
* @return {string} hexString
*/
function toString(sig) {
var partsArray = [sig.v, sig.r, sig.s];
return (0, _account.encodeSignature)(partsArray);
var partsArray = [sig.v, sig.r, sig.s];
return (0, _account.encodeSignature)(partsArray);
}

@ -31,8 +31,8 @@
"clear": "rimraf -rf ./dist && rimraf -rf ./gen && rimraf -rf ./test_tmp",
"build:sol": "solidity-cli -i './contracts/*.sol' -o ./gen",
"build:es6": "rimraf -rf dist/es && cross-env NODE_ENV=es6 babel src --out-dir dist/es",
"build:es5": "cross-env NODE_ENV=es5 node node_modules/babel-cli/bin/babel.js src --out-dir dist/lib",
"build:test": "cross-env NODE_ENV=es5 node node_modules/babel-cli/bin/babel.js test --out-dir test_tmp",
"build:es5": "babel src --out-dir dist/lib",
"build:test": "babel test --out-dir test_tmp",
"build": "npm run clear && concurrently \"npm run build:es6\" \"npm run build:es5\" \"npm run build:test\" \"npm run build:sol\"",
"build:webpack": "npm run build && cross-env NODE_ENV=build webpack --config ./config/webpack.config.js",
"build:size": "npm run build:webpack && echo \"Build-Size (minified+gzip):\" && gzip-size --raw ./test_tmp/webpack.bundle.js",
@ -49,27 +49,12 @@
},
"homepage": "https://github.com/pubkey/eth-crypto#readme",
"devDependencies": {
"@babel/cli": "^7.15.4",
"@babel/core": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"assert": "2.0.0",
"async-test-util": "1.7.3",
"babel-cli": "6.26.0",
"babel-core": "6.26.3",
"babel-loader": "8.2.2",
"babel-plugin-transform-async-to-generator": "6.24.1",
"babel-plugin-transform-class-properties": "6.24.1",
"babel-plugin-transform-es2015-block-scoping": "6.26.0",
"babel-plugin-transform-es2015-constants": "6.1.4",
"babel-plugin-transform-es3-member-expression-literals": "6.22.0",
"babel-plugin-transform-es3-property-literals": "6.22.0",
"babel-plugin-transform-object-rest-spread": "6.26.0",
"babel-plugin-transform-regenerator": "6.26.0",
"babel-plugin-transform-runtime": "6.23.0",
"babel-polyfill": "6.26.0",
"babel-preset-es2015": "6.24.1",
"babel-preset-es2015-native-modules": "6.9.4",
"babel-preset-es2015-rollup": "3.0.0",
"babel-preset-es2016": "6.24.1",
"babel-preset-es2017": "6.24.1",
"babel-preset-latest": "6.24.1",
"bn.js": "5.2.0",
"browserify": "17.0.0",
"concurrently": "6.2.1",
@ -110,7 +95,6 @@
"dependencies": {
"@ethereumjs/tx": "3.3.0",
"@types/bn.js": "5.1.0",
"babel-runtime": "6.26.0",
"eccrypto": "1.1.6",
"eth-lib": "0.2.8",
"ethereumjs-util": "7.1.0",

Loading…
Cancel
Save