2
0
mirror of synced 2025-02-24 20:18:07 +00:00

Renamed convert to bytes.

This commit is contained in:
Richard Moore 2018-06-17 16:47:28 -04:00
parent af893e79a4
commit c1b24e818c
No known key found for this signature in database
GPG Key ID: 525F70A6FCABC295
78 changed files with 758 additions and 516 deletions

52
dist/ethers.d.ts vendored
View File

@ -1,5 +1,5 @@
declare module "utils/keccak256" { declare module "utils/keccak256" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
export function keccak256(data: Arrayish): string; export function keccak256(data: Arrayish): string;
} }
declare module "utils/properties" { declare module "utils/properties" {
@ -25,7 +25,7 @@ declare module "utils/errors" {
export function checkNew(self: any, kind: any): void; export function checkNew(self: any, kind: any): void;
} }
declare module "utils/secp256k1" { declare module "utils/secp256k1" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
export const N: string; export const N: string;
export interface Signature { export interface Signature {
r: string; r: string;
@ -46,7 +46,7 @@ declare module "utils/secp256k1" {
export function recoverAddress(digest: Arrayish, signature: Signature): string; export function recoverAddress(digest: Arrayish, signature: Signature): string;
export function computeAddress(key: string): string; export function computeAddress(key: string): string;
} }
declare module "utils/convert" { declare module "utils/bytes" {
/** /**
* Conversion Utilities * Conversion Utilities
* *
@ -68,7 +68,7 @@ declare module "utils/convert" {
export function splitSignature(signature: Arrayish): Signature; export function splitSignature(signature: Arrayish): Signature;
} }
declare module "utils/bignumber" { declare module "utils/bignumber" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
export type BigNumberish = BigNumber | string | number | Arrayish; export type BigNumberish = BigNumber | string | number | Arrayish;
export class BigNumber { export class BigNumber {
private readonly _bn; private readonly _bn;
@ -101,13 +101,13 @@ declare module "utils/bignumber" {
export const ConstantWeiPerEther: BigNumber; export const ConstantWeiPerEther: BigNumber;
} }
declare module "utils/rlp" { declare module "utils/rlp" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
export function encode(object: any): string; export function encode(object: any): string;
export function decode(data: Arrayish): any; export function decode(data: Arrayish): any;
} }
declare module "utils/address" { declare module "utils/address" {
import { BigNumber } from "utils/bignumber"; import { BigNumber } from "utils/bignumber";
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
export function getAddress(address: string): string; export function getAddress(address: string): string;
export function getIcapAddress(address: string): string; export function getIcapAddress(address: string): string;
export function getContractAddress(transaction: { export function getContractAddress(transaction: {
@ -116,7 +116,7 @@ declare module "utils/address" {
}): string; }): string;
} }
declare module "utils/utf8" { declare module "utils/utf8" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
export enum UnicodeNormalizationForm { export enum UnicodeNormalizationForm {
current = "", current = "",
NFC = "NFC", NFC = "NFC",
@ -128,7 +128,7 @@ declare module "utils/utf8" {
export function toUtf8String(bytes: Arrayish): string; export function toUtf8String(bytes: Arrayish): string;
} }
declare module "utils/abi-coder" { declare module "utils/abi-coder" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
export type CoerceFunc = (type: string, value: any) => any; export type CoerceFunc = (type: string, value: any) => any;
export type ParamType = { export type ParamType = {
name?: string; name?: string;
@ -277,7 +277,7 @@ declare module "providers/networks" {
} }
declare module "utils/transaction" { declare module "utils/transaction" {
import { BigNumber, BigNumberish } from "utils/bignumber"; import { BigNumber, BigNumberish } from "utils/bignumber";
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
import { Signature } from "utils/secp256k1"; import { Signature } from "utils/secp256k1";
export interface UnsignedTransaction { export interface UnsignedTransaction {
to?: string; to?: string;
@ -308,7 +308,7 @@ declare module "utils/transaction" {
} }
declare module "providers/provider" { declare module "providers/provider" {
import { BigNumber, BigNumberish } from "utils/bignumber"; import { BigNumber, BigNumberish } from "utils/bignumber";
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
import { Network } from "providers/networks"; import { Network } from "providers/networks";
import { Transaction } from "utils/transaction"; import { Transaction } from "utils/transaction";
export type BlockTag = string | number; export type BlockTag = string | number;
@ -436,7 +436,7 @@ declare module "wallet/words" {
export function getWordIndex(word: string): number; export function getWordIndex(word: string): number;
} }
declare module "utils/hmac" { declare module "utils/hmac" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
interface HashFunc { interface HashFunc {
(): HashFunc; (): HashFunc;
update(chunk: Uint8Array): HashFunc; update(chunk: Uint8Array): HashFunc;
@ -450,7 +450,7 @@ declare module "utils/hmac" {
export function createSha512Hmac(key: Arrayish): HmacFunc; export function createSha512Hmac(key: Arrayish): HmacFunc;
} }
declare module "utils/pbkdf2" { declare module "utils/pbkdf2" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
import { HmacFunc } from "utils/hmac"; import { HmacFunc } from "utils/hmac";
export interface CreateHmacFunc { export interface CreateHmacFunc {
(key: Arrayish): HmacFunc; (key: Arrayish): HmacFunc;
@ -458,12 +458,12 @@ declare module "utils/pbkdf2" {
export function pbkdf2(password: Arrayish, salt: Arrayish, iterations: number, keylen: number, createHmac: CreateHmacFunc): Uint8Array; export function pbkdf2(password: Arrayish, salt: Arrayish, iterations: number, keylen: number, createHmac: CreateHmacFunc): Uint8Array;
} }
declare module "utils/sha2" { declare module "utils/sha2" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
export function sha256(data: Arrayish): string; export function sha256(data: Arrayish): string;
export function sha512(data: Arrayish): string; export function sha512(data: Arrayish): string;
} }
declare module "wallet/hdnode" { declare module "wallet/hdnode" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
import { KeyPair } from "utils/secp256k1"; import { KeyPair } from "utils/secp256k1";
export class HDNode { export class HDNode {
private readonly keyPair; private readonly keyPair;
@ -489,7 +489,7 @@ declare module "utils/random-bytes" {
export function randomBytes(length: number): Uint8Array; export function randomBytes(length: number): Uint8Array;
} }
declare module "wallet/signing-key" { declare module "wallet/signing-key" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
import { HDNode } from "wallet/hdnode"; import { HDNode } from "wallet/hdnode";
import { Signature } from "utils/secp256k1"; import { Signature } from "utils/secp256k1";
export class SigningKey { export class SigningKey {
@ -506,7 +506,7 @@ declare module "wallet/signing-key" {
export function computeAddress(key: string): string; export function computeAddress(key: string): string;
} }
declare module "wallet/secret-storage" { declare module "wallet/secret-storage" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
import { SigningKey } from "wallet/signing-key"; import { SigningKey } from "wallet/signing-key";
export interface ProgressCallback { export interface ProgressCallback {
(percent: number): void; (percent: number): void;
@ -523,7 +523,7 @@ declare module "wallet/wallet" {
import { SigningKey } from "wallet/signing-key"; import { SigningKey } from "wallet/signing-key";
import { BlockTag, Provider, TransactionRequest, TransactionResponse } from "providers/provider"; import { BlockTag, Provider, TransactionRequest, TransactionResponse } from "providers/provider";
import { BigNumber, BigNumberish } from "utils/bignumber"; import { BigNumber, BigNumberish } from "utils/bignumber";
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
import { UnsignedTransaction } from "utils/transaction"; import { UnsignedTransaction } from "utils/transaction";
export interface Signer { export interface Signer {
address?: string; address?: string;
@ -597,7 +597,7 @@ declare module "contracts/index" {
export { Contract, Interface }; export { Contract, Interface };
} }
declare module "utils/base64" { declare module "utils/base64" {
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
export function decode(textData: string): Uint8Array; export function decode(textData: string): Uint8Array;
export function encode(data: Arrayish): string; export function encode(data: Arrayish): string;
} }
@ -635,7 +635,7 @@ declare module "providers/json-rpc-provider" {
import { Network } from "providers/networks"; import { Network } from "providers/networks";
import { BlockTag, Provider, TransactionRequest } from "providers/provider"; import { BlockTag, Provider, TransactionRequest } from "providers/provider";
import { BigNumber } from "utils/bignumber"; import { BigNumber } from "utils/bignumber";
import { Arrayish } from "utils/convert"; import { Arrayish } from "utils/bytes";
import { ConnectionInfo } from "utils/web"; import { ConnectionInfo } from "utils/web";
export function hexlifyTransaction(transaction: TransactionRequest): any; export function hexlifyTransaction(transaction: TransactionRequest): any;
export class JsonRpcSigner { export class JsonRpcSigner {
@ -720,7 +720,7 @@ declare module "utils/index" {
import { AbiCoder, parseSignature } from "utils/abi-coder"; import { AbiCoder, parseSignature } from "utils/abi-coder";
import * as base64 from "utils/base64"; import * as base64 from "utils/base64";
import * as bigNumber from "utils/bignumber"; import * as bigNumber from "utils/bignumber";
import * as convert from "utils/convert"; import * as bytes from "utils/bytes";
import { id } from "utils/id"; import { id } from "utils/id";
import { keccak256 } from "utils/keccak256"; import { keccak256 } from "utils/keccak256";
import { namehash } from "utils/namehash"; import { namehash } from "utils/namehash";
@ -739,14 +739,14 @@ declare module "utils/index" {
RLP: typeof RLP; RLP: typeof RLP;
fetchJson: typeof fetchJson; fetchJson: typeof fetchJson;
etherSymbol: string; etherSymbol: string;
arrayify: typeof convert.arrayify; arrayify: typeof bytes.arrayify;
concat: typeof convert.concat; concat: typeof bytes.concat;
padZeros: typeof convert.padZeros; padZeros: typeof bytes.padZeros;
stripZeros: typeof convert.stripZeros; stripZeros: typeof bytes.stripZeros;
base64: typeof base64; base64: typeof base64;
bigNumberify: typeof bigNumber.bigNumberify; bigNumberify: typeof bigNumber.bigNumberify;
BigNumber: typeof bigNumber.BigNumber; BigNumber: typeof bigNumber.BigNumber;
hexlify: typeof convert.hexlify; hexlify: typeof bytes.hexlify;
toUtf8Bytes: typeof utf8.toUtf8Bytes; toUtf8Bytes: typeof utf8.toUtf8Bytes;
toUtf8String: typeof utf8.toUtf8String; toUtf8String: typeof utf8.toUtf8String;
namehash: typeof namehash; namehash: typeof namehash;
@ -764,7 +764,7 @@ declare module "utils/index" {
solidityPack: typeof solidity.pack; solidityPack: typeof solidity.pack;
solidityKeccak256: typeof solidity.keccak256; solidityKeccak256: typeof solidity.keccak256;
soliditySha256: typeof solidity.sha256; soliditySha256: typeof solidity.sha256;
splitSignature: typeof convert.splitSignature; splitSignature: typeof bytes.splitSignature;
parseTransaction: typeof parseTransaction; parseTransaction: typeof parseTransaction;
}; };
export default _default; export default _default;

450
dist/ethers.js vendored

File diff suppressed because it is too large Load Diff

2
dist/ethers.min.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
import { arrayify } from '../src.ts/utils/convert'; import { arrayify } from '../src.ts/utils/bytes';
module.exports = { module.exports = {
decode: function(textData) { decode: function(textData) {

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
import { arrayify } from '../src.ts/utils/convert'; import { arrayify } from '../src.ts/utils/bytes';
import { defineReadOnly } from '../src.ts/utils/properties'; import { defineReadOnly } from '../src.ts/utils/properties';
let crypto: any = global['crypto'] || global['msCrypto']; let crypto: any = global['crypto'] || global['msCrypto'];

View File

@ -6,7 +6,7 @@ import { Provider, TransactionResponse } from '../providers/provider';
import { Signer } from '../wallet/wallet'; import { Signer } from '../wallet/wallet';
import { getContractAddress } from '../utils/address'; import { getContractAddress } from '../utils/address';
import { isHexString } from '../utils/convert'; import { isHexString } from '../utils/bytes';
import { ParamType } from '../utils/abi-coder'; import { ParamType } from '../utils/abi-coder';
import { BigNumber, ConstantZero } from '../utils/bignumber'; import { BigNumber, ConstantZero } from '../utils/bignumber';
import { defineReadOnly, resolveProperties } from '../utils/properties'; import { defineReadOnly, resolveProperties } from '../utils/properties';

View File

@ -4,7 +4,7 @@
import { defaultAbiCoder, ParamType, parseSignature } from '../utils/abi-coder'; import { defaultAbiCoder, ParamType, parseSignature } from '../utils/abi-coder';
import { BigNumber, bigNumberify, BigNumberish } from '../utils/bignumber'; import { BigNumber, bigNumberify, BigNumberish } from '../utils/bignumber';
import { arrayify, concat, isHexString } from '../utils/convert'; import { arrayify, concat, isHexString } from '../utils/bytes';
import { keccak256 } from '../utils/keccak256'; import { keccak256 } from '../utils/keccak256';
import { toUtf8Bytes } from '../utils/utf8'; import { toUtf8Bytes } from '../utils/utf8';
import { defineReadOnly, defineFrozen } from '../utils/properties'; import { defineReadOnly, defineFrozen } from '../utils/properties';

View File

@ -2,7 +2,7 @@
import { checkTransactionResponse, Provider, TransactionRequest } from './provider'; import { checkTransactionResponse, Provider, TransactionRequest } from './provider';
import { Network } from './networks'; import { Network } from './networks';
import { hexlify, hexStripZeros } from '../utils/convert'; import { hexlify, hexStripZeros } from '../utils/bytes';
import { fetchJson } from '../utils/web'; import { fetchJson } from '../utils/web';
import * as errors from '../utils/errors'; import * as errors from '../utils/errors';

View File

@ -7,7 +7,7 @@ import { BlockTag, Provider, TransactionRequest, TransactionResponse } from './p
import { getAddress } from '../utils/address'; import { getAddress } from '../utils/address';
import { BigNumber } from '../utils/bignumber'; import { BigNumber } from '../utils/bignumber';
import { Arrayish, hexlify, hexStripZeros } from '../utils/convert'; import { Arrayish, hexlify, hexStripZeros } from '../utils/bytes';
import { toUtf8Bytes } from '../utils/utf8'; import { toUtf8Bytes } from '../utils/utf8';
import { ConnectionInfo, fetchJson } from '../utils/web'; import { ConnectionInfo, fetchJson } from '../utils/web';

View File

@ -4,7 +4,7 @@
import { getAddress, getContractAddress } from '../utils/address'; import { getAddress, getContractAddress } from '../utils/address';
import { BigNumber, bigNumberify, BigNumberish } from '../utils/bignumber'; import { BigNumber, bigNumberify, BigNumberish } from '../utils/bignumber';
import { Arrayish, hexDataLength, hexDataSlice, hexlify, hexStripZeros, isHexString, stripZeros } from '../utils/convert'; import { Arrayish, hexDataLength, hexDataSlice, hexlify, hexStripZeros, isHexString, stripZeros } from '../utils/bytes';
import { toUtf8String } from '../utils/utf8'; import { toUtf8String } from '../utils/utf8';
import { decode as rlpDecode, encode as rlpEncode } from '../utils/rlp'; import { decode as rlpDecode, encode as rlpEncode } from '../utils/rlp';
import { namehash } from '../utils/namehash'; import { namehash } from '../utils/namehash';

View File

@ -4,7 +4,7 @@
import { getAddress } from './address'; import { getAddress } from './address';
import { bigNumberify, BigNumberish } from './bignumber'; import { bigNumberify, BigNumberish } from './bignumber';
import { arrayify, Arrayish, concat, hexlify, padZeros } from './convert'; import { arrayify, Arrayish, concat, hexlify, padZeros } from './bytes';
import { toUtf8Bytes, toUtf8String } from './utf8'; import { toUtf8Bytes, toUtf8String } from './utf8';
import { defineReadOnly, jsonCopy } from './properties'; import { defineReadOnly, jsonCopy } from './properties';

View File

@ -4,7 +4,7 @@
import BN = require('bn.js'); import BN = require('bn.js');
import { BigNumber } from './bignumber'; import { BigNumber } from './bignumber';
import { arrayify, Arrayish, stripZeros, hexlify } from './convert'; import { arrayify, Arrayish, stripZeros, hexlify } from './bytes';
import { keccak256 } from './keccak256'; import { keccak256 } from './keccak256';
import { encode } from './rlp'; import { encode } from './rlp';

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
import { arrayify, Arrayish } from './convert'; import { arrayify, Arrayish } from './bytes';
declare class Buffer implements ArrayLike<number> { declare class Buffer implements ArrayLike<number> {
constructor(data: any, encoding?: string); constructor(data: any, encoding?: string);

View File

@ -10,7 +10,7 @@
import _BN from 'bn.js'; import _BN from 'bn.js';
import { Arrayish, hexlify, isArrayish, isHexString } from './convert'; import { Arrayish, hexlify, isArrayish, isHexString } from './bytes';
import { defineReadOnly } from './properties'; import { defineReadOnly } from './properties';
import * as errors from '../utils/errors'; import * as errors from '../utils/errors';

View File

@ -2,7 +2,7 @@
import * as _hash from 'hash.js'; import * as _hash from 'hash.js';
import { arrayify, Arrayish } from './convert'; import { arrayify, Arrayish } from './bytes';
interface HashFunc { interface HashFunc {
(): HashFunc; (): HashFunc;

View File

@ -7,7 +7,7 @@ import { getAddress, getContractAddress, getIcapAddress } from './address';
import { AbiCoder, defaultAbiCoder, parseSignature } from './abi-coder'; import { AbiCoder, defaultAbiCoder, parseSignature } from './abi-coder';
import * as base64 from './base64'; import * as base64 from './base64';
import * as bigNumber from './bignumber'; import * as bigNumber from './bignumber';
import * as convert from './convert'; import * as bytes from './bytes';
import { id } from './id'; import { id } from './id';
import { keccak256 } from './keccak256'; import { keccak256 } from './keccak256';
import { namehash } from './namehash'; import { namehash } from './namehash';
@ -38,18 +38,18 @@ export default {
// NFKC (composed) // NFKC (composed)
etherSymbol: '\u039e', etherSymbol: '\u039e',
arrayify: convert.arrayify, arrayify: bytes.arrayify,
concat: convert.concat, concat: bytes.concat,
padZeros: convert.padZeros, padZeros: bytes.padZeros,
stripZeros: convert.stripZeros, stripZeros: bytes.stripZeros,
base64: base64, base64: base64,
bigNumberify: bigNumber.bigNumberify, bigNumberify: bigNumber.bigNumberify,
BigNumber: bigNumber.BigNumber, BigNumber: bigNumber.BigNumber,
hexlify: convert.hexlify, hexlify: bytes.hexlify,
toUtf8Bytes: utf8.toUtf8Bytes, toUtf8Bytes: utf8.toUtf8Bytes,
toUtf8String: utf8.toUtf8String, toUtf8String: utf8.toUtf8String,
@ -76,7 +76,7 @@ export default {
solidityKeccak256: solidity.keccak256, solidityKeccak256: solidity.keccak256,
soliditySha256: solidity.sha256, soliditySha256: solidity.sha256,
splitSignature: convert.splitSignature, splitSignature: bytes.splitSignature,
parseTransaction: parseTransaction parseTransaction: parseTransaction
} }

View File

@ -2,7 +2,7 @@
import sha3 = require('js-sha3'); import sha3 = require('js-sha3');
import { arrayify, Arrayish } from './convert'; import { arrayify, Arrayish } from './bytes';
export function keccak256(data: Arrayish): string { export function keccak256(data: Arrayish): string {
return '0x' + sha3.keccak_256(arrayify(data)); return '0x' + sha3.keccak_256(arrayify(data));

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
import { concat, hexlify } from './convert'; import { concat, hexlify } from './bytes';
import { toUtf8Bytes } from './utf8'; import { toUtf8Bytes } from './utf8';
import { keccak256 } from './keccak256'; import { keccak256 } from './keccak256';

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
import { arrayify, Arrayish } from './convert'; import { arrayify, Arrayish } from './bytes';
import { HmacFunc } from './hmac'; import { HmacFunc } from './hmac';
export interface CreateHmacFunc { export interface CreateHmacFunc {

View File

@ -1,11 +1,9 @@
'use strict'; 'use strict';
import { arrayify } from './convert'; import { arrayify } from './bytes';
import { randomBytes as _randomBytes } from 'crypto'; import { randomBytes as _randomBytes } from 'crypto';
//function _randomBytes(length) { return "0x00"; }
export function randomBytes(length: number): Uint8Array { export function randomBytes(length: number): Uint8Array {
return arrayify(_randomBytes(length)); return arrayify(_randomBytes(length));
} }

View File

@ -1,7 +1,7 @@
//See: https://github.com/ethereum/wiki/wiki/RLP //See: https://github.com/ethereum/wiki/wiki/RLP
import { arrayify, Arrayish, hexlify } from './convert'; import { arrayify, Arrayish, hexlify } from './bytes';
function arrayifyInteger(value: number): Array<number> { function arrayifyInteger(value: number): Array<number> {
var result = []; var result = [];

View File

@ -1,11 +1,11 @@
'use strict'; 'use strict';
import { getAddress } from './address'; import { getAddress } from './address';
import { arrayify, Arrayish, hexlify } from '../utils/convert'; import { arrayify, Arrayish, hexlify } from './bytes';
import { keccak256 } from './keccak256'; import { keccak256 } from './keccak256';
import { defineReadOnly } from '../utils/properties'; import { defineReadOnly } from './properties';
import * as errors from '../utils/errors'; import * as errors from './errors';
interface _BN { interface _BN {
toString(radix: number): string; toString(radix: number): string;

View File

@ -2,7 +2,7 @@
import * as _hash from 'hash.js'; import * as _hash from 'hash.js';
import { arrayify, Arrayish } from './convert'; import { arrayify, Arrayish } from './bytes';
interface HashFunc { interface HashFunc {

View File

@ -1,7 +1,7 @@
'use strict'; 'use strict';
import { bigNumberify } from './bignumber'; import { bigNumberify } from './bignumber';
import { arrayify, concat, hexlify, padZeros} from './convert'; import { arrayify, concat, hexlify, padZeros} from './bytes';
import { toUtf8Bytes } from './utf8'; import { toUtf8Bytes } from './utf8';
import { keccak256 as hashKeccak256 } from './keccak256'; import { keccak256 as hashKeccak256 } from './keccak256';

View File

@ -1,7 +1,7 @@
import { getAddress } from './address'; import { getAddress } from './address';
import { BigNumber, bigNumberify, BigNumberish,ConstantZero } from './bignumber'; import { BigNumber, bigNumberify, BigNumberish,ConstantZero } from './bignumber';
import { arrayify, Arrayish, hexlify, stripZeros, } from './convert'; import { arrayify, Arrayish, hexlify, stripZeros, } from './bytes';
import { keccak256 } from './keccak256'; import { keccak256 } from './keccak256';
import { recoverAddress, Signature } from './secp256k1'; import { recoverAddress, Signature } from './secp256k1';
import * as RLP from './rlp'; import * as RLP from './rlp';

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
import { arrayify, Arrayish } from './convert'; import { arrayify, Arrayish } from './bytes';
export enum UnicodeNormalizationForm { export enum UnicodeNormalizationForm {
current = '', current = '',

View File

@ -5,7 +5,7 @@
import { getWord, getWordIndex } from './words'; import { getWord, getWordIndex } from './words';
import { arrayify, Arrayish, hexlify } from '../utils/convert'; import { arrayify, Arrayish, hexlify } from '../utils/bytes';
import { bigNumberify } from '../utils/bignumber'; import { bigNumberify } from '../utils/bignumber';
import { toUtf8Bytes, UnicodeNormalizationForm } from '../utils/utf8'; import { toUtf8Bytes, UnicodeNormalizationForm } from '../utils/utf8';
import { pbkdf2 } from '../utils/pbkdf2'; import { pbkdf2 } from '../utils/pbkdf2';

View File

@ -5,7 +5,7 @@ import scrypt = require('scrypt-js');
import uuid = require('uuid'); import uuid = require('uuid');
import { getAddress } from '../utils/address'; import { getAddress } from '../utils/address';
import { arrayify, Arrayish, concat, hexlify } from '../utils/convert'; import { arrayify, Arrayish, concat, hexlify } from '../utils/bytes';
import * as hmac from '../utils/hmac'; import * as hmac from '../utils/hmac';
import { pbkdf2 } from '../utils/pbkdf2'; import { pbkdf2 } from '../utils/pbkdf2';

View File

@ -7,7 +7,7 @@
*/ */
import { getAddress } from '../utils/address'; import { getAddress } from '../utils/address';
import { arrayify, Arrayish, hexlify } from '../utils/convert'; import { arrayify, Arrayish, hexlify } from '../utils/bytes';
import { HDNode } from './hdnode'; import { HDNode } from './hdnode';
import { keccak256 } from '../utils/keccak256'; import { keccak256 } from '../utils/keccak256';
import { defineReadOnly } from '../utils/properties'; import { defineReadOnly } from '../utils/properties';

View File

@ -10,7 +10,7 @@ import { recoverAddress, SigningKey } from './signing-key';
import { BlockTag, Provider, TransactionRequest, TransactionResponse } from '../providers/provider'; import { BlockTag, Provider, TransactionRequest, TransactionResponse } from '../providers/provider';
import { BigNumber, BigNumberish } from '../utils/bignumber'; import { BigNumber, BigNumberish } from '../utils/bignumber';
import { arrayify, Arrayish, concat, hexlify, hexZeroPad } from '../utils/convert'; import { arrayify, Arrayish, concat, hexlify, hexZeroPad } from '../utils/bytes';
import { keccak256 } from '../utils/keccak256'; import { keccak256 } from '../utils/keccak256';
import { defineReadOnly, resolveProperties, shallowCopy } from '../utils/properties'; import { defineReadOnly, resolveProperties, shallowCopy } from '../utils/properties';
import { randomBytes } from '../utils/random-bytes'; import { randomBytes } from '../utils/random-bytes';

View File

@ -9,7 +9,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var interface_1 = require("./interface"); var interface_1 = require("./interface");
var address_1 = require("../utils/address"); var address_1 = require("../utils/address");
var convert_1 = require("../utils/convert"); var bytes_1 = require("../utils/bytes");
var bignumber_1 = require("../utils/bignumber"); var bignumber_1 = require("../utils/bignumber");
var properties_1 = require("../utils/properties"); var properties_1 = require("../utils/properties");
var errors = __importStar(require("../utils/errors")); var errors = __importStar(require("../utils/errors"));
@ -318,7 +318,7 @@ var Contract = /** @class */ (function () {
if (this.signer == null) { if (this.signer == null) {
throw new Error('missing signer'); // @TODO: errors.throwError throw new Error('missing signer'); // @TODO: errors.throwError
} }
if (!convert_1.isHexString(bytecode)) { if (!bytes_1.isHexString(bytecode)) {
errors.throwError('bytecode must be a valid hex string', errors.INVALID_ARGUMENT, { arg: 'bytecode', value: bytecode }); errors.throwError('bytecode must be a valid hex string', errors.INVALID_ARGUMENT, { arg: 'bytecode', value: bytecode });
} }
if ((bytecode.length % 2) !== 0) { if ((bytecode.length % 2) !== 0) {

View File

@ -20,7 +20,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
// See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI // See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI
var abi_coder_1 = require("../utils/abi-coder"); var abi_coder_1 = require("../utils/abi-coder");
var bignumber_1 = require("../utils/bignumber"); var bignumber_1 = require("../utils/bignumber");
var convert_1 = require("../utils/convert"); var bytes_1 = require("../utils/bytes");
var keccak256_1 = require("../utils/keccak256"); var keccak256_1 = require("../utils/keccak256");
var utf8_1 = require("../utils/utf8"); var utf8_1 = require("../utils/utf8");
var properties_1 = require("../utils/properties"); var properties_1 = require("../utils/properties");
@ -82,7 +82,7 @@ var DeployDescription = /** @class */ (function (_super) {
return _super !== null && _super.apply(this, arguments) || this; return _super !== null && _super.apply(this, arguments) || this;
} }
DeployDescription.prototype.encode = function (bytecode, params) { DeployDescription.prototype.encode = function (bytecode, params) {
if (!convert_1.isHexString(bytecode)) { if (!bytes_1.isHexString(bytecode)) {
errors.throwError('invalid contract bytecode', errors.INVALID_ARGUMENT, { errors.throwError('invalid contract bytecode', errors.INVALID_ARGUMENT, {
arg: 'bytecode', arg: 'bytecode',
type: typeof (bytecode), type: typeof (bytecode),
@ -151,7 +151,7 @@ var FunctionDescription = /** @class */ (function (_super) {
}; };
FunctionDescription.prototype.decode = function (data) { FunctionDescription.prototype.decode = function (data) {
try { try {
return abi_coder_1.defaultAbiCoder.decode(this.outputs, convert_1.arrayify(data)); return abi_coder_1.defaultAbiCoder.decode(this.outputs, bytes_1.arrayify(data));
} }
catch (error) { catch (error) {
errors.throwError('invalid data for function output', errors.INVALID_ARGUMENT, { errors.throwError('invalid data for function output', errors.INVALID_ARGUMENT, {
@ -197,9 +197,9 @@ var EventDescription = /** @class */ (function (_super) {
} }
}); });
if (topics != null) { if (topics != null) {
var resultIndexed = abi_coder_1.defaultAbiCoder.decode(inputIndexed, convert_1.concat(topics)); var resultIndexed = abi_coder_1.defaultAbiCoder.decode(inputIndexed, bytes_1.concat(topics));
} }
var resultNonIndexed = abi_coder_1.defaultAbiCoder.decode(inputNonIndexed, convert_1.arrayify(data)); var resultNonIndexed = abi_coder_1.defaultAbiCoder.decode(inputNonIndexed, bytes_1.arrayify(data));
var result = new Result(); var result = new Result();
var nonIndexedIndex = 0, indexedIndex = 0; var nonIndexedIndex = 0, indexedIndex = 0;
this.inputs.forEach(function (input, index) { this.inputs.forEach(function (input, index) {

View File

@ -18,7 +18,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var provider_1 = require("./provider"); var provider_1 = require("./provider");
var convert_1 = require("../utils/convert"); var bytes_1 = require("../utils/bytes");
var web_1 = require("../utils/web"); var web_1 = require("../utils/web");
var errors = __importStar(require("../utils/errors")); var errors = __importStar(require("../utils/errors"));
// The transaction has already been sanitized by the calls in Provider // The transaction has already been sanitized by the calls in Provider
@ -28,9 +28,9 @@ function getTransactionString(transaction) {
if (transaction[key] == null) { if (transaction[key] == null) {
continue; continue;
} }
var value = convert_1.hexlify(transaction[key]); var value = bytes_1.hexlify(transaction[key]);
if ({ gasLimit: true, gasPrice: true, nonce: true, value: true }[key]) { if ({ gasLimit: true, gasPrice: true, nonce: true, value: true }[key]) {
value = convert_1.hexStripZeros(value); value = bytes_1.hexStripZeros(value);
} }
result.push(key + '=' + value); result.push(key + '=' + value);
} }

View File

@ -1,7 +1,7 @@
import { Network } from './networks'; import { Network } from './networks';
import { BlockTag, Provider, TransactionRequest } from './provider'; import { BlockTag, Provider, TransactionRequest } from './provider';
import { BigNumber } from '../utils/bignumber'; import { BigNumber } from '../utils/bignumber';
import { Arrayish } from '../utils/convert'; import { Arrayish } from '../utils/bytes';
import { ConnectionInfo } from '../utils/web'; import { ConnectionInfo } from '../utils/web';
export declare function hexlifyTransaction(transaction: TransactionRequest): any; export declare function hexlifyTransaction(transaction: TransactionRequest): any;
export declare class JsonRpcSigner { export declare class JsonRpcSigner {

View File

@ -21,7 +21,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
var networks_1 = require("./networks"); var networks_1 = require("./networks");
var provider_1 = require("./provider"); var provider_1 = require("./provider");
var address_1 = require("../utils/address"); var address_1 = require("../utils/address");
var convert_1 = require("../utils/convert"); var bytes_1 = require("../utils/bytes");
var utf8_1 = require("../utils/utf8"); var utf8_1 = require("../utils/utf8");
var web_1 = require("../utils/web"); var web_1 = require("../utils/web");
var errors = __importStar(require("../utils/errors")); var errors = __importStar(require("../utils/errors"));
@ -53,7 +53,7 @@ function hexlifyTransaction(transaction) {
if (transaction[key] == null) { if (transaction[key] == null) {
return; return;
} }
var value = convert_1.hexStripZeros(convert_1.hexlify(transaction[key])); var value = bytes_1.hexStripZeros(bytes_1.hexlify(transaction[key]));
if (key === 'gasLimit') { if (key === 'gasLimit') {
key = 'gas'; key = 'gas';
} }
@ -63,7 +63,7 @@ function hexlifyTransaction(transaction) {
if (transaction[key] == null) { if (transaction[key] == null) {
return; return;
} }
result[key] = convert_1.hexlify(transaction[key]); result[key] = bytes_1.hexlify(transaction[key]);
}); });
return result; return result;
} }
@ -150,7 +150,7 @@ var JsonRpcSigner = /** @class */ (function () {
var data = ((typeof (message) === 'string') ? utf8_1.toUtf8Bytes(message) : message); var data = ((typeof (message) === 'string') ? utf8_1.toUtf8Bytes(message) : message);
return this.getAddress().then(function (address) { return this.getAddress().then(function (address) {
// https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign
return _this.provider.send('eth_sign', [address.toLowerCase(), convert_1.hexlify(data)]); return _this.provider.send('eth_sign', [address.toLowerCase(), bytes_1.hexlify(data)]);
}); });
}; };
JsonRpcSigner.prototype.unlock = function (password) { JsonRpcSigner.prototype.unlock = function (password) {

View File

@ -1,5 +1,5 @@
import { BigNumber, BigNumberish } from '../utils/bignumber'; import { BigNumber, BigNumberish } from '../utils/bignumber';
import { Arrayish } from '../utils/convert'; import { Arrayish } from '../utils/bytes';
import { Network } from './networks'; import { Network } from './networks';
import { Transaction } from '../utils/transaction'; import { Transaction } from '../utils/transaction';
export declare type BlockTag = string | number; export declare type BlockTag = string | number;

View File

@ -10,7 +10,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
//import inherits = require('inherits'); //import inherits = require('inherits');
var address_1 = require("../utils/address"); var address_1 = require("../utils/address");
var bignumber_1 = require("../utils/bignumber"); var bignumber_1 = require("../utils/bignumber");
var convert_1 = require("../utils/convert"); var bytes_1 = require("../utils/bytes");
var utf8_1 = require("../utils/utf8"); var utf8_1 = require("../utils/utf8");
var rlp_1 = require("../utils/rlp"); var rlp_1 = require("../utils/rlp");
var namehash_1 = require("../utils/namehash"); var namehash_1 = require("../utils/namehash");
@ -76,7 +76,7 @@ function arrayOf(check) {
}); });
} }
function checkHash(hash) { function checkHash(hash) {
if (typeof (hash) === 'string' && convert_1.hexDataLength(hash) === 32) { if (typeof (hash) === 'string' && bytes_1.hexDataLength(hash) === 32) {
return hash; return hash;
} }
errors.throwError('invalid hash', errors.INVALID_ARGUMENT, { arg: 'hash', value: hash }); errors.throwError('invalid hash', errors.INVALID_ARGUMENT, { arg: 'hash', value: hash });
@ -109,7 +109,7 @@ function checkBoolean(value) {
throw new Error('invaid boolean - ' + value); throw new Error('invaid boolean - ' + value);
} }
function checkUint256(uint256) { function checkUint256(uint256) {
if (!convert_1.isHexString(uint256)) { if (!bytes_1.isHexString(uint256)) {
throw new Error('invalid uint256'); throw new Error('invalid uint256');
} }
while (uint256.length < 66) { while (uint256.length < 66) {
@ -134,10 +134,10 @@ function checkBlockTag(blockTag) {
return blockTag; return blockTag;
} }
if (typeof (blockTag) === 'number') { if (typeof (blockTag) === 'number') {
return convert_1.hexStripZeros(convert_1.hexlify(blockTag)); return bytes_1.hexStripZeros(bytes_1.hexlify(blockTag));
} }
if (convert_1.isHexString(blockTag)) { if (bytes_1.isHexString(blockTag)) {
return convert_1.hexStripZeros(blockTag); return bytes_1.hexStripZeros(blockTag);
} }
throw new Error('invalid blockTag'); throw new Error('invalid blockTag');
} }
@ -146,12 +146,12 @@ var formatBlock = {
parentHash: checkHash, parentHash: checkHash,
number: checkNumber, number: checkNumber,
timestamp: checkNumber, timestamp: checkNumber,
nonce: allowNull(convert_1.hexlify), nonce: allowNull(bytes_1.hexlify),
difficulty: checkDifficulty, difficulty: checkDifficulty,
gasLimit: bignumber_1.bigNumberify, gasLimit: bignumber_1.bigNumberify,
gasUsed: bignumber_1.bigNumberify, gasUsed: bignumber_1.bigNumberify,
miner: address_1.getAddress, miner: address_1.getAddress,
extraData: convert_1.hexlify, extraData: bytes_1.hexlify,
//transactions: allowNull(arrayOf(checkTransaction)), //transactions: allowNull(arrayOf(checkTransaction)),
transactions: allowNull(arrayOf(checkHash)), transactions: allowNull(arrayOf(checkHash)),
}; };
@ -172,12 +172,12 @@ var formatTransaction = {
to: allowNull(address_1.getAddress, null), to: allowNull(address_1.getAddress, null),
value: bignumber_1.bigNumberify, value: bignumber_1.bigNumberify,
nonce: checkNumber, nonce: checkNumber,
data: convert_1.hexlify, data: bytes_1.hexlify,
r: allowNull(checkUint256), r: allowNull(checkUint256),
s: allowNull(checkUint256), s: allowNull(checkUint256),
v: allowNull(checkNumber), v: allowNull(checkNumber),
creates: allowNull(address_1.getAddress, null), creates: allowNull(address_1.getAddress, null),
raw: allowNull(convert_1.hexlify), raw: allowNull(bytes_1.hexlify),
}; };
function checkTransactionResponse(transaction) { function checkTransactionResponse(transaction) {
// Rename gas to gasLimit // Rename gas to gasLimit
@ -201,22 +201,22 @@ function checkTransactionResponse(transaction) {
// Very loose providers (e.g. TestRPC) don't provide a signature or raw // Very loose providers (e.g. TestRPC) don't provide a signature or raw
if (transaction.v && transaction.r && transaction.s) { if (transaction.v && transaction.r && transaction.s) {
var raw = [ var raw = [
convert_1.stripZeros(convert_1.hexlify(transaction.nonce)), bytes_1.stripZeros(bytes_1.hexlify(transaction.nonce)),
convert_1.stripZeros(convert_1.hexlify(transaction.gasPrice)), bytes_1.stripZeros(bytes_1.hexlify(transaction.gasPrice)),
convert_1.stripZeros(convert_1.hexlify(transaction.gasLimit)), bytes_1.stripZeros(bytes_1.hexlify(transaction.gasLimit)),
(transaction.to || "0x"), (transaction.to || "0x"),
convert_1.stripZeros(convert_1.hexlify(transaction.value || '0x')), bytes_1.stripZeros(bytes_1.hexlify(transaction.value || '0x')),
convert_1.hexlify(transaction.data || '0x'), bytes_1.hexlify(transaction.data || '0x'),
convert_1.stripZeros(convert_1.hexlify(transaction.v || '0x')), bytes_1.stripZeros(bytes_1.hexlify(transaction.v || '0x')),
convert_1.stripZeros(convert_1.hexlify(transaction.r)), bytes_1.stripZeros(bytes_1.hexlify(transaction.r)),
convert_1.stripZeros(convert_1.hexlify(transaction.s)), bytes_1.stripZeros(bytes_1.hexlify(transaction.s)),
]; ];
transaction.raw = rlp_1.encode(raw); transaction.raw = rlp_1.encode(raw);
} }
} }
var result = check(formatTransaction, transaction); var result = check(formatTransaction, transaction);
var networkId = transaction.networkId; var networkId = transaction.networkId;
if (convert_1.isHexString(networkId)) { if (bytes_1.isHexString(networkId)) {
networkId = bignumber_1.bigNumberify(networkId).toNumber(); networkId = bignumber_1.bigNumberify(networkId).toNumber();
} }
if (typeof (networkId) !== 'number' && result.v != null) { if (typeof (networkId) !== 'number' && result.v != null) {
@ -244,7 +244,7 @@ var formatTransactionRequest = {
gasPrice: allowNull(bignumber_1.bigNumberify), gasPrice: allowNull(bignumber_1.bigNumberify),
to: allowNull(address_1.getAddress), to: allowNull(address_1.getAddress),
value: allowNull(bignumber_1.bigNumberify), value: allowNull(bignumber_1.bigNumberify),
data: allowNull(convert_1.hexlify), data: allowNull(bytes_1.hexlify),
}; };
function checkTransactionRequest(transaction) { function checkTransactionRequest(transaction) {
return check(formatTransactionRequest, transaction); return check(formatTransactionRequest, transaction);
@ -256,7 +256,7 @@ var formatTransactionReceiptLog = {
transactionHash: checkHash, transactionHash: checkHash,
address: address_1.getAddress, address: address_1.getAddress,
topics: arrayOf(checkHash), topics: arrayOf(checkHash),
data: convert_1.hexlify, data: bytes_1.hexlify,
logIndex: checkNumber, logIndex: checkNumber,
blockHash: checkHash, blockHash: checkHash,
}; };
@ -268,7 +268,7 @@ var formatTransactionReceipt = {
transactionIndex: checkNumber, transactionIndex: checkNumber,
root: allowNull(checkHash), root: allowNull(checkHash),
gasUsed: bignumber_1.bigNumberify, gasUsed: bignumber_1.bigNumberify,
logsBloom: allowNull(convert_1.hexlify), logsBloom: allowNull(bytes_1.hexlify),
blockHash: checkHash, blockHash: checkHash,
transactionHash: checkHash, transactionHash: checkHash,
logs: arrayOf(checkTransactionReceiptLog), logs: arrayOf(checkTransactionReceiptLog),
@ -316,7 +316,7 @@ var formatLog = {
transactionIndex: checkNumber, transactionIndex: checkNumber,
removed: allowNull(checkBoolean), removed: allowNull(checkBoolean),
address: address_1.getAddress, address: address_1.getAddress,
data: allowFalsish(convert_1.hexlify, '0x'), data: allowFalsish(bytes_1.hexlify, '0x'),
topics: arrayOf(checkHash), topics: arrayOf(checkHash),
transactionHash: checkHash, transactionHash: checkHash,
logIndex: checkNumber, logIndex: checkNumber,
@ -372,7 +372,7 @@ function getEventString(object) {
else if (object === 'pending') { else if (object === 'pending') {
return 'pending'; return 'pending';
} }
else if (convert_1.hexDataLength(object) === 32) { else if (bytes_1.hexDataLength(object) === 32) {
return 'tx:' + object; return 'tx:' + object;
} }
else if (Array.isArray(object)) { else if (Array.isArray(object)) {
@ -673,7 +673,7 @@ var Provider = /** @class */ (function () {
return _this.resolveName(addressOrName).then(function (address) { return _this.resolveName(addressOrName).then(function (address) {
var params = { address: address, blockTag: checkBlockTag(blockTag) }; var params = { address: address, blockTag: checkBlockTag(blockTag) };
return _this.perform('getCode', params).then(function (result) { return _this.perform('getCode', params).then(function (result) {
return convert_1.hexlify(result); return bytes_1.hexlify(result);
}); });
}); });
}); });
@ -688,10 +688,10 @@ var Provider = /** @class */ (function () {
var params = { var params = {
address: address, address: address,
blockTag: checkBlockTag(blockTag), blockTag: checkBlockTag(blockTag),
position: convert_1.hexStripZeros(convert_1.hexlify(position)), position: bytes_1.hexStripZeros(bytes_1.hexlify(position)),
}; };
return _this.perform('getStorageAt', params).then(function (result) { return _this.perform('getStorageAt', params).then(function (result) {
return convert_1.hexlify(result); return bytes_1.hexlify(result);
}); });
}); });
}); });
@ -702,9 +702,9 @@ var Provider = /** @class */ (function () {
return this.ready.then(function () { return this.ready.then(function () {
return properties_1.resolveProperties({ signedTransaction: signedTransaction }).then(function (_a) { return properties_1.resolveProperties({ signedTransaction: signedTransaction }).then(function (_a) {
var signedTransaction = _a.signedTransaction; var signedTransaction = _a.signedTransaction;
var params = { signedTransaction: convert_1.hexlify(signedTransaction) }; var params = { signedTransaction: bytes_1.hexlify(signedTransaction) };
return _this.perform('sendTransaction', params).then(function (hash) { return _this.perform('sendTransaction', params).then(function (hash) {
if (convert_1.hexDataLength(hash) !== 32) { if (bytes_1.hexDataLength(hash) !== 32) {
throw new Error('invalid response - sendTransaction'); throw new Error('invalid response - sendTransaction');
} }
// A signed transaction always has a from (and we add wait below) // A signed transaction always has a from (and we add wait below)
@ -729,7 +729,7 @@ var Provider = /** @class */ (function () {
return _this._resolveNames(transaction, ['to', 'from']).then(function (transaction) { return _this._resolveNames(transaction, ['to', 'from']).then(function (transaction) {
var params = { transaction: checkTransactionRequest(transaction) }; var params = { transaction: checkTransactionRequest(transaction) };
return _this.perform('call', params).then(function (result) { return _this.perform('call', params).then(function (result) {
return convert_1.hexlify(result); return bytes_1.hexlify(result);
}); });
}); });
}); });
@ -754,8 +754,8 @@ var Provider = /** @class */ (function () {
return properties_1.resolveProperties({ blockHashOrBlockTag: blockHashOrBlockTag }).then(function (_a) { return properties_1.resolveProperties({ blockHashOrBlockTag: blockHashOrBlockTag }).then(function (_a) {
var blockHashOrBlockTag = _a.blockHashOrBlockTag; var blockHashOrBlockTag = _a.blockHashOrBlockTag;
try { try {
var blockHash = convert_1.hexlify(blockHashOrBlockTag); var blockHash = bytes_1.hexlify(blockHashOrBlockTag);
if (convert_1.hexDataLength(blockHash) === 32) { if (bytes_1.hexDataLength(blockHash) === 32) {
return stallPromise(function () { return stallPromise(function () {
return (_this._emitted['b:' + blockHash.toLowerCase()] == null); return (_this._emitted['b:' + blockHash.toLowerCase()] == null);
}, function () { }, function () {
@ -772,7 +772,7 @@ var Provider = /** @class */ (function () {
try { try {
var blockTag = checkBlockTag(blockHashOrBlockTag); var blockTag = checkBlockTag(blockHashOrBlockTag);
return stallPromise(function () { return stallPromise(function () {
if (convert_1.isHexString(blockTag)) { if (bytes_1.isHexString(blockTag)) {
var blockNumber = parseInt(blockTag.substring(2), 16); var blockNumber = parseInt(blockTag.substring(2), 16);
return blockNumber > _this._emitted.block; return blockNumber > _this._emitted.block;
} }
@ -877,10 +877,10 @@ var Provider = /** @class */ (function () {
var transaction = { to: network.ensAddress, data: data }; var transaction = { to: network.ensAddress, data: data };
return _this.call(transaction).then(function (data) { return _this.call(transaction).then(function (data) {
// extract the address from the data // extract the address from the data
if (convert_1.hexDataLength(data) !== 32) { if (bytes_1.hexDataLength(data) !== 32) {
return null; return null;
} }
return address_1.getAddress(convert_1.hexDataSlice(data, 12)); return address_1.getAddress(bytes_1.hexDataSlice(data, 12));
}); });
}); });
}; };
@ -907,10 +907,10 @@ var Provider = /** @class */ (function () {
return self.call(transaction); return self.call(transaction);
// extract the address from the data // extract the address from the data
}).then(function (data) { }).then(function (data) {
if (convert_1.hexDataLength(data) !== 32) { if (bytes_1.hexDataLength(data) !== 32) {
return null; return null;
} }
var address = address_1.getAddress(convert_1.hexDataSlice(data, 12)); var address = address_1.getAddress(bytes_1.hexDataSlice(data, 12));
if (address === '0x0000000000000000000000000000000000000000') { if (address === '0x0000000000000000000000000000000000000000') {
return null; return null;
} }

View File

@ -1,4 +1,4 @@
import { Arrayish } from './convert'; import { Arrayish } from './bytes';
export declare type CoerceFunc = (type: string, value: any) => any; export declare type CoerceFunc = (type: string, value: any) => any;
export declare type ParamType = { export declare type ParamType = {
name?: string; name?: string;

View File

@ -20,7 +20,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
// See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI // See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI
var address_1 = require("./address"); var address_1 = require("./address");
var bignumber_1 = require("./bignumber"); var bignumber_1 = require("./bignumber");
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
var utf8_1 = require("./utf8"); var utf8_1 = require("./utf8");
var properties_1 = require("./properties"); var properties_1 = require("./properties");
var errors = __importStar(require("./errors")); var errors = __importStar(require("./errors"));
@ -282,7 +282,7 @@ var CoderNull = /** @class */ (function (_super) {
return _super.call(this, coerceFunc, 'null', '', localName, false) || this; return _super.call(this, coerceFunc, 'null', '', localName, false) || this;
} }
CoderNull.prototype.encode = function (value) { CoderNull.prototype.encode = function (value) {
return convert_1.arrayify([]); return bytes_1.arrayify([]);
}; };
CoderNull.prototype.decode = function (data, offset) { CoderNull.prototype.decode = function (data, offset) {
if (offset > data.length) { if (offset > data.length) {
@ -313,7 +313,7 @@ var CoderNumber = /** @class */ (function (_super) {
if (this.signed) { if (this.signed) {
v = v.fromTwos(this.size * 8).toTwos(256); v = v.fromTwos(this.size * 8).toTwos(256);
} }
return convert_1.padZeros(convert_1.arrayify(v), 32); return bytes_1.padZeros(bytes_1.arrayify(v), 32);
} }
catch (error) { catch (error) {
errors.throwError('invalid number value', errors.INVALID_ARGUMENT, { errors.throwError('invalid number value', errors.INVALID_ARGUMENT, {
@ -329,7 +329,7 @@ var CoderNumber = /** @class */ (function (_super) {
errors.throwError('insufficient data for ' + this.name + ' type', errors.INVALID_ARGUMENT, { errors.throwError('insufficient data for ' + this.name + ' type', errors.INVALID_ARGUMENT, {
arg: this.localName, arg: this.localName,
coderType: this.name, coderType: this.name,
value: convert_1.hexlify(data.slice(offset, offset + 32)) value: bytes_1.hexlify(data.slice(offset, offset + 32))
}); });
} }
var junkLength = 32 - this.size; var junkLength = 32 - this.size;
@ -389,7 +389,7 @@ var CoderFixedBytes = /** @class */ (function (_super) {
CoderFixedBytes.prototype.encode = function (value) { CoderFixedBytes.prototype.encode = function (value) {
var result = new Uint8Array(32); var result = new Uint8Array(32);
try { try {
var data = convert_1.arrayify(value); var data = bytes_1.arrayify(value);
if (data.length > 32) { if (data.length > 32) {
throw new Error(); throw new Error();
} }
@ -409,12 +409,12 @@ var CoderFixedBytes = /** @class */ (function (_super) {
errors.throwError('insufficient data for ' + name + ' type', errors.INVALID_ARGUMENT, { errors.throwError('insufficient data for ' + name + ' type', errors.INVALID_ARGUMENT, {
arg: this.localName, arg: this.localName,
coderType: this.name, coderType: this.name,
value: convert_1.hexlify(data.slice(offset, offset + 32)) value: bytes_1.hexlify(data.slice(offset, offset + 32))
}); });
} }
return { return {
consumed: 32, consumed: 32,
value: this.coerceFunc(this.name, convert_1.hexlify(data.slice(offset, offset + this.length))) value: this.coerceFunc(this.name, bytes_1.hexlify(data.slice(offset, offset + this.length)))
}; };
}; };
return CoderFixedBytes; return CoderFixedBytes;
@ -427,7 +427,7 @@ var CoderAddress = /** @class */ (function (_super) {
CoderAddress.prototype.encode = function (value) { CoderAddress.prototype.encode = function (value) {
var result = new Uint8Array(32); var result = new Uint8Array(32);
try { try {
result.set(convert_1.arrayify(address_1.getAddress(value)), 12); result.set(bytes_1.arrayify(address_1.getAddress(value)), 12);
} }
catch (error) { catch (error) {
errors.throwError('invalid address', errors.INVALID_ARGUMENT, { errors.throwError('invalid address', errors.INVALID_ARGUMENT, {
@ -443,12 +443,12 @@ var CoderAddress = /** @class */ (function (_super) {
errors.throwError('insufficuent data for address type', errors.INVALID_ARGUMENT, { errors.throwError('insufficuent data for address type', errors.INVALID_ARGUMENT, {
arg: this.localName, arg: this.localName,
coderType: 'address', coderType: 'address',
value: convert_1.hexlify(data.slice(offset, offset + 32)) value: bytes_1.hexlify(data.slice(offset, offset + 32))
}); });
} }
return { return {
consumed: 32, consumed: 32,
value: this.coerceFunc('address', address_1.getAddress(convert_1.hexlify(data.slice(offset + 12, offset + 32)))) value: this.coerceFunc('address', address_1.getAddress(bytes_1.hexlify(data.slice(offset + 12, offset + 32))))
}; };
}; };
return CoderAddress; return CoderAddress;
@ -456,7 +456,7 @@ var CoderAddress = /** @class */ (function (_super) {
function _encodeDynamicBytes(value) { function _encodeDynamicBytes(value) {
var dataLength = Math.trunc(32 * Math.ceil(value.length / 32)); var dataLength = Math.trunc(32 * Math.ceil(value.length / 32));
var padding = new Uint8Array(dataLength - value.length); var padding = new Uint8Array(dataLength - value.length);
return convert_1.concat([ return bytes_1.concat([
uint256Coder.encode(value.length), uint256Coder.encode(value.length),
value, value,
padding padding
@ -467,7 +467,7 @@ function _decodeDynamicBytes(data, offset, localName) {
errors.throwError('insufficient data for dynamicBytes length', errors.INVALID_ARGUMENT, { errors.throwError('insufficient data for dynamicBytes length', errors.INVALID_ARGUMENT, {
arg: localName, arg: localName,
coderType: 'dynamicBytes', coderType: 'dynamicBytes',
value: convert_1.hexlify(data.slice(offset, offset + 32)) value: bytes_1.hexlify(data.slice(offset, offset + 32))
}); });
} }
var length = uint256Coder.decode(data, offset).value; var length = uint256Coder.decode(data, offset).value;
@ -485,7 +485,7 @@ function _decodeDynamicBytes(data, offset, localName) {
errors.throwError('insufficient data for dynamicBytes type', errors.INVALID_ARGUMENT, { errors.throwError('insufficient data for dynamicBytes type', errors.INVALID_ARGUMENT, {
arg: localName, arg: localName,
coderType: 'dynamicBytes', coderType: 'dynamicBytes',
value: convert_1.hexlify(data.slice(offset, offset + 32 + length)) value: bytes_1.hexlify(data.slice(offset, offset + 32 + length))
}); });
} }
return { return {
@ -500,7 +500,7 @@ var CoderDynamicBytes = /** @class */ (function (_super) {
} }
CoderDynamicBytes.prototype.encode = function (value) { CoderDynamicBytes.prototype.encode = function (value) {
try { try {
return _encodeDynamicBytes(convert_1.arrayify(value)); return _encodeDynamicBytes(bytes_1.arrayify(value));
} }
catch (error) { catch (error) {
errors.throwError('invalid bytes value', errors.INVALID_ARGUMENT, { errors.throwError('invalid bytes value', errors.INVALID_ARGUMENT, {
@ -513,7 +513,7 @@ var CoderDynamicBytes = /** @class */ (function (_super) {
}; };
CoderDynamicBytes.prototype.decode = function (data, offset) { CoderDynamicBytes.prototype.decode = function (data, offset) {
var result = _decodeDynamicBytes(data, offset, this.localName); var result = _decodeDynamicBytes(data, offset, this.localName);
result.value = this.coerceFunc('bytes', convert_1.hexlify(result.value)); result.value = this.coerceFunc('bytes', bytes_1.hexlify(result.value));
return result; return result;
}; };
return CoderDynamicBytes; return CoderDynamicBytes;
@ -677,7 +677,7 @@ var CoderArray = /** @class */ (function (_super) {
for (var i = 0; i < value.length; i++) { for (var i = 0; i < value.length; i++) {
coders.push(this.coder); coders.push(this.coder);
} }
return convert_1.concat([result, pack(coders, value)]); return bytes_1.concat([result, pack(coders, value)]);
}; };
CoderArray.prototype.decode = function (data, offset) { CoderArray.prototype.decode = function (data, offset) {
// @TODO: // @TODO:
@ -868,7 +868,7 @@ var AbiCoder = /** @class */ (function () {
} }
coders.push(getParamCoder(this.coerceFunc, typeObject)); coders.push(getParamCoder(this.coerceFunc, typeObject));
}, this); }, this);
return convert_1.hexlify(new CoderTuple(this.coerceFunc, coders, '_').encode(values)); return bytes_1.hexlify(new CoderTuple(this.coerceFunc, coders, '_').encode(values));
}; };
AbiCoder.prototype.decode = function (types, data) { AbiCoder.prototype.decode = function (types, data) {
var coders = []; var coders = [];
@ -883,7 +883,7 @@ var AbiCoder = /** @class */ (function () {
} }
coders.push(getParamCoder(this.coerceFunc, typeObject)); coders.push(getParamCoder(this.coerceFunc, typeObject));
}, this); }, this);
return new CoderTuple(this.coerceFunc, coders, '_').decode(convert_1.arrayify(data), 0).value; return new CoderTuple(this.coerceFunc, coders, '_').decode(bytes_1.arrayify(data), 0).value;
}; };
return AbiCoder; return AbiCoder;
}()); }());

View File

@ -1,5 +1,5 @@
import { BigNumber } from './bignumber'; import { BigNumber } from './bignumber';
import { Arrayish } from './convert'; import { Arrayish } from './bytes';
export declare function getAddress(address: string): string; export declare function getAddress(address: string): string;
export declare function getIcapAddress(address: string): string; export declare function getIcapAddress(address: string): string;
export declare function getContractAddress(transaction: { export declare function getContractAddress(transaction: {

View File

@ -2,7 +2,7 @@
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
// We use this for base 36 maths // We use this for base 36 maths
var BN = require("bn.js"); var BN = require("bn.js");
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
var keccak256_1 = require("./keccak256"); var keccak256_1 = require("./keccak256");
var rlp_1 = require("./rlp"); var rlp_1 = require("./rlp");
var errors = require("./errors"); var errors = require("./errors");
@ -16,7 +16,7 @@ function getChecksumAddress(address) {
for (var i_1 = 0; i_1 < 40; i_1++) { for (var i_1 = 0; i_1 < 40; i_1++) {
hashed[i_1] = chars[i_1].charCodeAt(0); hashed[i_1] = chars[i_1].charCodeAt(0);
} }
hashed = convert_1.arrayify(keccak256_1.keccak256(hashed)); hashed = bytes_1.arrayify(keccak256_1.keccak256(hashed));
for (var i = 0; i < 40; i += 2) { for (var i = 0; i < 40; i += 2) {
if ((hashed[i >> 1] >> 4) >= 8) { if ((hashed[i >> 1] >> 4) >= 8) {
chars[i] = chars[i].toUpperCase(); chars[i] = chars[i].toUpperCase();
@ -115,7 +115,7 @@ function getContractAddress(transaction) {
var nonce = transaction.nonce; var nonce = transaction.nonce;
return getAddress('0x' + keccak256_1.keccak256(rlp_1.encode([ return getAddress('0x' + keccak256_1.keccak256(rlp_1.encode([
getAddress(transaction.from), getAddress(transaction.from),
convert_1.stripZeros(convert_1.hexlify(nonce)) bytes_1.stripZeros(bytes_1.hexlify(nonce))
])).substring(26)); ])).substring(26));
} }
exports.getContractAddress = getContractAddress; exports.getContractAddress = getContractAddress;

View File

@ -1,3 +1,3 @@
import { Arrayish } from './convert'; import { Arrayish } from './bytes';
export declare function decode(textData: string): Uint8Array; export declare function decode(textData: string): Uint8Array;
export declare function encode(data: Arrayish): string; export declare function encode(data: Arrayish): string;

View File

@ -1,12 +1,12 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
function decode(textData) { function decode(textData) {
return convert_1.arrayify(new Uint8Array(new Buffer(textData, 'base64'))); return bytes_1.arrayify(new Uint8Array(new Buffer(textData, 'base64')));
} }
exports.decode = decode; exports.decode = decode;
; ;
function encode(data) { function encode(data) {
return new Buffer(convert_1.arrayify(data)).toString('base64'); return new Buffer(bytes_1.arrayify(data)).toString('base64');
} }
exports.encode = encode; exports.encode = encode;

View File

@ -1,4 +1,4 @@
import { Arrayish } from './convert'; import { Arrayish } from './bytes';
export declare type BigNumberish = BigNumber | string | number | Arrayish; export declare type BigNumberish = BigNumber | string | number | Arrayish;
export declare class BigNumber { export declare class BigNumber {
private readonly _bn; private readonly _bn;

View File

@ -18,7 +18,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
* *
*/ */
var bn_js_1 = __importDefault(require("bn.js")); var bn_js_1 = __importDefault(require("bn.js"));
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
var properties_1 = require("./properties"); var properties_1 = require("./properties");
var errors = __importStar(require("../utils/errors")); var errors = __importStar(require("../utils/errors"));
function _isBigNumber(value) { function _isBigNumber(value) {
@ -28,13 +28,13 @@ var BigNumber = /** @class */ (function () {
function BigNumber(value) { function BigNumber(value) {
errors.checkNew(this, BigNumber); errors.checkNew(this, BigNumber);
if (typeof (value) === 'string') { if (typeof (value) === 'string') {
if (convert_1.isHexString(value)) { if (bytes_1.isHexString(value)) {
if (value == '0x') { if (value == '0x') {
value = '0x0'; value = '0x0';
} }
properties_1.defineReadOnly(this, '_bn', new bn_js_1.default.BN(value.substring(2), 16)); properties_1.defineReadOnly(this, '_bn', new bn_js_1.default.BN(value.substring(2), 16));
} }
else if (value[0] === '-' && convert_1.isHexString(value.substring(1))) { else if (value[0] === '-' && bytes_1.isHexString(value.substring(1))) {
properties_1.defineReadOnly(this, '_bn', (new bn_js_1.default.BN(value.substring(3), 16)).mul(exports.ConstantNegativeOne._bn)); properties_1.defineReadOnly(this, '_bn', (new bn_js_1.default.BN(value.substring(3), 16)).mul(exports.ConstantNegativeOne._bn));
} }
else if (value.match(/^-?[0-9]*$/)) { else if (value.match(/^-?[0-9]*$/)) {
@ -61,8 +61,8 @@ var BigNumber = /** @class */ (function () {
else if (_isBigNumber(value)) { else if (_isBigNumber(value)) {
properties_1.defineReadOnly(this, '_bn', value._bn); properties_1.defineReadOnly(this, '_bn', value._bn);
} }
else if (convert_1.isArrayish(value)) { else if (bytes_1.isArrayish(value)) {
properties_1.defineReadOnly(this, '_bn', new bn_js_1.default.BN(convert_1.hexlify(value).substring(2), 16)); properties_1.defineReadOnly(this, '_bn', new bn_js_1.default.BN(bytes_1.hexlify(value).substring(2), 16));
} }
else { else {
errors.throwError('invalid BigNumber value', errors.INVALID_ARGUMENT, { arg: 'value', value: value }); errors.throwError('invalid BigNumber value', errors.INVALID_ARGUMENT, { arg: 'value', value: value });

19
src/utils/bytes.d.ts vendored Normal file
View File

@ -0,0 +1,19 @@
/**
* Conversion Utilities
*
*/
import { BigNumber } from './bignumber';
import { Signature } from './secp256k1';
export declare type Arrayish = string | ArrayLike<number>;
export declare function isArrayish(value: any): boolean;
export declare function arrayify(value: Arrayish | BigNumber): Uint8Array;
export declare function concat(objects: Array<Arrayish>): Uint8Array;
export declare function stripZeros(value: Arrayish): Uint8Array;
export declare function padZeros(value: Arrayish, length: number): Uint8Array;
export declare function isHexString(value: any, length?: number): boolean;
export declare function hexlify(value: Arrayish | BigNumber | number): string;
export declare function hexDataLength(data: string): number;
export declare function hexDataSlice(data: string, offset: number, length?: number): string;
export declare function hexStripZeros(value: string): string;
export declare function hexZeroPad(value: string, length: number): string;
export declare function splitSignature(signature: Arrayish): Signature;

226
src/utils/bytes.js Normal file
View File

@ -0,0 +1,226 @@
"use strict";
/**
* Conversion Utilities
*
*/
Object.defineProperty(exports, "__esModule", { value: true });
var errors = require("./errors");
function isBigNumber(value) {
return !!value._bn;
}
function addSlice(array) {
if (array.slice) {
return array;
}
array.slice = function () {
var args = Array.prototype.slice.call(arguments);
return new Uint8Array(Array.prototype.slice.apply(array, args));
};
return array;
}
function isArrayish(value) {
if (!value || parseInt(value.length) != value.length || typeof (value) === 'string') {
return false;
}
for (var i = 0; i < value.length; i++) {
var v = value[i];
if (v < 0 || v >= 256 || parseInt(v) != v) {
return false;
}
}
return true;
}
exports.isArrayish = isArrayish;
function arrayify(value) {
if (value == null) {
errors.throwError('cannot convert null value to array', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
}
if (isBigNumber(value)) {
value = value.toHexString();
}
if (typeof (value) === 'string') {
var match = value.match(/^(0x)?[0-9a-fA-F]*$/);
if (!match) {
errors.throwError('invalid hexidecimal string', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
}
if (match[1] !== '0x') {
errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
}
value = value.substring(2);
if (value.length % 2) {
value = '0' + value;
}
var result = [];
for (var i = 0; i < value.length; i += 2) {
result.push(parseInt(value.substr(i, 2), 16));
}
return addSlice(new Uint8Array(result));
}
else if (typeof (value) === 'string') {
}
if (isArrayish(value)) {
return addSlice(new Uint8Array(value));
}
errors.throwError('invalid arrayify value', null, { arg: 'value', value: value, type: typeof (value) });
return null;
}
exports.arrayify = arrayify;
function concat(objects) {
var arrays = [];
var length = 0;
for (var i = 0; i < objects.length; i++) {
var object = arrayify(objects[i]);
arrays.push(object);
length += object.length;
}
var result = new Uint8Array(length);
var offset = 0;
for (var i = 0; i < arrays.length; i++) {
result.set(arrays[i], offset);
offset += arrays[i].length;
}
return addSlice(result);
}
exports.concat = concat;
function stripZeros(value) {
var result = arrayify(value);
if (result.length === 0) {
return result;
}
// Find the first non-zero entry
var start = 0;
while (result[start] === 0) {
start++;
}
// If we started with zeros, strip them
if (start) {
result = result.slice(start);
}
return result;
}
exports.stripZeros = stripZeros;
function padZeros(value, length) {
value = arrayify(value);
if (length < value.length) {
throw new Error('cannot pad');
}
var result = new Uint8Array(length);
result.set(value, length - value.length);
return addSlice(result);
}
exports.padZeros = padZeros;
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;
}
exports.isHexString = isHexString;
var HexCharacters = '0123456789abcdef';
function hexlify(value) {
if (isBigNumber(value)) {
return value.toHexString();
}
if (typeof (value) === 'number') {
if (value < 0) {
errors.throwError('cannot hexlify negative value', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
}
var hex = '';
while (value) {
hex = HexCharacters[value & 0x0f] + hex;
value = Math.trunc(value / 16);
}
if (hex.length) {
if (hex.length % 2) {
hex = '0' + hex;
}
return '0x' + hex;
}
return '0x00';
}
if (typeof (value) === 'string') {
var match = value.match(/^(0x)?[0-9a-fA-F]*$/);
if (!match) {
errors.throwError('invalid hexidecimal string', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
}
if (match[1] !== '0x') {
errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
}
if (value.length % 2) {
value = '0x0' + value.substring(2);
}
return value;
}
if (isArrayish(value)) {
var result = [];
for (var i = 0; i < value.length; i++) {
var v = value[i];
result.push(HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]);
}
return '0x' + result.join('');
}
errors.throwError('invalid hexlify value', null, { arg: 'value', value: value });
return 'never';
}
exports.hexlify = hexlify;
function hexDataLength(data) {
if (!isHexString(data) || (data.length % 2) !== 0) {
return null;
}
return (data.length - 2) / 2;
}
exports.hexDataLength = hexDataLength;
function hexDataSlice(data, offset, length) {
if (!isHexString(data)) {
errors.throwError('invalid hex data', errors.INVALID_ARGUMENT, { arg: 'value', value: data });
}
if ((data.length % 2) !== 0) {
errors.throwError('hex data length must be even', errors.INVALID_ARGUMENT, { arg: 'value', value: data });
}
offset = 2 + 2 * offset;
if (length != null) {
return '0x' + data.substring(offset, offset + 2 * length);
}
return '0x' + data.substring(offset);
}
exports.hexDataSlice = hexDataSlice;
function hexStripZeros(value) {
if (!isHexString(value)) {
errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
}
while (value.length > 3 && value.substring(0, 3) === '0x0') {
value = '0x' + value.substring(3);
}
return value;
}
exports.hexStripZeros = hexStripZeros;
function hexZeroPad(value, length) {
if (!isHexString(value)) {
errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
}
while (value.length < 2 * length + 2) {
value = '0x0' + value.substring(2);
}
return value;
}
exports.hexZeroPad = hexZeroPad;
function splitSignature(signature) {
var bytes = arrayify(signature);
if (bytes.length !== 65) {
throw new Error('invalid signature');
}
var v = bytes[64];
if (v !== 27 && v !== 28) {
v = 27 + (v % 2);
}
return {
r: hexlify(bytes.slice(0, 32)),
s: hexlify(bytes.slice(32, 64)),
recoveryParam: (v - 27),
v: v
};
}
exports.splitSignature = splitSignature;

2
src/utils/hmac.d.ts vendored
View File

@ -1,4 +1,4 @@
import { Arrayish } from './convert'; import { Arrayish } from './bytes';
interface HashFunc { interface HashFunc {
(): HashFunc; (): HashFunc;
update(chunk: Uint8Array): HashFunc; update(chunk: Uint8Array): HashFunc;

View File

@ -8,21 +8,21 @@ var __importStar = (this && this.__importStar) || function (mod) {
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var _hash = __importStar(require("hash.js")); var _hash = __importStar(require("hash.js"));
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
var _hmac = _hash['hmac']; var _hmac = _hash['hmac'];
var _sha256 = _hash['sha256']; var _sha256 = _hash['sha256'];
var _sha512 = _hash['sha512']; var _sha512 = _hash['sha512'];
// @TODO: Make this use create-hmac in node // @TODO: Make this use create-hmac in node
function createSha256Hmac(key) { function createSha256Hmac(key) {
if (!key['buffer']) { if (!key['buffer']) {
key = convert_1.arrayify(key); key = bytes_1.arrayify(key);
} }
return _hmac(_sha256, key); return _hmac(_sha256, key);
} }
exports.createSha256Hmac = createSha256Hmac; exports.createSha256Hmac = createSha256Hmac;
function createSha512Hmac(key) { function createSha512Hmac(key) {
if (!key['buffer']) { if (!key['buffer']) {
key = convert_1.arrayify(key); key = bytes_1.arrayify(key);
} }
return _hmac(_sha512, key); return _hmac(_sha512, key);
} }

14
src/utils/index.d.ts vendored
View File

@ -2,7 +2,7 @@ import { getAddress, getContractAddress, getIcapAddress } from './address';
import { AbiCoder, parseSignature } from './abi-coder'; import { AbiCoder, parseSignature } from './abi-coder';
import * as base64 from './base64'; import * as base64 from './base64';
import * as bigNumber from './bignumber'; import * as bigNumber from './bignumber';
import * as convert from './convert'; import * as bytes from './bytes';
import { id } from './id'; import { id } from './id';
import { keccak256 } from './keccak256'; import { keccak256 } from './keccak256';
import { namehash } from './namehash'; import { namehash } from './namehash';
@ -21,14 +21,14 @@ declare const _default: {
RLP: typeof RLP; RLP: typeof RLP;
fetchJson: typeof fetchJson; fetchJson: typeof fetchJson;
etherSymbol: string; etherSymbol: string;
arrayify: typeof convert.arrayify; arrayify: typeof bytes.arrayify;
concat: typeof convert.concat; concat: typeof bytes.concat;
padZeros: typeof convert.padZeros; padZeros: typeof bytes.padZeros;
stripZeros: typeof convert.stripZeros; stripZeros: typeof bytes.stripZeros;
base64: typeof base64; base64: typeof base64;
bigNumberify: typeof bigNumber.bigNumberify; bigNumberify: typeof bigNumber.bigNumberify;
BigNumber: typeof bigNumber.BigNumber; BigNumber: typeof bigNumber.BigNumber;
hexlify: typeof convert.hexlify; hexlify: typeof bytes.hexlify;
toUtf8Bytes: typeof utf8.toUtf8Bytes; toUtf8Bytes: typeof utf8.toUtf8Bytes;
toUtf8String: typeof utf8.toUtf8String; toUtf8String: typeof utf8.toUtf8String;
namehash: typeof namehash; namehash: typeof namehash;
@ -46,7 +46,7 @@ declare const _default: {
solidityPack: typeof solidity.pack; solidityPack: typeof solidity.pack;
solidityKeccak256: typeof solidity.keccak256; solidityKeccak256: typeof solidity.keccak256;
soliditySha256: typeof solidity.sha256; soliditySha256: typeof solidity.sha256;
splitSignature: typeof convert.splitSignature; splitSignature: typeof bytes.splitSignature;
parseTransaction: typeof parseTransaction; parseTransaction: typeof parseTransaction;
}; };
export default _default; export default _default;

View File

@ -13,7 +13,7 @@ var address_1 = require("./address");
var abi_coder_1 = require("./abi-coder"); var abi_coder_1 = require("./abi-coder");
var base64 = __importStar(require("./base64")); var base64 = __importStar(require("./base64"));
var bigNumber = __importStar(require("./bignumber")); var bigNumber = __importStar(require("./bignumber"));
var convert = __importStar(require("./convert")); var bytes = __importStar(require("./bytes"));
var id_1 = require("./id"); var id_1 = require("./id");
var keccak256_1 = require("./keccak256"); var keccak256_1 = require("./keccak256");
var namehash_1 = require("./namehash"); var namehash_1 = require("./namehash");
@ -37,14 +37,14 @@ exports.default = {
//etherSymbol: '\uD835\uDF63', //etherSymbol: '\uD835\uDF63',
// NFKC (composed) // NFKC (composed)
etherSymbol: '\u039e', etherSymbol: '\u039e',
arrayify: convert.arrayify, arrayify: bytes.arrayify,
concat: convert.concat, concat: bytes.concat,
padZeros: convert.padZeros, padZeros: bytes.padZeros,
stripZeros: convert.stripZeros, stripZeros: bytes.stripZeros,
base64: base64, base64: base64,
bigNumberify: bigNumber.bigNumberify, bigNumberify: bigNumber.bigNumberify,
BigNumber: bigNumber.BigNumber, BigNumber: bigNumber.BigNumber,
hexlify: convert.hexlify, hexlify: bytes.hexlify,
toUtf8Bytes: utf8.toUtf8Bytes, toUtf8Bytes: utf8.toUtf8Bytes,
toUtf8String: utf8.toUtf8String, toUtf8String: utf8.toUtf8String,
namehash: namehash_1.namehash, namehash: namehash_1.namehash,
@ -62,6 +62,6 @@ exports.default = {
solidityPack: solidity.pack, solidityPack: solidity.pack,
solidityKeccak256: solidity.keccak256, solidityKeccak256: solidity.keccak256,
soliditySha256: solidity.sha256, soliditySha256: solidity.sha256,
splitSignature: convert.splitSignature, splitSignature: bytes.splitSignature,
parseTransaction: transaction_1.parse parseTransaction: transaction_1.parse
}; };

View File

@ -1,2 +1,2 @@
import { Arrayish } from './convert'; import { Arrayish } from './bytes';
export declare function keccak256(data: Arrayish): string; export declare function keccak256(data: Arrayish): string;

View File

@ -1,8 +1,8 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var sha3 = require("js-sha3"); var sha3 = require("js-sha3");
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
function keccak256(data) { function keccak256(data) {
return '0x' + sha3.keccak_256(convert_1.arrayify(data)); return '0x' + sha3.keccak_256(bytes_1.arrayify(data));
} }
exports.keccak256 = keccak256; exports.keccak256 = keccak256;

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
var utf8_1 = require("./utf8"); var utf8_1 = require("./utf8");
var keccak256_1 = require("./keccak256"); var keccak256_1 = require("./keccak256");
var Zeros = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); var Zeros = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
@ -19,9 +19,9 @@ function namehash(name) {
while (name.length) { while (name.length) {
var partition = name.match(Partition); var partition = name.match(Partition);
var label = utf8_1.toUtf8Bytes(partition[3]); var label = utf8_1.toUtf8Bytes(partition[3]);
result = keccak256_1.keccak256(convert_1.concat([result, keccak256_1.keccak256(label)])); result = keccak256_1.keccak256(bytes_1.concat([result, keccak256_1.keccak256(label)]));
name = partition[2] || ''; name = partition[2] || '';
} }
return convert_1.hexlify(result); return bytes_1.hexlify(result);
} }
exports.namehash = namehash; exports.namehash = namehash;

View File

@ -1,4 +1,4 @@
import { Arrayish } from './convert'; import { Arrayish } from './bytes';
import { HmacFunc } from './hmac'; import { HmacFunc } from './hmac';
export interface CreateHmacFunc { export interface CreateHmacFunc {
(key: Arrayish): HmacFunc; (key: Arrayish): HmacFunc;

View File

@ -1,9 +1,9 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
function pbkdf2(password, salt, iterations, keylen, createHmac) { function pbkdf2(password, salt, iterations, keylen, createHmac) {
password = convert_1.arrayify(password); password = bytes_1.arrayify(password);
salt = convert_1.arrayify(salt); salt = bytes_1.arrayify(salt);
var hLen; var hLen;
var l = 1; var l = 1;
var DK = new Uint8Array(keylen); var DK = new Uint8Array(keylen);
@ -35,8 +35,8 @@ function pbkdf2(password, salt, iterations, keylen, createHmac) {
var destPos = (i - 1) * hLen; var destPos = (i - 1) * hLen;
var len = (i === l ? r : hLen); var len = (i === l ? r : hLen);
//T.copy(DK, destPos, 0, len) //T.copy(DK, destPos, 0, len)
DK.set(convert_1.arrayify(T).slice(0, len), destPos); DK.set(bytes_1.arrayify(T).slice(0, len), destPos);
} }
return convert_1.arrayify(DK); return bytes_1.arrayify(DK);
} }
exports.pbkdf2 = pbkdf2; exports.pbkdf2 = pbkdf2;

View File

@ -1,9 +1,8 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
var crypto_1 = require("crypto"); var crypto_1 = require("crypto");
//function _randomBytes(length) { return "0x00"; }
function randomBytes(length) { function randomBytes(length) {
return convert_1.arrayify(crypto_1.randomBytes(length)); return bytes_1.arrayify(crypto_1.randomBytes(length));
} }
exports.randomBytes = randomBytes; exports.randomBytes = randomBytes;

2
src/utils/rlp.d.ts vendored
View File

@ -1,3 +1,3 @@
import { Arrayish } from './convert'; import { Arrayish } from './bytes';
export declare function encode(object: any): string; export declare function encode(object: any): string;
export declare function decode(data: Arrayish): any; export declare function decode(data: Arrayish): any;

View File

@ -1,7 +1,7 @@
"use strict"; "use strict";
//See: https://github.com/ethereum/wiki/wiki/RLP //See: https://github.com/ethereum/wiki/wiki/RLP
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
function arrayifyInteger(value) { function arrayifyInteger(value) {
var result = []; var result = [];
while (value) { while (value) {
@ -32,7 +32,7 @@ function _encode(object) {
return length.concat(payload); return length.concat(payload);
} }
else { else {
var data = Array.prototype.slice.call(convert_1.arrayify(object)); var data = Array.prototype.slice.call(bytes_1.arrayify(object));
if (data.length === 1 && data[0] <= 0x7f) { if (data.length === 1 && data[0] <= 0x7f) {
return data; return data;
} }
@ -46,7 +46,7 @@ function _encode(object) {
} }
} }
function encode(object) { function encode(object) {
return convert_1.hexlify(_encode(object)); return bytes_1.hexlify(_encode(object));
} }
exports.encode = encode; exports.encode = encode;
function _decodeChildren(data, offset, childOffset, length) { function _decodeChildren(data, offset, childOffset, length) {
@ -94,7 +94,7 @@ function _decode(data, offset) {
if (offset + 1 + lengthLength + length > data.length) { if (offset + 1 + lengthLength + length > data.length) {
throw new Error('invalid rlp data'); throw new Error('invalid rlp data');
} }
var result = convert_1.hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length)); var result = bytes_1.hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));
return { consumed: (1 + lengthLength + length), result: result }; return { consumed: (1 + lengthLength + length), result: result };
} }
else if (data[offset] >= 0x80) { else if (data[offset] >= 0x80) {
@ -102,13 +102,13 @@ function _decode(data, offset) {
if (offset + 1 + length > data.length) { if (offset + 1 + length > data.length) {
throw new Error('invlaid rlp data'); throw new Error('invlaid rlp data');
} }
var result = convert_1.hexlify(data.slice(offset + 1, offset + 1 + length)); var result = bytes_1.hexlify(data.slice(offset + 1, offset + 1 + length));
return { consumed: (1 + length), result: result }; return { consumed: (1 + length), result: result };
} }
return { consumed: 1, result: convert_1.hexlify(data[offset]) }; return { consumed: 1, result: bytes_1.hexlify(data[offset]) };
} }
function decode(data) { function decode(data) {
var bytes = convert_1.arrayify(data); var bytes = bytes_1.arrayify(data);
var decoded = _decode(bytes, 0); var decoded = _decode(bytes, 0);
if (decoded.consumed !== bytes.length) { if (decoded.consumed !== bytes.length) {
throw new Error('invalid rlp data'); throw new Error('invalid rlp data');

View File

@ -1,4 +1,4 @@
import { Arrayish } from '../utils/convert'; import { Arrayish } from './bytes';
export declare const N: string; export declare const N: string;
export interface Signature { export interface Signature {
r: string; r: string;

View File

@ -8,24 +8,24 @@ var __importStar = (this && this.__importStar) || function (mod) {
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var address_1 = require("./address"); var address_1 = require("./address");
var convert_1 = require("../utils/convert"); var bytes_1 = require("./bytes");
var keccak256_1 = require("./keccak256"); var keccak256_1 = require("./keccak256");
var properties_1 = require("../utils/properties"); var properties_1 = require("./properties");
var errors = __importStar(require("../utils/errors")); var errors = __importStar(require("./errors"));
var elliptic = __importStar(require("elliptic")); var elliptic = __importStar(require("elliptic"));
var curve = new elliptic.ec('secp256k1'); var curve = new elliptic.ec('secp256k1');
exports.N = '0x' + curve.n.toString(16); exports.N = '0x' + curve.n.toString(16);
var KeyPair = /** @class */ (function () { var KeyPair = /** @class */ (function () {
function KeyPair(privateKey) { function KeyPair(privateKey) {
var keyPair = curve.keyFromPrivate(convert_1.arrayify(privateKey)); var keyPair = curve.keyFromPrivate(bytes_1.arrayify(privateKey));
properties_1.defineReadOnly(this, 'privateKey', convert_1.hexlify(keyPair.priv.toArray('be', 32))); properties_1.defineReadOnly(this, 'privateKey', bytes_1.hexlify(keyPair.priv.toArray('be', 32)));
properties_1.defineReadOnly(this, 'publicKey', '0x' + keyPair.getPublic(false, 'hex')); properties_1.defineReadOnly(this, 'publicKey', '0x' + keyPair.getPublic(false, 'hex'));
properties_1.defineReadOnly(this, 'compressedPublicKey', '0x' + keyPair.getPublic(true, 'hex')); properties_1.defineReadOnly(this, 'compressedPublicKey', '0x' + keyPair.getPublic(true, 'hex'));
properties_1.defineReadOnly(this, 'publicKeyBytes', keyPair.getPublic().encode(null, true)); properties_1.defineReadOnly(this, 'publicKeyBytes', keyPair.getPublic().encode(null, true));
} }
KeyPair.prototype.sign = function (digest) { KeyPair.prototype.sign = function (digest) {
var keyPair = curve.keyFromPrivate(convert_1.arrayify(this.privateKey)); var keyPair = curve.keyFromPrivate(bytes_1.arrayify(this.privateKey));
var signature = keyPair.sign(convert_1.arrayify(digest), { canonical: true }); var signature = keyPair.sign(bytes_1.arrayify(digest), { canonical: true });
return { return {
recoveryParam: signature.recoveryParam, recoveryParam: signature.recoveryParam,
r: '0x' + signature.r.toString(16), r: '0x' + signature.r.toString(16),
@ -38,14 +38,14 @@ var KeyPair = /** @class */ (function () {
exports.KeyPair = KeyPair; exports.KeyPair = KeyPair;
function recoverPublicKey(digest, signature) { function recoverPublicKey(digest, signature) {
var sig = { var sig = {
r: convert_1.arrayify(signature.r), r: bytes_1.arrayify(signature.r),
s: convert_1.arrayify(signature.s) s: bytes_1.arrayify(signature.s)
}; };
return '0x' + curve.recoverPubKey(convert_1.arrayify(digest), sig, signature.recoveryParam).encode('hex', false); return '0x' + curve.recoverPubKey(bytes_1.arrayify(digest), sig, signature.recoveryParam).encode('hex', false);
} }
exports.recoverPublicKey = recoverPublicKey; exports.recoverPublicKey = recoverPublicKey;
function computePublicKey(key, compressed) { function computePublicKey(key, compressed) {
var bytes = convert_1.arrayify(key); var bytes = bytes_1.arrayify(key);
if (bytes.length === 32) { if (bytes.length === 32) {
var keyPair = new KeyPair(bytes); var keyPair = new KeyPair(bytes);
if (compressed) { if (compressed) {
@ -55,13 +55,13 @@ function computePublicKey(key, compressed) {
} }
else if (bytes.length === 33) { else if (bytes.length === 33) {
if (compressed) { if (compressed) {
return convert_1.hexlify(bytes); return bytes_1.hexlify(bytes);
} }
return '0x' + curve.keyFromPublic(bytes).getPublic(false, 'hex'); return '0x' + curve.keyFromPublic(bytes).getPublic(false, 'hex');
} }
else if (bytes.length === 65) { else if (bytes.length === 65) {
if (!compressed) { if (!compressed) {
return convert_1.hexlify(bytes); return bytes_1.hexlify(bytes);
} }
return '0x' + curve.keyFromPublic(bytes).getPublic(true, 'hex'); return '0x' + curve.keyFromPublic(bytes).getPublic(true, 'hex');
} }

2
src/utils/sha2.d.ts vendored
View File

@ -1,3 +1,3 @@
import { Arrayish } from './convert'; import { Arrayish } from './bytes';
export declare function sha256(data: Arrayish): string; export declare function sha256(data: Arrayish): string;
export declare function sha512(data: Arrayish): string; export declare function sha512(data: Arrayish): string;

View File

@ -8,14 +8,14 @@ var __importStar = (this && this.__importStar) || function (mod) {
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var _hash = __importStar(require("hash.js")); var _hash = __importStar(require("hash.js"));
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
var _sha256 = _hash['sha256']; var _sha256 = _hash['sha256'];
var _sha512 = _hash['sha512']; var _sha512 = _hash['sha512'];
function sha256(data) { function sha256(data) {
return '0x' + (_sha256().update(convert_1.arrayify(data)).digest('hex')); return '0x' + (_sha256().update(bytes_1.arrayify(data)).digest('hex'));
} }
exports.sha256 = sha256; exports.sha256 = sha256;
function sha512(data) { function sha512(data) {
return '0x' + (_sha512().update(convert_1.arrayify(data)).digest('hex')); return '0x' + (_sha512().update(bytes_1.arrayify(data)).digest('hex'));
} }
exports.sha512 = sha512; exports.sha512 = sha512;

View File

@ -1,7 +1,7 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var bignumber_1 = require("./bignumber"); var bignumber_1 = require("./bignumber");
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
var utf8_1 = require("./utf8"); var utf8_1 = require("./utf8");
var keccak256_1 = require("./keccak256"); var keccak256_1 = require("./keccak256");
var sha2_1 = require("./sha2"); var sha2_1 = require("./sha2");
@ -13,19 +13,19 @@ function _pack(type, value, isArray) {
switch (type) { switch (type) {
case 'address': case 'address':
if (isArray) { if (isArray) {
return convert_1.padZeros(value, 32); return bytes_1.padZeros(value, 32);
} }
return convert_1.arrayify(value); return bytes_1.arrayify(value);
case 'string': case 'string':
return utf8_1.toUtf8Bytes(value); return utf8_1.toUtf8Bytes(value);
case 'bytes': case 'bytes':
return convert_1.arrayify(value); return bytes_1.arrayify(value);
case 'bool': case 'bool':
value = (value ? '0x01' : '0x00'); value = (value ? '0x01' : '0x00');
if (isArray) { if (isArray) {
return convert_1.padZeros(value, 32); return bytes_1.padZeros(value, 32);
} }
return convert_1.arrayify(value); return bytes_1.arrayify(value);
} }
var match = type.match(regexNumber); var match = type.match(regexNumber);
if (match) { if (match) {
@ -38,7 +38,7 @@ function _pack(type, value, isArray) {
size = 256; size = 256;
} }
value = bignumber_1.bigNumberify(value).toTwos(size); value = bignumber_1.bigNumberify(value).toTwos(size);
return convert_1.padZeros(value, size / 8); return bytes_1.padZeros(value, size / 8);
} }
match = type.match(regexBytes); match = type.match(regexBytes);
if (match) { if (match) {
@ -46,11 +46,11 @@ function _pack(type, value, isArray) {
if (String(size) != match[1] || size === 0 || size > 32) { if (String(size) != match[1] || size === 0 || size > 32) {
throw new Error('invalid number type - ' + type); throw new Error('invalid number type - ' + type);
} }
if (convert_1.arrayify(value).byteLength !== size) { if (bytes_1.arrayify(value).byteLength !== size) {
throw new Error('invalid value for ' + type); throw new Error('invalid value for ' + type);
} }
if (isArray) { if (isArray) {
return convert_1.arrayify((value + Zeros).substring(0, 66)); return bytes_1.arrayify((value + Zeros).substring(0, 66));
} }
return value; return value;
} }
@ -66,7 +66,7 @@ function _pack(type, value, isArray) {
value = _pack(baseType, value, true); value = _pack(baseType, value, true);
result.push(value); result.push(value);
}); });
return convert_1.concat(result); return bytes_1.concat(result);
} }
throw new Error('unknown type - ' + type); throw new Error('unknown type - ' + type);
} }
@ -79,7 +79,7 @@ function pack(types, values) {
types.forEach(function (type, index) { types.forEach(function (type, index) {
tight.push(_pack(type, values[index])); tight.push(_pack(type, values[index]));
}); });
return convert_1.hexlify(convert_1.concat(tight)); return bytes_1.hexlify(bytes_1.concat(tight));
} }
exports.pack = pack; exports.pack = pack;
function keccak256(types, values) { function keccak256(types, values) {

View File

@ -1,5 +1,5 @@
import { BigNumber, BigNumberish } from './bignumber'; import { BigNumber, BigNumberish } from './bignumber';
import { Arrayish } from './convert'; import { Arrayish } from './bytes';
import { Signature } from './secp256k1'; import { Signature } from './secp256k1';
export interface UnsignedTransaction { export interface UnsignedTransaction {
to?: string; to?: string;

View File

@ -9,7 +9,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var address_1 = require("./address"); var address_1 = require("./address");
var bignumber_1 = require("./bignumber"); var bignumber_1 = require("./bignumber");
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
var keccak256_1 = require("./keccak256"); var keccak256_1 = require("./keccak256");
var secp256k1_1 = require("./secp256k1"); var secp256k1_1 = require("./secp256k1");
var RLP = __importStar(require("./rlp")); var RLP = __importStar(require("./rlp"));
@ -37,7 +37,7 @@ function sign(transaction, signDigest) {
var raw = []; var raw = [];
transactionFields.forEach(function (fieldInfo) { transactionFields.forEach(function (fieldInfo) {
var value = transaction[fieldInfo.name] || ([]); var value = transaction[fieldInfo.name] || ([]);
value = convert_1.arrayify(convert_1.hexlify(value)); value = bytes_1.arrayify(bytes_1.hexlify(value));
// Fixed-width field // Fixed-width field
if (fieldInfo.length && value.length !== fieldInfo.length && value.length > 0) { if (fieldInfo.length && value.length !== fieldInfo.length && value.length > 0) {
var error = new Error('invalid ' + fieldInfo.name); var error = new Error('invalid ' + fieldInfo.name);
@ -47,7 +47,7 @@ function sign(transaction, signDigest) {
} }
// Variable-width (with a maximum) // Variable-width (with a maximum)
if (fieldInfo.maxLength) { if (fieldInfo.maxLength) {
value = convert_1.stripZeros(value); value = bytes_1.stripZeros(value);
if (value.length > fieldInfo.maxLength) { if (value.length > fieldInfo.maxLength) {
var error = new Error('invalid ' + fieldInfo.name); var error = new Error('invalid ' + fieldInfo.name);
error.reason = 'too long'; error.reason = 'too long';
@ -55,10 +55,10 @@ function sign(transaction, signDigest) {
throw error; throw error;
} }
} }
raw.push(convert_1.hexlify(value)); raw.push(bytes_1.hexlify(value));
}); });
if (transaction.chainId) { if (transaction.chainId) {
raw.push(convert_1.hexlify(transaction.chainId)); raw.push(bytes_1.hexlify(transaction.chainId));
raw.push('0x'); raw.push('0x');
raw.push('0x'); raw.push('0x');
} }
@ -71,7 +71,7 @@ function sign(transaction, signDigest) {
raw.pop(); raw.pop();
v += transaction.chainId * 2 + 8; v += transaction.chainId * 2 + 8;
} }
raw.push(convert_1.hexlify(v)); raw.push(bytes_1.hexlify(v));
raw.push(signature.r); raw.push(signature.r);
raw.push(signature.s); raw.push(signature.s);
return RLP.encode(raw); return RLP.encode(raw);
@ -91,9 +91,9 @@ function parse(rawTransaction) {
data: signedTransaction[5], data: signedTransaction[5],
chainId: 0 chainId: 0
}; };
var v = convert_1.arrayify(signedTransaction[6]); var v = bytes_1.arrayify(signedTransaction[6]);
var r = convert_1.arrayify(signedTransaction[7]); var r = bytes_1.arrayify(signedTransaction[7]);
var s = convert_1.arrayify(signedTransaction[8]); var s = bytes_1.arrayify(signedTransaction[8]);
if (v.length >= 1 && r.length >= 1 && r.length <= 32 && s.length >= 1 && s.length <= 32) { if (v.length >= 1 && r.length >= 1 && r.length <= 32 && s.length >= 1 && s.length <= 32) {
tx.v = bignumber_1.bigNumberify(v).toNumber(); tx.v = bignumber_1.bigNumberify(v).toNumber();
tx.r = signedTransaction[7]; tx.r = signedTransaction[7];
@ -107,14 +107,14 @@ function parse(rawTransaction) {
var recoveryParam = tx.v - 27; var recoveryParam = tx.v - 27;
var raw = signedTransaction.slice(0, 6); var raw = signedTransaction.slice(0, 6);
if (chainId) { if (chainId) {
raw.push(convert_1.hexlify(chainId)); raw.push(bytes_1.hexlify(chainId));
raw.push('0x'); raw.push('0x');
raw.push('0x'); raw.push('0x');
recoveryParam -= chainId * 2 + 8; recoveryParam -= chainId * 2 + 8;
} }
var digest = keccak256_1.keccak256(RLP.encode(raw)); var digest = keccak256_1.keccak256(RLP.encode(raw));
try { try {
tx.from = secp256k1_1.recoverAddress(digest, { r: convert_1.hexlify(r), s: convert_1.hexlify(s), recoveryParam: recoveryParam }); tx.from = secp256k1_1.recoverAddress(digest, { r: bytes_1.hexlify(r), s: bytes_1.hexlify(s), recoveryParam: recoveryParam });
} }
catch (error) { catch (error) {
console.log(error); console.log(error);

2
src/utils/utf8.d.ts vendored
View File

@ -1,4 +1,4 @@
import { Arrayish } from './convert'; import { Arrayish } from './bytes';
export declare enum UnicodeNormalizationForm { export declare enum UnicodeNormalizationForm {
current = "", current = "",
NFC = "NFC", NFC = "NFC",

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
var convert_1 = require("./convert"); var bytes_1 = require("./bytes");
var UnicodeNormalizationForm; var UnicodeNormalizationForm;
(function (UnicodeNormalizationForm) { (function (UnicodeNormalizationForm) {
UnicodeNormalizationForm["current"] = ""; UnicodeNormalizationForm["current"] = "";
@ -43,13 +43,13 @@ function toUtf8Bytes(str, form) {
result[offset++] = (c & 63) | 128; result[offset++] = (c & 63) | 128;
} }
} }
return convert_1.arrayify(result); return bytes_1.arrayify(result);
} }
exports.toUtf8Bytes = toUtf8Bytes; exports.toUtf8Bytes = toUtf8Bytes;
; ;
// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 // http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499
function toUtf8String(bytes) { function toUtf8String(bytes) {
bytes = convert_1.arrayify(bytes); bytes = bytes_1.arrayify(bytes);
var result = ''; var result = '';
var i = 0; var i = 0;
// Invalid bytes are ignored // Invalid bytes are ignored

View File

@ -1,4 +1,4 @@
import { Arrayish } from '../utils/convert'; import { Arrayish } from '../utils/bytes';
import { KeyPair } from '../utils/secp256k1'; import { KeyPair } from '../utils/secp256k1';
export declare class HDNode { export declare class HDNode {
private readonly keyPair; private readonly keyPair;

View File

@ -10,7 +10,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
// See: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki // See: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
// See: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki // See: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
var words_1 = require("./words"); var words_1 = require("./words");
var convert_1 = require("../utils/convert"); var bytes_1 = require("../utils/bytes");
var bignumber_1 = require("../utils/bignumber"); var bignumber_1 = require("../utils/bignumber");
var utf8_1 = require("../utils/utf8"); var utf8_1 = require("../utils/utf8");
var pbkdf2_1 = require("../utils/pbkdf2"); var pbkdf2_1 = require("../utils/pbkdf2");
@ -36,7 +36,7 @@ var HDNode = /** @class */ (function () {
this.keyPair = keyPair; this.keyPair = keyPair;
this.privateKey = keyPair.privateKey; this.privateKey = keyPair.privateKey;
this.publicKey = keyPair.compressedPublicKey; this.publicKey = keyPair.compressedPublicKey;
this.chainCode = convert_1.hexlify(chainCode); this.chainCode = bytes_1.hexlify(chainCode);
this.index = index; this.index = index;
this.depth = depth; this.depth = depth;
this.mnemonic = mnemonic; this.mnemonic = mnemonic;
@ -59,7 +59,7 @@ var HDNode = /** @class */ (function () {
} }
if (index & HardenedBit) { if (index & HardenedBit) {
// Data = 0x00 || ser_256(k_par) // Data = 0x00 || ser_256(k_par)
data.set(convert_1.arrayify(this.privateKey), 1); data.set(bytes_1.arrayify(this.privateKey), 1);
// Hardened path // Hardened path
if (path) { if (path) {
path += "'"; path += "'";
@ -73,11 +73,11 @@ var HDNode = /** @class */ (function () {
for (var i = 24; i >= 0; i -= 8) { for (var i = 24; i >= 0; i -= 8) {
data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff); data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff);
} }
var I = convert_1.arrayify(hmac_1.createSha512Hmac(this.chainCode).update(data).digest()); var I = bytes_1.arrayify(hmac_1.createSha512Hmac(this.chainCode).update(data).digest());
var IL = bignumber_1.bigNumberify(I.slice(0, 32)); var IL = bignumber_1.bigNumberify(I.slice(0, 32));
var IR = I.slice(32); var IR = I.slice(32);
var ki = IL.add(this.keyPair.privateKey).mod(secp256k1_1.N); var ki = IL.add(this.keyPair.privateKey).mod(secp256k1_1.N);
return new HDNode(new secp256k1_1.KeyPair(convert_1.arrayify(ki)), IR, index, this.depth + 1, mnemonic, path); return new HDNode(new secp256k1_1.KeyPair(bytes_1.arrayify(ki)), IR, index, this.depth + 1, mnemonic, path);
}; };
HDNode.prototype.derivePath = function (path) { HDNode.prototype.derivePath = function (path) {
var components = path.split('/'); var components = path.split('/');
@ -114,11 +114,11 @@ var HDNode = /** @class */ (function () {
}()); }());
exports.HDNode = HDNode; exports.HDNode = HDNode;
function _fromSeed(seed, mnemonic) { function _fromSeed(seed, mnemonic) {
var seedArray = convert_1.arrayify(seed); var seedArray = bytes_1.arrayify(seed);
if (seedArray.length < 16 || seedArray.length > 64) { if (seedArray.length < 16 || seedArray.length > 64) {
throw new Error('invalid seed'); throw new Error('invalid seed');
} }
var I = convert_1.arrayify(hmac_1.createSha512Hmac(MasterSecret).update(seedArray).digest()); var I = bytes_1.arrayify(hmac_1.createSha512Hmac(MasterSecret).update(seedArray).digest());
return new HDNode(new secp256k1_1.KeyPair(I.slice(0, 32)), I.slice(32), 0, 0, mnemonic, 'm'); return new HDNode(new secp256k1_1.KeyPair(I.slice(0, 32)), I.slice(32), 0, 0, mnemonic, 'm');
} }
function fromMnemonic(mnemonic) { function fromMnemonic(mnemonic) {
@ -147,7 +147,7 @@ function mnemonicToSeed(mnemonic, password) {
} }
} }
var salt = utf8_1.toUtf8Bytes('mnemonic' + password, utf8_1.UnicodeNormalizationForm.NFKD); var salt = utf8_1.toUtf8Bytes('mnemonic' + password, utf8_1.UnicodeNormalizationForm.NFKD);
return convert_1.hexlify(pbkdf2_1.pbkdf2(utf8_1.toUtf8Bytes(mnemonic, utf8_1.UnicodeNormalizationForm.NFKD), salt, 2048, 64, hmac_1.createSha512Hmac)); return bytes_1.hexlify(pbkdf2_1.pbkdf2(utf8_1.toUtf8Bytes(mnemonic, utf8_1.UnicodeNormalizationForm.NFKD), salt, 2048, 64, hmac_1.createSha512Hmac));
} }
exports.mnemonicToSeed = mnemonicToSeed; exports.mnemonicToSeed = mnemonicToSeed;
function mnemonicToEntropy(mnemonic) { function mnemonicToEntropy(mnemonic) {
@ -155,7 +155,7 @@ function mnemonicToEntropy(mnemonic) {
if ((words.length % 3) !== 0) { if ((words.length % 3) !== 0) {
throw new Error('invalid mnemonic'); throw new Error('invalid mnemonic');
} }
var entropy = convert_1.arrayify(new Uint8Array(Math.ceil(11 * words.length / 8))); var entropy = bytes_1.arrayify(new Uint8Array(Math.ceil(11 * words.length / 8)));
var offset = 0; var offset = 0;
for (var i = 0; i < words.length; i++) { for (var i = 0; i < words.length; i++) {
var index = words_1.getWordIndex(words[i]); var index = words_1.getWordIndex(words[i]);
@ -172,16 +172,16 @@ function mnemonicToEntropy(mnemonic) {
var entropyBits = 32 * words.length / 3; var entropyBits = 32 * words.length / 3;
var checksumBits = words.length / 3; var checksumBits = words.length / 3;
var checksumMask = getUpperMask(checksumBits); var checksumMask = getUpperMask(checksumBits);
var checksum = convert_1.arrayify(sha2_1.sha256(entropy.slice(0, entropyBits / 8)))[0]; var checksum = bytes_1.arrayify(sha2_1.sha256(entropy.slice(0, entropyBits / 8)))[0];
checksum &= checksumMask; checksum &= checksumMask;
if (checksum !== (entropy[entropy.length - 1] & checksumMask)) { if (checksum !== (entropy[entropy.length - 1] & checksumMask)) {
throw new Error('invalid checksum'); throw new Error('invalid checksum');
} }
return convert_1.hexlify(entropy.slice(0, entropyBits / 8)); return bytes_1.hexlify(entropy.slice(0, entropyBits / 8));
} }
exports.mnemonicToEntropy = mnemonicToEntropy; exports.mnemonicToEntropy = mnemonicToEntropy;
function entropyToMnemonic(entropy) { function entropyToMnemonic(entropy) {
entropy = convert_1.arrayify(entropy); entropy = bytes_1.arrayify(entropy);
if ((entropy.length % 4) !== 0 || entropy.length < 16 || entropy.length > 32) { if ((entropy.length % 4) !== 0 || entropy.length < 16 || entropy.length > 32) {
throw new Error('invalid entropy'); throw new Error('invalid entropy');
} }
@ -204,7 +204,7 @@ function entropyToMnemonic(entropy) {
} }
} }
// Compute the checksum bits // Compute the checksum bits
var checksum = convert_1.arrayify(sha2_1.sha256(entropy))[0]; var checksum = bytes_1.arrayify(sha2_1.sha256(entropy))[0];
var checksumBits = entropy.length / 4; var checksumBits = entropy.length / 4;
checksum &= getUpperMask(checksumBits); checksum &= getUpperMask(checksumBits);
// Shift the checksum into the word indices // Shift the checksum into the word indices

View File

@ -1,4 +1,4 @@
import { Arrayish } from '../utils/convert'; import { Arrayish } from '../utils/bytes';
import { SigningKey } from './signing-key'; import { SigningKey } from './signing-key';
export interface ProgressCallback { export interface ProgressCallback {
(percent: number): void; (percent: number): void;

View File

@ -11,7 +11,7 @@ var aes = require("aes-js");
var scrypt = require("scrypt-js"); var scrypt = require("scrypt-js");
var uuid = require("uuid"); var uuid = require("uuid");
var address_1 = require("../utils/address"); var address_1 = require("../utils/address");
var convert_1 = require("../utils/convert"); var bytes_1 = require("../utils/bytes");
var hmac = __importStar(require("../utils/hmac")); var hmac = __importStar(require("../utils/hmac"));
var pbkdf2_1 = require("../utils/pbkdf2"); var pbkdf2_1 = require("../utils/pbkdf2");
var keccak256_1 = require("../utils/keccak256"); var keccak256_1 = require("../utils/keccak256");
@ -25,7 +25,7 @@ function looseArrayify(hexString) {
if (typeof (hexString) === 'string' && hexString.substring(0, 2) !== '0x') { if (typeof (hexString) === 'string' && hexString.substring(0, 2) !== '0x') {
hexString = '0x' + hexString; hexString = '0x' + hexString;
} }
return convert_1.arrayify(hexString); return bytes_1.arrayify(hexString);
} }
function zpad(value, length) { function zpad(value, length) {
value = String(value); value = String(value);
@ -38,7 +38,7 @@ function getPassword(password) {
if (typeof (password) === 'string') { if (typeof (password) === 'string') {
return utf8_1.toUtf8Bytes(password, utf8_1.UnicodeNormalizationForm.NFKC); return utf8_1.toUtf8Bytes(password, utf8_1.UnicodeNormalizationForm.NFKC);
} }
return convert_1.arrayify(password); return bytes_1.arrayify(password);
} }
// Search an Object and its children recursively, caselessly. // Search an Object and its children recursively, caselessly.
function searchPath(object, path) { function searchPath(object, path) {
@ -103,7 +103,7 @@ function decryptCrowdsale(json, password) {
var encryptedSeed = encseed.slice(16); var encryptedSeed = encseed.slice(16);
// Decrypt the seed // Decrypt the seed
var aesCbc = new aes.ModeOfOperation.cbc(key, iv); var aesCbc = new aes.ModeOfOperation.cbc(key, iv);
var seed = convert_1.arrayify(aesCbc.decrypt(encryptedSeed)); var seed = bytes_1.arrayify(aesCbc.decrypt(encryptedSeed));
seed = aes.padding.pkcs7.strip(seed); seed = aes.padding.pkcs7.strip(seed);
// This wallet format is weird... Convert the binary encoded hex to a string. // This wallet format is weird... Convert the binary encoded hex to a string.
var seedHex = ''; var seedHex = '';
@ -128,16 +128,16 @@ function decrypt(json, password, progressCallback) {
var iv = looseArrayify(searchPath(data, 'crypto/cipherparams/iv')); var iv = looseArrayify(searchPath(data, 'crypto/cipherparams/iv'));
var counter = new aes.Counter(iv); var counter = new aes.Counter(iv);
var aesCtr = new aes.ModeOfOperation.ctr(key, counter); var aesCtr = new aes.ModeOfOperation.ctr(key, counter);
return convert_1.arrayify(aesCtr.decrypt(ciphertext)); return bytes_1.arrayify(aesCtr.decrypt(ciphertext));
} }
return null; return null;
}; };
var computeMAC = function (derivedHalf, ciphertext) { var computeMAC = function (derivedHalf, ciphertext) {
return keccak256_1.keccak256(convert_1.concat([derivedHalf, ciphertext])); return keccak256_1.keccak256(bytes_1.concat([derivedHalf, ciphertext]));
}; };
var getSigningKey = function (key, reject) { var getSigningKey = function (key, reject) {
var ciphertext = looseArrayify(searchPath(data, 'crypto/ciphertext')); var ciphertext = looseArrayify(searchPath(data, 'crypto/ciphertext'));
var computedMAC = convert_1.hexlify(computeMAC(key.slice(16, 32), ciphertext)).substring(2); var computedMAC = bytes_1.hexlify(computeMAC(key.slice(16, 32), ciphertext)).substring(2);
if (computedMAC !== searchPath(data, 'crypto/mac').toLowerCase()) { if (computedMAC !== searchPath(data, 'crypto/mac').toLowerCase()) {
reject(new Error('invalid password')); reject(new Error('invalid password'));
return null; return null;
@ -160,10 +160,10 @@ function decrypt(json, password, progressCallback) {
var mnemonicCounter = new aes.Counter(mnemonicIv); var mnemonicCounter = new aes.Counter(mnemonicIv);
var mnemonicAesCtr = new aes.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter); var mnemonicAesCtr = new aes.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter);
var path = searchPath(data, 'x-ethers/path') || defaultPath; var path = searchPath(data, 'x-ethers/path') || defaultPath;
var entropy = convert_1.arrayify(mnemonicAesCtr.decrypt(mnemonicCiphertext)); var entropy = bytes_1.arrayify(mnemonicAesCtr.decrypt(mnemonicCiphertext));
var mnemonic = HDNode.entropyToMnemonic(entropy); var mnemonic = HDNode.entropyToMnemonic(entropy);
var node = HDNode.fromMnemonic(mnemonic).derivePath(path); var node = HDNode.fromMnemonic(mnemonic).derivePath(path);
if (node.privateKey != convert_1.hexlify(privateKey)) { if (node.privateKey != bytes_1.hexlify(privateKey)) {
reject(new Error('mnemonic mismatch')); reject(new Error('mnemonic mismatch'));
return null; return null;
} }
@ -199,7 +199,7 @@ function decrypt(json, password, progressCallback) {
reject(error); reject(error);
} }
else if (key) { else if (key) {
key = convert_1.arrayify(key); key = bytes_1.arrayify(key);
var signingKey = getSigningKey(key, reject); var signingKey = getSigningKey(key, reject);
if (!signingKey) { if (!signingKey) {
return; return;
@ -264,10 +264,10 @@ function encrypt(privateKey, password, options, progressCallback) {
// Check the private key // Check the private key
var privateKeyBytes = null; var privateKeyBytes = null;
if (privateKey instanceof signing_key_1.SigningKey) { if (privateKey instanceof signing_key_1.SigningKey) {
privateKeyBytes = convert_1.arrayify(privateKey.privateKey); privateKeyBytes = bytes_1.arrayify(privateKey.privateKey);
} }
else { else {
privateKeyBytes = convert_1.arrayify(privateKey); privateKeyBytes = bytes_1.arrayify(privateKey);
} }
if (privateKeyBytes.length !== 32) { if (privateKeyBytes.length !== 32) {
throw new Error('invalid private key'); throw new Error('invalid private key');
@ -285,7 +285,7 @@ function encrypt(privateKey, password, options, progressCallback) {
} }
} }
if (entropy) { if (entropy) {
entropy = convert_1.arrayify(entropy); entropy = bytes_1.arrayify(entropy);
} }
var path = options.path; var path = options.path;
if (entropy && !path) { if (entropy && !path) {
@ -298,7 +298,7 @@ function encrypt(privateKey, password, options, progressCallback) {
// Check/generate the salt // Check/generate the salt
var salt = options.salt; var salt = options.salt;
if (salt) { if (salt) {
salt = convert_1.arrayify(salt); salt = bytes_1.arrayify(salt);
} }
else { else {
salt = random_bytes_1.randomBytes(32); salt = random_bytes_1.randomBytes(32);
@ -307,7 +307,7 @@ function encrypt(privateKey, password, options, progressCallback) {
// Override initialization vector // Override initialization vector
var iv = null; var iv = null;
if (options.iv) { if (options.iv) {
iv = convert_1.arrayify(options.iv); iv = bytes_1.arrayify(options.iv);
if (iv.length !== 16) { if (iv.length !== 16) {
throw new Error('invalid iv'); throw new Error('invalid iv');
} }
@ -318,7 +318,7 @@ function encrypt(privateKey, password, options, progressCallback) {
// Override the uuid // Override the uuid
var uuidRandom = options.uuid; var uuidRandom = options.uuid;
if (uuidRandom) { if (uuidRandom) {
uuidRandom = convert_1.arrayify(uuidRandom); uuidRandom = bytes_1.arrayify(uuidRandom);
if (uuidRandom.length !== 16) { if (uuidRandom.length !== 16) {
throw new Error('invalid uuid'); throw new Error('invalid uuid');
} }
@ -349,7 +349,7 @@ function encrypt(privateKey, password, options, progressCallback) {
reject(error); reject(error);
} }
else if (key) { else if (key) {
key = convert_1.arrayify(key); key = bytes_1.arrayify(key);
// This will be used to encrypt the wallet (as per Web3 secret storage) // This will be used to encrypt the wallet (as per Web3 secret storage)
var derivedKey = key.slice(0, 16); var derivedKey = key.slice(0, 16);
var macPrefix = key.slice(16, 32); var macPrefix = key.slice(16, 32);
@ -360,9 +360,9 @@ function encrypt(privateKey, password, options, progressCallback) {
// Encrypt the private key // Encrypt the private key
var counter = new aes.Counter(iv); var counter = new aes.Counter(iv);
var aesCtr = new aes.ModeOfOperation.ctr(derivedKey, counter); var aesCtr = new aes.ModeOfOperation.ctr(derivedKey, counter);
var ciphertext = convert_1.arrayify(aesCtr.encrypt(privateKeyBytes)); var ciphertext = bytes_1.arrayify(aesCtr.encrypt(privateKeyBytes));
// Compute the message authentication code, used to check the password // Compute the message authentication code, used to check the password
var mac = keccak256_1.keccak256(convert_1.concat([macPrefix, ciphertext])); var mac = keccak256_1.keccak256(bytes_1.concat([macPrefix, ciphertext]));
// See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
var data = { var data = {
address: address.substring(2).toLowerCase(), address: address.substring(2).toLowerCase(),
@ -371,12 +371,12 @@ function encrypt(privateKey, password, options, progressCallback) {
Crypto: { Crypto: {
cipher: 'aes-128-ctr', cipher: 'aes-128-ctr',
cipherparams: { cipherparams: {
iv: convert_1.hexlify(iv).substring(2), iv: bytes_1.hexlify(iv).substring(2),
}, },
ciphertext: convert_1.hexlify(ciphertext).substring(2), ciphertext: bytes_1.hexlify(ciphertext).substring(2),
kdf: 'scrypt', kdf: 'scrypt',
kdfparams: { kdfparams: {
salt: convert_1.hexlify(salt).substring(2), salt: bytes_1.hexlify(salt).substring(2),
n: N, n: N,
dklen: 32, dklen: 32,
p: p, p: p,
@ -390,7 +390,7 @@ function encrypt(privateKey, password, options, progressCallback) {
var mnemonicIv = random_bytes_1.randomBytes(16); var mnemonicIv = random_bytes_1.randomBytes(16);
var mnemonicCounter = new aes.Counter(mnemonicIv); var mnemonicCounter = new aes.Counter(mnemonicIv);
var mnemonicAesCtr = new aes.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter); var mnemonicAesCtr = new aes.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter);
var mnemonicCiphertext = convert_1.arrayify(mnemonicAesCtr.encrypt(entropy)); var mnemonicCiphertext = bytes_1.arrayify(mnemonicAesCtr.encrypt(entropy));
var now = new Date(); var now = new Date();
var timestamp = (now.getUTCFullYear() + '-' + var timestamp = (now.getUTCFullYear() + '-' +
zpad(now.getUTCMonth() + 1, 2) + '-' + zpad(now.getUTCMonth() + 1, 2) + '-' +
@ -401,8 +401,8 @@ function encrypt(privateKey, password, options, progressCallback) {
data['x-ethers'] = { data['x-ethers'] = {
client: client, client: client,
gethFilename: ('UTC--' + timestamp + '--' + data.address), gethFilename: ('UTC--' + timestamp + '--' + data.address),
mnemonicCounter: convert_1.hexlify(mnemonicIv).substring(2), mnemonicCounter: bytes_1.hexlify(mnemonicIv).substring(2),
mnemonicCiphertext: convert_1.hexlify(mnemonicCiphertext).substring(2), mnemonicCiphertext: bytes_1.hexlify(mnemonicCiphertext).substring(2),
version: "0.1" version: "0.1"
}; };
} }

View File

@ -1,4 +1,4 @@
import { Arrayish } from '../utils/convert'; import { Arrayish } from '../utils/bytes';
import { HDNode } from './hdnode'; import { HDNode } from './hdnode';
import { Signature } from '../utils/secp256k1'; import { Signature } from '../utils/secp256k1';
export declare class SigningKey { export declare class SigningKey {

View File

@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
* *
*/ */
var address_1 = require("../utils/address"); var address_1 = require("../utils/address");
var convert_1 = require("../utils/convert"); var bytes_1 = require("../utils/bytes");
var hdnode_1 = require("./hdnode"); var hdnode_1 = require("./hdnode");
var keccak256_1 = require("../utils/keccak256"); var keccak256_1 = require("../utils/keccak256");
var properties_1 = require("../utils/properties"); var properties_1 = require("../utils/properties");
@ -19,10 +19,10 @@ var SigningKey = /** @class */ (function () {
if (privateKey instanceof hdnode_1.HDNode) { if (privateKey instanceof hdnode_1.HDNode) {
properties_1.defineReadOnly(this, 'mnemonic', privateKey.mnemonic); properties_1.defineReadOnly(this, 'mnemonic', privateKey.mnemonic);
properties_1.defineReadOnly(this, 'path', privateKey.path); properties_1.defineReadOnly(this, 'path', privateKey.path);
privateKeyBytes = convert_1.arrayify(privateKey.privateKey); privateKeyBytes = bytes_1.arrayify(privateKey.privateKey);
} }
else { else {
privateKeyBytes = convert_1.arrayify(privateKey); privateKeyBytes = bytes_1.arrayify(privateKey);
} }
try { try {
if (privateKeyBytes.length !== 32) { if (privateKeyBytes.length !== 32) {
@ -39,7 +39,7 @@ var SigningKey = /** @class */ (function () {
} }
errors.throwError('invalid private key', error.code, params); errors.throwError('invalid private key', error.code, params);
} }
properties_1.defineReadOnly(this, 'privateKey', convert_1.hexlify(privateKeyBytes)); properties_1.defineReadOnly(this, 'privateKey', bytes_1.hexlify(privateKeyBytes));
properties_1.defineReadOnly(this, 'keyPair', new secp256k1_1.KeyPair(privateKeyBytes)); properties_1.defineReadOnly(this, 'keyPair', new secp256k1_1.KeyPair(privateKeyBytes));
properties_1.defineReadOnly(this, 'publicKey', this.keyPair.publicKey); properties_1.defineReadOnly(this, 'publicKey', this.keyPair.publicKey);
properties_1.defineReadOnly(this, 'address', computeAddress(this.keyPair.publicKey)); properties_1.defineReadOnly(this, 'address', computeAddress(this.keyPair.publicKey));

View File

@ -3,7 +3,7 @@ import { ProgressCallback } from './secret-storage';
import { SigningKey } from './signing-key'; import { SigningKey } from './signing-key';
import { BlockTag, Provider, TransactionRequest, TransactionResponse } from '../providers/provider'; import { BlockTag, Provider, TransactionRequest, TransactionResponse } from '../providers/provider';
import { BigNumber, BigNumberish } from '../utils/bignumber'; import { BigNumber, BigNumberish } from '../utils/bignumber';
import { Arrayish } from '../utils/convert'; import { Arrayish } from '../utils/bytes';
import { UnsignedTransaction } from '../utils/transaction'; import { UnsignedTransaction } from '../utils/transaction';
export interface Signer { export interface Signer {
address?: string; address?: string;

View File

@ -14,7 +14,7 @@ var scrypt_js_1 = __importDefault(require("scrypt-js"));
var hdnode_1 = require("./hdnode"); var hdnode_1 = require("./hdnode");
var secretStorage = __importStar(require("./secret-storage")); var secretStorage = __importStar(require("./secret-storage"));
var signing_key_1 = require("./signing-key"); var signing_key_1 = require("./signing-key");
var convert_1 = require("../utils/convert"); var bytes_1 = require("../utils/bytes");
var keccak256_1 = require("../utils/keccak256"); var keccak256_1 = require("../utils/keccak256");
var properties_1 = require("../utils/properties"); var properties_1 = require("../utils/properties");
var random_bytes_1 = require("../utils/random-bytes"); var random_bytes_1 = require("../utils/random-bytes");
@ -128,7 +128,7 @@ var Wallet = /** @class */ (function () {
}); });
}; };
Wallet.hashMessage = function (message) { Wallet.hashMessage = function (message) {
var payload = convert_1.concat([ var payload = bytes_1.concat([
utf8_1.toUtf8Bytes('\x19Ethereum Signed Message:\n'), utf8_1.toUtf8Bytes('\x19Ethereum Signed Message:\n'),
utf8_1.toUtf8Bytes(String(message.length)), utf8_1.toUtf8Bytes(String(message.length)),
((typeof (message) === 'string') ? utf8_1.toUtf8Bytes(message) : message) ((typeof (message) === 'string') ? utf8_1.toUtf8Bytes(message) : message)
@ -138,10 +138,10 @@ var Wallet = /** @class */ (function () {
Wallet.prototype.signMessage = function (message) { Wallet.prototype.signMessage = function (message) {
var signingKey = new signing_key_1.SigningKey(this.privateKey); var signingKey = new signing_key_1.SigningKey(this.privateKey);
var sig = signingKey.signDigest(Wallet.hashMessage(message)); var sig = signingKey.signDigest(Wallet.hashMessage(message));
return (convert_1.hexZeroPad(sig.r, 32) + convert_1.hexZeroPad(sig.s, 32).substring(2) + (sig.recoveryParam ? '1c' : '1b')); return (bytes_1.hexZeroPad(sig.r, 32) + bytes_1.hexZeroPad(sig.s, 32).substring(2) + (sig.recoveryParam ? '1c' : '1b'));
}; };
Wallet.verifyMessage = function (message, signature) { Wallet.verifyMessage = function (message, signature) {
signature = convert_1.hexlify(signature); signature = bytes_1.hexlify(signature);
if (signature.length != 132) { if (signature.length != 132) {
throw new Error('invalid signature'); throw new Error('invalid signature');
} }
@ -189,7 +189,7 @@ var Wallet = /** @class */ (function () {
options = {}; options = {};
} }
if (options.extraEntropy) { if (options.extraEntropy) {
entropy = convert_1.arrayify(keccak256_1.keccak256(convert_1.concat([entropy, options.extraEntropy])).substring(0, 34)); entropy = bytes_1.arrayify(keccak256_1.keccak256(bytes_1.concat([entropy, options.extraEntropy])).substring(0, 34));
} }
var mnemonic = hdnode_1.entropyToMnemonic(entropy); var mnemonic = hdnode_1.entropyToMnemonic(entropy);
return Wallet.fromMnemonic(mnemonic, options.path); return Wallet.fromMnemonic(mnemonic, options.path);
@ -244,13 +244,13 @@ var Wallet = /** @class */ (function () {
username = utf8_1.toUtf8Bytes(username, utf8_1.UnicodeNormalizationForm.NFKC); username = utf8_1.toUtf8Bytes(username, utf8_1.UnicodeNormalizationForm.NFKC);
} }
else { else {
username = convert_1.arrayify(username); username = bytes_1.arrayify(username);
} }
if (typeof (password) === 'string') { if (typeof (password) === 'string') {
password = utf8_1.toUtf8Bytes(password, utf8_1.UnicodeNormalizationForm.NFKC); password = utf8_1.toUtf8Bytes(password, utf8_1.UnicodeNormalizationForm.NFKC);
} }
else { else {
password = convert_1.arrayify(password); password = bytes_1.arrayify(password);
} }
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
scrypt_js_1.default(password, username, (1 << 18), 8, 1, 32, function (error, progress, key) { scrypt_js_1.default(password, username, (1 << 18), 8, 1, 32, function (error, progress, key) {
@ -258,7 +258,7 @@ var Wallet = /** @class */ (function () {
reject(error); reject(error);
} }
else if (key) { else if (key) {
resolve(new Wallet(convert_1.hexlify(key))); resolve(new Wallet(bytes_1.hexlify(key)));
} }
else if (progressCallback) { else if (progressCallback) {
return progressCallback(progress); return progressCallback(progress);