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
84 lines (67 loc) · 2.52 KB
/
Copy pathAddress.cpp
File metadata and controls
84 lines (67 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
// 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 "../Base32.h"
#include "../HexCoding.h"
#include "Crc.h"
#include <TrezorCrypto/memzero.h>
#include <TrustWalletCore/TWStellarVersionByte.h>
#include <array>
#include <cassert>
using namespace TW::Stellar;
bool Address::isValid(const std::string& string) {
bool valid = false;
if (string.length() != size) {
return false;
}
// Check that it decodes correctly
Data decoded;
valid = Base32::decode(string, decoded);
// ... and that version byte is 0x30
if (valid && TWStellarVersionByte(decoded[0]) != TWStellarVersionByte::TWStellarVersionByteAccountID) {
valid = false;
}
// ... and that checksums match
uint16_t checksum_expected = Crc::crc16(decoded.data(), 33);
uint16_t checksum_actual = static_cast<uint16_t>((decoded[34] << 8) | decoded[33]); // unsigned short (little endian)
if (valid && checksum_expected != checksum_actual) {
valid = false;
}
memzero(decoded.data(), decoded.size());
return valid;
}
Address::Address(const std::string& string) {
// Ensure address is valid
if (!isValid(string)) {
throw std::invalid_argument("Invalid address data");
}
Data decoded;
Base32::decode(string, decoded);
std::copy(decoded.begin() + 1, decoded.begin() + 1 + bytes.size(), bytes.begin());
memzero(decoded.data(), decoded.size());
}
Address::Address(const PublicKey& publicKey) {
if (publicKey.type != TWPublicKeyTypeED25519) {
throw std::invalid_argument("Invalid public key type");
}
static_assert(PublicKey::ed25519Size == keySize);
std::copy(publicKey.bytes.begin(), publicKey.bytes.end(), bytes.data());
}
std::string Address::string() const {
// version + key bytes + checksum
constexpr uint8_t keylen = 1 + 32 + 2;
std::array<uint8_t, keylen> bytes_full;
bytes_full[0] = 6 << 3; // 'G'
std::copy(bytes.begin(), bytes.end(), bytes_full.begin() + 1);
// Last two bytes are the checksum
uint16_t checksum = Crc::crc16(bytes_full.data(), 33);
bytes_full[keylen - 2] = checksum & 0x00ff;
bytes_full[keylen - 1] = (checksum >> 8) & 0x00ff;
Data bytesAsData;
bytesAsData.assign(bytes_full.begin(), bytes_full.end());
auto out = Base32::encode(bytesAsData);
return out;
}