-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
index.ts
174 lines (139 loc) · 6.95 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"use strict";
import { getAddress } from "@ethersproject/address";
import { Provider, TransactionRequest } from "@ethersproject/abstract-provider";
import { ExternallyOwnedAccount, Signer } from "@ethersproject/abstract-signer";
import { arrayify, Bytes, BytesLike, concat, hexDataSlice, isHexString, joinSignature, SignatureLike } from "@ethersproject/bytes";
import { hashMessage } from "@ethersproject/hash";
import { defaultPath, HDNode, entropyToMnemonic, Mnemonic } from "@ethersproject/hdnode";
import { keccak256 } from "@ethersproject/keccak256";
import { defineReadOnly, resolveProperties } from "@ethersproject/properties";
import { randomBytes } from "@ethersproject/random";
import { SigningKey } from "@ethersproject/signing-key";
import { decryptJsonWallet, decryptJsonWalletSync, encryptKeystore, ProgressCallback } from "@ethersproject/json-wallets";
import { computeAddress, recoverAddress, serialize, UnsignedTransaction } from "@ethersproject/transactions";
import { Wordlist } from "@ethersproject/wordlists";
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
function isAccount(value: any): value is ExternallyOwnedAccount {
return (value != null && isHexString(value.privateKey, 32) && value.address != null);
}
function hasMnemonic(value: any): value is { mnemonic: Mnemonic } {
const mnemonic = value.mnemonic;
return (mnemonic && mnemonic.phrase);
}
export class Wallet extends Signer implements ExternallyOwnedAccount {
readonly address: string;
readonly provider: Provider;
// Wrapping the _signingKey and _mnemonic in a getter function prevents
// leaking the private key in console.log; still, be careful! :)
readonly _signingKey: () => SigningKey;
readonly _mnemonic: () => Mnemonic;
constructor(privateKey: BytesLike | ExternallyOwnedAccount | SigningKey, provider?: Provider) {
logger.checkNew(new.target, Wallet);
super();
if (isAccount(privateKey)) {
const signingKey = new SigningKey(privateKey.privateKey);
defineReadOnly(this, "_signingKey", () => signingKey);
defineReadOnly(this, "address", computeAddress(this.publicKey));
if (this.address !== getAddress(privateKey.address)) {
logger.throwArgumentError("privateKey/address mismatch", "privateKey", "[REDACTED]");
}
if (hasMnemonic(privateKey)) {
const srcMnemonic = privateKey.mnemonic;
defineReadOnly(this, "_mnemonic", () => (
{
phrase: srcMnemonic.phrase,
path: srcMnemonic.path || defaultPath,
locale: srcMnemonic.locale || "en"
}
));
const mnemonic = this.mnemonic;
const node = HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path);
if (computeAddress(node.privateKey) !== this.address) {
logger.throwArgumentError("mnemonic/address mismatch", "privateKey", "[REDACTED]");
}
} else {
defineReadOnly(this, "_mnemonic", (): Mnemonic => null);
}
} else {
if (SigningKey.isSigningKey(privateKey)) {
if (privateKey.curve !== "secp256k1") {
logger.throwArgumentError("unsupported curve; must be secp256k1", "privateKey", "[REDACTED]");
}
defineReadOnly(this, "_signingKey", () => privateKey);
} else {
const signingKey = new SigningKey(privateKey);
defineReadOnly(this, "_signingKey", () => signingKey);
}
defineReadOnly(this, "_mnemonic", (): Mnemonic => null);
defineReadOnly(this, "address", computeAddress(this.publicKey));
}
if (provider && !Provider.isProvider(provider)) {
logger.throwArgumentError("invalid provider", "provider", provider);
}
defineReadOnly(this, "provider", provider || null);
}
get mnemonic(): Mnemonic { return this._mnemonic(); }
get privateKey(): string { return this._signingKey().privateKey; }
get publicKey(): string { return this._signingKey().publicKey; }
getAddress(): Promise<string> {
return Promise.resolve(this.address);
}
connect(provider: Provider): Wallet {
return new Wallet(this, provider);
}
signTransaction(transaction: TransactionRequest): Promise<string> {
return resolveProperties(transaction).then((tx) => {
if (tx.from != null) {
if (getAddress(tx.from) !== this.address) {
throw new Error("transaction from address mismatch");
}
delete tx.from;
}
const signature = this._signingKey().signDigest(keccak256(serialize(<UnsignedTransaction>tx)));
return serialize(<UnsignedTransaction>tx, signature);
});
}
signMessage(message: Bytes | string): Promise<string> {
return Promise.resolve(joinSignature(this._signingKey().signDigest(hashMessage(message))));
}
encrypt(password: Bytes | string, options?: any, progressCallback?: ProgressCallback): Promise<string> {
if (typeof(options) === "function" && !progressCallback) {
progressCallback = options;
options = {};
}
if (progressCallback && typeof(progressCallback) !== "function") {
throw new Error("invalid callback");
}
if (!options) { options = {}; }
return encryptKeystore(this, password, options, progressCallback);
}
/**
* Static methods to create Wallet instances.
*/
static createRandom(options?: any): Wallet {
let entropy: Uint8Array = randomBytes(16);
if (!options) { options = { }; }
if (options.extraEntropy) {
entropy = arrayify(hexDataSlice(keccak256(concat([ entropy, options.extraEntropy ])), 0, 16));
}
const mnemonic = entropyToMnemonic(entropy, options.locale);
return Wallet.fromMnemonic(mnemonic, options.path, options.locale);
}
static fromEncryptedJson(json: string, password: Bytes | string, progressCallback?: ProgressCallback): Promise<Wallet> {
return decryptJsonWallet(json, password, progressCallback).then((account) => {
return new Wallet(account);
});
}
static fromEncryptedJsonSync(json: string, password: Bytes | string): Wallet {
return new Wallet(decryptJsonWalletSync(json, password));
}
static fromMnemonic(mnemonic: string, path?: string, wordlist?: Wordlist): Wallet {
if (!path) { path = defaultPath; }
return new Wallet(HDNode.fromMnemonic(mnemonic, null, wordlist).derivePath(path));
}
}
export function verifyMessage(message: Bytes | string, signature: SignatureLike): string {
return recoverAddress(hashMessage(message), signature);
}