1
// Copyright © 2017-2020 Trust Wallet.
2
//
3
// This file is part of Trust. The full Trust copyright notice, including
4
// terms governing use, modification, and redistribution, is contained in the
5
// file LICENSE at the root of the source code distribution tree.
6

7
#include "Address.h"
8

9
#include "../Hash.h"
10
#include "../HexCoding.h"
11
#include "../PrivateKey.h"
12

13
#include <TrezorCrypto/sha3.h>
14

15
using namespace TW;
16
using namespace TW::Icon;
17

18 1
static const std::string addressPrefix = "hx";
19 1
static const std::string contractPrefix = "cx";
20

21 1
bool Address::isValid(const std::string& string) {
22 1
    if (string.size() != Address::size * 2 + 2) {
23 1
        return false;
24
    }
25 1
    if (!std::equal(addressPrefix.begin(), addressPrefix.end(), string.begin()) &&
26 1
        !std::equal(contractPrefix.begin(), contractPrefix.end(), string.begin())) {
27 1
        return false;
28
    }
29 1
    return true;
30
}
31

32 1
Address::Address(const std::string& string) {
33 1
    if (!isValid(string)) {
34 0
        throw std::invalid_argument("Invalid address data");
35
    }
36

37 1
    if (std::equal(addressPrefix.begin(), addressPrefix.end(), string.begin())) {
38 1
        type = TypeAddress;
39 1
    } else if (std::equal(contractPrefix.begin(), contractPrefix.end(), string.begin())) {
40 1
        type = TypeContract;
41 1
    } else {
42 0
        throw std::invalid_argument("Invalid address prefix");
43
    }
44

45 1
    const auto data = parse_hex(string.begin() + 2, string.end());
46 1
    std::copy(data.begin(), data.end(), bytes.begin());
47
}
48

49 1
Address::Address(const PublicKey& publicKey, enum AddressType type) : type(type) {
50 1
    auto hash = std::array<uint8_t, Hash::sha256Size>();
51 1
    sha3_256(publicKey.bytes.data() + 1, publicKey.bytes.size() - 1, hash.data());
52 1
    std::copy(hash.end() - Address::size, hash.end(), bytes.begin());
53
}
54

55 1
std::string Address::string() const {
56 1
    switch (type) {
57
    case TypeAddress:
58 1
        return addressPrefix + hex(bytes);
59
    case TypeContract:
60 1
        return contractPrefix + hex(bytes);
61
    default:
62 0
        return "";
63
    }
64
}

Read our documentation on viewing source code .

Loading