-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcfdcore_key.cpp
553 lines (466 loc) · 15.9 KB
/
cfdcore_key.cpp
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
// Copyright 2020 CryptoGarage
/**
* @file cfdcore_key.cpp
*
* @brief definition for Pubkey/Privkey class
*/
#include "cfdcore/cfdcore_key.h"
#include <string>
#include <vector>
#include "cfdcore/cfdcore_bytedata.h"
#include "cfdcore/cfdcore_exception.h"
#include "cfdcore/cfdcore_logger.h"
#include "cfdcore/cfdcore_transaction_common.h"
#include "cfdcore/cfdcore_util.h"
#include "cfdcore_wally_util.h" // NOLINT
namespace cfd {
namespace core {
using logger::warn;
// ----------------------------------------------------------------------------
// Public Key
// ----------------------------------------------------------------------------
Pubkey::Pubkey() : data_() {}
bool Pubkey::IsValid(const ByteData &byte_data) {
const std::vector<uint8_t> &buffer = byte_data.GetBytes();
if (buffer.size() > 0) {
uint8_t header = buffer[0];
if (header == 0x02 || header == 0x03) {
return buffer.size() == Pubkey::kCompressedPubkeySize;
} else if (header == 0x04 || header == 0x06 || header == 0x07) {
return buffer.size() == Pubkey::kPubkeySize;
}
}
return false;
}
Pubkey::Pubkey(ByteData byte_data) : data_(byte_data) {
if (!Pubkey::IsValid(data_)) {
warn(CFD_LOG_SOURCE, "Invalid Pubkey data. hex={}.", data_.GetHex());
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Invalid Pubkey data.");
}
}
Pubkey::Pubkey(const std::string &hex_string) : Pubkey(ByteData(hex_string)) {
// do nothing
}
std::string Pubkey::GetHex() const { return data_.GetHex(); }
ByteData Pubkey::GetData() const { return data_.GetBytes(); }
bool Pubkey::IsCompress() const {
if (!data_.IsEmpty()) {
uint8_t header = data_.GetHeadData();
if (header == 0x02 || header == 0x03) {
return true;
} else if (header == 0x04 || header == 0x06 || header == 0x07) {
return false;
}
}
return false;
}
bool Pubkey::IsParity() const { return (data_.GetHeadData() == 0x03); }
bool Pubkey::IsValid() const { return IsValid(data_); }
bool Pubkey::Equals(const Pubkey &pubkey) const {
return data_.Equals(pubkey.data_);
}
ByteData Pubkey::GetFingerprint(uint32_t get_size) const {
if ((get_size == 0) || (get_size > kByteData160Length)) {
warn(CFD_LOG_SOURCE, "Invalid fingerprint size: {}.", get_size);
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Invalid fingerprint size.");
}
ByteData data;
if (IsCompress()) {
data = data_;
} else {
data = Compress().data_;
}
auto data160 = HashUtil::Hash160(data);
auto bytes = data160.GetBytes();
return ByteData(bytes.data(), get_size);
}
Pubkey Pubkey::CombinePubkey(const std::vector<Pubkey> &pubkeys) {
std::vector<ByteData> data_list;
for (const auto &pubkey : pubkeys) {
data_list.push_back(pubkey.GetData());
}
return Pubkey(WallyUtil::CombinePubkeySecp256k1Ec(data_list));
}
Pubkey Pubkey::CombinePubkey(const Pubkey &pubkey, const Pubkey &message_key) {
std::vector<ByteData> data_list;
data_list.push_back(pubkey.GetData());
data_list.push_back(message_key.GetData());
return Pubkey(WallyUtil::CombinePubkeySecp256k1Ec(data_list));
}
Pubkey Pubkey::CreateTweakAdd(const ByteData256 &tweak) const {
ByteData tweak_added = WallyUtil::AddTweakPubkey(data_, tweak);
return Pubkey(tweak_added);
}
Pubkey Pubkey::CreateTweakMul(const ByteData256 &tweak) const {
ByteData tweak_muled = WallyUtil::MulTweakPubkey(data_, tweak);
return Pubkey(tweak_muled);
}
Pubkey Pubkey::CreateNegate() const {
ByteData negated = WallyUtil::NegatePubkey(data_);
return Pubkey(negated);
}
Pubkey Pubkey::Compress() const {
if (IsCompress()) {
return *this;
}
ByteData compress_data = WallyUtil::CompressPubkey(data_);
return Pubkey(compress_data);
}
Pubkey Pubkey::Uncompress() const {
if (!IsCompress()) {
return *this;
}
// The conversion from uncompress to compress is irreversible.
// (if convert compress to uncompress, prefix is '04'. Not '06' or '07'.)
std::vector<uint8_t> decompress_data(EC_PUBLIC_KEY_UNCOMPRESSED_LEN);
std::vector<uint8_t> data = data_.GetBytes();
int ret = wally_ec_public_key_decompress(
data.data(), data.size(), decompress_data.data(),
decompress_data.size());
if (ret != WALLY_OK) {
warn(CFD_LOG_SOURCE, "wally_ec_public_key_decompress error. ret={}", ret);
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Failed to uncompress pubkey.");
}
return Pubkey(decompress_data);
}
bool Pubkey::IsLarge(const Pubkey &source, const Pubkey &destination) {
return ByteData::IsLarge(source.data_, destination.data_);
}
bool Pubkey::VerifyEcSignature(
const ByteData256 &signature_hash, const ByteData &signature) const {
return SignatureUtil::VerifyEcSignature(signature_hash, *this, signature);
}
Pubkey Pubkey::operator+=(const Pubkey &right) {
Pubkey key = Pubkey::CombinePubkey(*this, right);
*this = key;
return *this;
}
Pubkey Pubkey::operator+=(const ByteData256 &right) {
Pubkey key = CreateTweakAdd(right);
*this = key;
return *this;
}
Pubkey Pubkey::operator-=(const ByteData256 &right) {
Privkey sk(right);
auto neg = sk.CreateNegate();
Pubkey key = CreateTweakAdd(ByteData256(neg.GetData()));
*this = key;
return *this;
}
Pubkey Pubkey::operator*=(const ByteData256 &right) {
Pubkey key = CreateTweakMul(right);
*this = key;
return *this;
}
// global operator overloading
Pubkey operator+(const Pubkey &left, const Pubkey &right) {
return Pubkey::CombinePubkey(left, right);
}
Pubkey operator+(const Pubkey &left, const ByteData256 &right) {
return left.CreateTweakAdd(right);
}
Pubkey operator-(const Pubkey &left, const ByteData256 &right) {
Pubkey key = left;
key -= right;
return key;
}
Pubkey operator*(const Pubkey &left, const ByteData256 &right) {
return left.CreateTweakMul(right);
}
// ----------------------------------------------------------------------------
// Private Key
// ----------------------------------------------------------------------------
/// Mainnet Prefix
static constexpr uint32_t kPrefixMainnet = 0x80;
/// Testnet Prefix
static constexpr uint32_t kPrefixTestnet = 0xef;
Privkey::Privkey() : data_() {
// do nothing
}
Privkey::Privkey(
const ByteData &byte_data, NetType net_type, bool is_compressed)
: data_(byte_data), is_compressed_(is_compressed), net_type_(net_type) {
if (!IsValid(data_.GetBytes())) {
warn(CFD_LOG_SOURCE, "Invalid Privkey data. hex={}.", data_.GetHex());
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Invalid Privkey data.");
}
}
Privkey::Privkey(
const ByteData256 &byte_data, NetType net_type, bool is_compressed)
: data_(ByteData(byte_data.GetBytes())),
is_compressed_(is_compressed),
net_type_(net_type) {
if (!IsValid(data_.GetBytes())) {
warn(CFD_LOG_SOURCE, "Invalid Privkey data. hex={}.", data_.GetHex());
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Invalid Privkey data.");
}
}
Privkey::Privkey(
const std::string &hex_str, NetType net_type, bool is_compressed)
: data_(ByteData(hex_str)),
is_compressed_(is_compressed),
net_type_(net_type) {
if (!IsValid(data_.GetBytes())) {
warn(CFD_LOG_SOURCE, "Invalid Privkey data. hex={}.", data_.GetHex());
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Invalid Privkey data.");
}
}
std::string Privkey::GetHex() const { return data_.GetHex(); }
ByteData Privkey::GetData() const { return data_.GetBytes(); }
std::string Privkey::ConvertWif(NetType net_type, bool is_compressed) const {
uint32_t prefix = (net_type == kMainnet ? kPrefixMainnet : kPrefixTestnet);
uint32_t flags =
(is_compressed ? WALLY_WIF_FLAG_COMPRESSED
: WALLY_WIF_FLAG_UNCOMPRESSED);
char *wif_ptr = NULL;
int ret = wally_wif_from_bytes(
data_.GetBytes().data(), data_.GetDataSize(), prefix, flags, &wif_ptr);
if (ret != WALLY_OK) {
warn(
CFD_LOG_SOURCE, "wally_wif_from_bytes error. ret={} bytes={}.", ret,
data_.GetHex());
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Error Private key to WIF.");
}
std::string wif = WallyUtil::ConvertStringAndFree(wif_ptr);
return wif;
}
std::string Privkey::GetWif() const {
return ConvertWif(net_type_, is_compressed_);
}
Privkey Privkey::FromWif(
const std::string &wif, NetType net_type, bool is_compressed) {
std::vector<uint8_t> privkey(kPrivkeySize);
NetType temp_net_type = net_type;
bool is_temp_compressed = is_compressed;
if (net_type == NetType::kCustomChain) {
// auto analyze
size_t written = 0;
size_t uncompressed = 0;
std::vector<uint8_t> buf(2 + EC_PRIVATE_KEY_LEN + BASE58_CHECKSUM_LEN);
int ret = wally_base58_to_bytes(
wif.data(), BASE58_FLAG_CHECKSUM, buf.data(), buf.size(), &written);
if (ret != WALLY_OK) {
warn(
CFD_LOG_SOURCE, "wally_base58_to_bytes error. ret={} wif={}.", ret,
wif);
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Error decode base58 WIF.");
}
ret = wally_wif_is_uncompressed(wif.data(), &uncompressed);
if (ret != WALLY_OK) {
warn(
CFD_LOG_SOURCE, "wally_wif_is_uncompressed error. ret={} wif={}.",
ret, wif);
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Error WIF is uncompressed.");
}
uint32_t prefix = buf[0];
memcpy(privkey.data(), &buf[1], privkey.size());
temp_net_type = (prefix == kPrefixMainnet) ? kMainnet : kTestnet;
is_temp_compressed = (uncompressed == 0) ? true : false;
} else {
uint32_t prefix = (net_type == kMainnet ? kPrefixMainnet : kPrefixTestnet);
uint32_t flags =
(is_compressed ? WALLY_WIF_FLAG_COMPRESSED
: WALLY_WIF_FLAG_UNCOMPRESSED);
int ret = wally_wif_to_bytes(
wif.data(), prefix, flags, privkey.data(), kPrivkeySize);
if (ret != WALLY_OK) {
warn(
CFD_LOG_SOURCE, "wally_wif_to_bytes error. ret={} wif={}.", ret,
wif);
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Error WIF to Private key.");
}
temp_net_type = net_type;
is_temp_compressed = is_compressed;
}
if (!IsValid(privkey)) {
warn(
CFD_LOG_SOURCE, "Invalid Privkey data. data={}",
ByteData(privkey).GetHex());
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Invalid Privkey data");
}
Privkey key = Privkey(ByteData(privkey));
key.SetPubkeyCompressed(is_temp_compressed);
key.SetNetType(temp_net_type);
return key;
}
bool Privkey::HasWif(
const std::string &wif, NetType *net_type, bool *is_compressed) {
static constexpr size_t kWifMinimumSize = EC_PRIVATE_KEY_LEN + 1;
size_t is_uncompressed = 0;
int ret = wally_wif_is_uncompressed(wif.c_str(), &is_uncompressed);
if (ret != WALLY_OK) {
// contains check wif.
return false;
}
bool has_wif = false;
ByteData data = CryptoUtil::DecodeBase58Check(wif);
if (data.GetDataSize() >= kWifMinimumSize) {
std::vector<uint8_t> key_data = data.GetBytes();
uint32_t prefix = key_data[0];
if (net_type != nullptr) {
if (prefix == kPrefixMainnet) {
*net_type = NetType::kMainnet;
} else if (prefix == kPrefixTestnet) {
*net_type = NetType::kTestnet;
} else {
warn(CFD_LOG_SOURCE, "Invalid Privkey format. prefix={}", prefix);
*net_type = NetType::kTestnet;
}
}
if (is_compressed != nullptr) {
*is_compressed = (is_uncompressed == 0) ? true : false;
}
has_wif = true;
}
return has_wif;
}
Pubkey Privkey::GetPubkey() const { return GeneratePubkey(is_compressed_); }
Pubkey Privkey::GeneratePubkey(bool is_compressed) const {
std::vector<uint8_t> pubkey(Pubkey::kCompressedPubkeySize);
int ret = wally_ec_public_key_from_private_key(
data_.GetBytes().data(), data_.GetDataSize(), pubkey.data(),
pubkey.size());
if (ret != WALLY_OK) {
warn(
CFD_LOG_SOURCE,
"wally_ec_public_key_from_private_key error. ret={} privkey={}.", ret,
data_.GetHex());
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Generate Pubkey error.");
}
if (is_compressed) {
return Pubkey(pubkey);
}
std::vector<uint8_t> uncompressed_pubkey(Pubkey::kPubkeySize);
ret = wally_ec_public_key_decompress(
pubkey.data(), pubkey.size(), uncompressed_pubkey.data(),
uncompressed_pubkey.size());
if (ret != WALLY_OK) {
warn(
CFD_LOG_SOURCE,
"wally_ec_public_key_decompress error. ret={} compressed pubkey={}.",
ret, ByteData(pubkey).GetHex());
throw CfdException(
CfdError::kCfdIllegalArgumentError, "Decompressed Pubkey error.");
}
return Pubkey(uncompressed_pubkey);
}
Privkey Privkey::GenerageRandomKey() {
std::vector<uint8_t> privkey;
int ret = WALLY_OK;
do {
privkey = RandomNumberUtil::GetRandomBytes(kPrivkeySize);
ret = wally_ec_private_key_verify(privkey.data(), privkey.size());
} while (ret != WALLY_OK);
return Privkey(ByteData(privkey));
}
Privkey Privkey::CreateTweakAdd(const ByteData256 &tweak) const {
ByteData tweak_added = WallyUtil::AddTweakPrivkey(data_, tweak);
return Privkey(tweak_added);
}
Privkey Privkey::CreateTweakAdd(const Privkey &tweak) const {
ByteData tweak_added =
WallyUtil::AddTweakPrivkey(data_, ByteData256(tweak.data_));
return Privkey(tweak_added);
}
Privkey Privkey::CreateTweakMul(const ByteData256 &tweak) const {
ByteData tweak_muled = WallyUtil::MulTweakPrivkey(data_, tweak);
return Privkey(tweak_muled);
}
Privkey Privkey::CreateTweakMul(const Privkey &tweak) const {
ByteData tweak_muled =
WallyUtil::MulTweakPrivkey(data_, ByteData256(tweak.data_));
return Privkey(tweak_muled);
}
Privkey Privkey::CreateNegate() const {
ByteData negated = WallyUtil::NegatePrivkey(data_);
return Privkey(negated);
}
bool Privkey::IsInvalid() const { return !IsValid(); }
bool Privkey::IsValid() const { return IsValid(data_.GetBytes()); }
bool Privkey::Equals(const Privkey &privkey) const {
return data_.Equals(privkey.data_);
}
bool Privkey::IsValid(const std::vector<uint8_t> &buffer) {
if (buffer.size() > 0) {
int ret = wally_ec_private_key_verify(buffer.data(), buffer.size());
return ret == WALLY_OK;
}
return false;
}
ByteData Privkey::CalculateEcSignature(
const ByteData256 &signature_hash, bool has_grind_r) const {
return SignatureUtil::CalculateEcSignature(
signature_hash, *this, has_grind_r);
}
void Privkey::SetPubkeyCompressed(bool is_compressed) {
is_compressed_ = is_compressed;
}
void Privkey::SetNetType(NetType net_type) { net_type_ = net_type; }
Privkey Privkey::operator+=(const Privkey &right) {
Privkey key = CreateTweakAdd(right);
*this = key;
return *this;
}
Privkey Privkey::operator+=(const ByteData256 &right) {
Privkey key = CreateTweakAdd(right);
*this = key;
return *this;
}
Privkey Privkey::operator-=(const Privkey &right) {
Privkey key = CreateTweakAdd(right.CreateNegate());
*this = key;
return *this;
}
Privkey Privkey::operator-=(const ByteData256 &right) {
Privkey sk(right);
Privkey key = CreateTweakAdd(sk.CreateNegate());
*this = key;
return *this;
}
Privkey Privkey::operator*=(const Privkey &right) {
Privkey key = CreateTweakMul(right);
*this = key;
return *this;
}
Privkey Privkey::operator*=(const ByteData256 &right) {
Privkey key = CreateTweakMul(right);
*this = key;
return *this;
}
// global operator overloading
Privkey operator+(const Privkey &left, const Privkey &right) {
return left.CreateTweakAdd(right);
}
Privkey operator+(const Privkey &left, const ByteData256 &right) {
return left.CreateTweakAdd(right);
}
Privkey operator-(const Privkey &left, const Privkey &right) {
Privkey key = left;
key -= right;
return key;
}
Privkey operator-(const Privkey &left, const ByteData256 &right) {
Privkey key = left;
key -= right;
return key;
}
Privkey operator*(const Privkey &left, const Privkey &right) {
return left.CreateTweakMul(right);
}
Privkey operator*(const Privkey &left, const ByteData256 &right) {
return left.CreateTweakMul(right);
}
} // namespace core
} // namespace cfd