forked from trustwallet/wallet-core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAddress.cpp
More file actions
85 lines (69 loc) · 2.52 KB
/
Copy pathAddress.cpp
File metadata and controls
85 lines (69 loc) · 2.52 KB
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
// Copyright © 2017-2020 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "Address.h"
#include "../Base58.h"
#include "../Data.h"
#include "../Hash.h"
#include <HexCoding.h>
#include <cassert>
#include <stdexcept>
using namespace TW;
using namespace TW::Waves;
template <typename T>
Data Address::secureHash(const T &data) {
return Hash::keccak256(Hash::blake2b(data, 32));
}
bool Address::isValid(const Data &decoded) {
if (decoded.size() != Address::size) {
return false;
}
if (decoded[0] != v1) {
return false;
}
if (decoded[1] != mainnet) {
return false;
}
const auto data = Data(decoded.begin(), decoded.end() - 4);
const auto data_checksum = Data(decoded.end() - 4, decoded.end());
const auto calculated_hash = secureHash(data);
const auto calculated_checksum = Data(calculated_hash.begin(), calculated_hash.begin() + 4);
const auto h = hex(data);
const auto h2 = hex(calculated_hash);
return std::memcmp(data_checksum.data(), calculated_checksum.data(), 4) == 0;
}
bool Address::isValid(const std::string &string) {
const auto decoded = Base58::bitcoin.decode(string);
return isValid(decoded);
}
Address::Address(const std::string &string) {
const auto decoded = Base58::bitcoin.decode(string);
if (!isValid(string)) {
throw std::invalid_argument("Invalid address key data");
}
std::copy(decoded.begin(), decoded.end(), bytes.begin());
}
Address::Address(const Data &data) {
if (!isValid(data)) {
throw std::invalid_argument("Invalid address data");
}
std::copy(data.begin(), data.end(), bytes.begin());
}
Address::Address(const PublicKey &publicKey) {
if (publicKey.type != TWPublicKeyTypeCURVE25519) {
throw std::invalid_argument("Invalid public key type");
}
const auto pkdata = Data(publicKey.bytes.begin(), publicKey.bytes.end());
const auto keyhash = Address::secureHash(pkdata);
bytes[0] = v1;
bytes[1] = mainnet;
std::copy(keyhash.begin(), keyhash.begin() + 20, bytes.begin() + 2);
const auto checksum_data = Data(bytes.begin(), bytes.begin() + 22);
const auto checksum = Hash::keccak256(Hash::blake2b(checksum_data, 32));
std::copy(checksum.begin(), checksum.begin() + 4, bytes.begin() + 22);
}
std::string Address::string() const {
return Base58::bitcoin.encode(bytes);
}