-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcosmoskeypair.js
253 lines (220 loc) · 7.75 KB
/
cosmoskeypair.js
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
'use strict';
const Codec = require("./codec.js");
const Sha256 = require("sha256");
const RIPEMD160 = require('ripemd160');
const Bip39 = require('bip39');
const Random = require('randombytes');
const Secp256k1 = require('secp256k1');
const BN = require("bn");
const Amino = require('./amino.js');
const Config = {
bip39Path: "44'/118'/0'/0/0",
amino: {
signature: "tendermint/SignatureSecp256k1",
pubKey: "tendermint/PubKeySecp256k1"
},
bech32: {
accAddr: "cosmos",
valAddr: "cosmosvaloper",
accPub: "cosmospub"
}
}
class CosmosKeypair {
static getPrivateKeyFromSecret(mnemonicS) {
let seed = Bip39.mnemonicToSeed(mnemonicS);
let master = Hd.ComputeMastersFromSeed(seed);
let derivedPriv = Hd.DerivePrivateKeyForPath(master.secret,master.chainCode,Config.bip39Path);
return derivedPriv;
}
static sign(private_key, msg) {
//将签名字符串使用Sha256构造32位byte数组
let sigByte = Buffer.from(JSON.stringify(msg));
let sig32 = Buffer.from(Sha256(sigByte,{ asBytes: true }));
//console.log("sigByte: ", JSON.stringify(sigByte).replace(/,/g , " ")) // IT MAKES SENSE TO SHOW THIS LOG IF SIGNATURE IS WRONG
//对数据签名
let prikeyArr = Buffer.from(new Uint8Array(Codec.Hex.hexToBytes(private_key)));
let sig = Secp256k1.sign(sig32,prikeyArr);
//let signature = Buffer.from(Hd.Serialize(sig.signature));
return Array.from(sig.signature)
}
static getAddress(publicKey) {
if (publicKey.length > 33){
//去掉amino编码前缀
publicKey = publicKey.slice(5,publicKey.length)
}
let hmac = Sha256(publicKey);
let b = Buffer.from(Codec.Hex.hexToBytes(hmac));
let addr = new RIPEMD160().update(b);
return addr.digest('hex').toUpperCase();
}
static hasRepeatElement(target,splitChar){
if (!(target instanceof Array)){
if (this.isEmpty(splitChar)){
throw new Error("split char is empty");
}
target = target.split(splitChar)
}
let srcLen = target.length;
let eSet = new Set(target);
return !(srcLen == eSet.size)
}
static isEmpty(obj) {
switch (typeof obj) {
case "undefined": {
return true
}
case "string": {
return obj.length === 0
}
case "number": {
return obj === 0
}
case "object": {
if (obj == null) {
return true
} else if (Array.isArray(obj)) {
return obj.length === 0
} else {
return Object.keys(obj).length === 0
}
}
}
}
static create(language) {
//生成24位助记词
let entropySize = 24 * 11 - 8;
let entropy = Random(entropySize / 8);
let mnemonicS = Bip39.entropyToMnemonic(entropy,language);
while (this.hasRepeatElement(mnemonicS," ")){
entropy = Random(entropySize / 8);
mnemonicS = Bip39.entropyToMnemonic(entropy,language);
}
//生成私钥
let secretKey = this.getPrivateKeyFromSecret(mnemonicS);
//构造公钥
let pubKey = Secp256k1.publicKeyCreate(secretKey);
pubKey = Amino.MarshalBinary(Config.amino.pubKey,pubKey);
return {
"secret": mnemonicS,
"address": this.getAddress(pubKey),
"privateKey": Codec.Hex.bytesToHex(secretKey),
"publicKey": Codec.Hex.bytesToHex(pubKey)
};
}
static recover(mnemonic,language){
this.checkSeed(mnemonic,language);
//生成私钥
let secretKey = this.getPrivateKeyFromSecret(mnemonic);
//构造公钥
let pubKey = Secp256k1.publicKeyCreate(secretKey);
pubKey = Amino.MarshalBinary(Config.amino.pubKey,pubKey);
return {
"secret": mnemonic,
"address": this.getAddress(pubKey),
"privateKey": Codec.Hex.bytesToHex(secretKey),
"publicKey": Codec.Hex.bytesToHex(pubKey)
};
}
static checkSeed(mnemonic,language){
const seed = mnemonic.split(" ");
if(seed.length != 12 && seed.length != 24){
throw new Error("seed length must be equal 12 or 24");
}
if (!Bip39.validateMnemonic(mnemonic,language)){
throw new Error("seed is invalid");
}
}
static import(secretKey){
let secretBytes = Buffer.from(secretKey,"hex");
//构造公钥
let pubKey = Secp256k1.publicKeyCreate(secretBytes);
//pubKey = Amino.MarshalBinary(Config.amino.pubKey,pubKey); // manually removed
return {
"address": this.getAddress(pubKey),
"privateKey": secretKey,
"publicKey": Codec.Hex.bytesToHex(pubKey)
};
}
static isValidAddress(address) {
let prefix = Config.bech32.accAddr;
return Codec.Bech32.isBech32(prefix,address);
}
static isValidPrivate(privateKey) {
return /^[0-9a-fA-F]{64}$/i.test(privateKey);
}
}
class Hd {
static ComputeMastersFromSeed(seed) {
let masterSecret = Buffer.from("Bitcoin seed");
let master = Hd.I64(masterSecret,seed);
return master
}
static DerivePrivateKeyForPath(privKeyBytes, chainCode, path) {
let data = privKeyBytes;
let parts = path.split("/");
parts.forEach(function (part) {
let harden = part.slice(part.length-1,part.length) === "'";
if (harden) {
part = part.slice(0,part.length -1);
}
let idx = parseInt(part);
let json = Hd.DerivePrivateKey(data, chainCode, idx, harden);
data = json.data;
chainCode = json.chainCode;
});
let derivedKey = data;
return derivedKey
}
static I64(key , data) {
let createHmac = require('create-hmac');
let hmac = createHmac('sha512', key);
hmac.update(data); //optional encoding parameter
let i = hmac.digest(); // synchronously get result with optional encoding parameter
return {
secret : i.slice(0,32),
chainCode : i.slice(32,i.length)
}
}
static DerivePrivateKey(privKeyBytes, chainCode, index, harden) {
let data;
let indexBuffer = Buffer.from([index]);
if(harden){
let c = new BN(index).or(new BN(0x80000000));
indexBuffer = c.toBuffer();
let privKeyBuffer = Buffer.from(privKeyBytes);
data = Buffer.from([0]);
data = Buffer.concat([data,privKeyBuffer]);
}else{
const pubKey =Secp256k1.publicKeyCreate(privKeyBytes);
if (index ==0){
indexBuffer = Buffer.from([0,0,0,0]);
}
data = pubKey
}
data = Buffer.concat([data,indexBuffer]);
let i64P = Hd.I64(chainCode, Uint8Array.from(data));
let aInt = new BN(privKeyBytes);
let bInt = new BN(i64P.secret);
let x = Hd.AddScalars(aInt, bInt);
return {
data : x,
chainCode : i64P.chainCode
}
}
static AddScalars(a, b) {
let c = a.add(b);
const bn = require('secp256k1/lib/js/bn');
let n = bn.n.toBuffer();
let x = c.mod(new BN(n)).toBuffer();
let buf = Buffer.alloc(32);
buf.fill(x,32 - x.length);
return buf
}
static Serialize(sig) {
const sigObj = {r: sig.slice(0, 32), s: sig.slice(32, 64)};
const SignatureFun = require('elliptic/lib/elliptic/ec/signature');
let signature = new SignatureFun(sigObj);
return signature.toDER();
}
}
module.exports = CosmosKeypair;