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 "Base58.h"
8
#include "HexCoding.h"
9
#include "Address.h"
10

11
#include <stdexcept>
12

13
using namespace TW;
14
using namespace TW::NEAR;
15

16 1
bool Address::isValid(const std::string& string) {
17 1
    const auto data = Address::decodeLegacyAddress(string);
18 1
    if (data.has_value()) {
19 1
        return true;
20
    } 
21 1
    const auto parsed = parse_hex(string);
22 1
    return parsed.size() == PublicKey::ed25519Size;
23
}
24

25
/// Decode and verifies the key data from a base58 string.
26 1
std::optional<Data> Address::decodeLegacyAddress(const std::string& string) {
27 1
    const auto prefix = std::string("NEAR");
28 1
    if (string.substr(0, prefix.size()) != prefix) {
29 1
        return {};
30
    }
31

32 1
    const Data& decoded = Base58::bitcoin.decode(string.substr(prefix.size()));
33 1
    return Data(decoded.begin(), decoded.end() - 4);
34
}
35

36
/// Initializes a NEAR address from a string representation.
37 1
Address::Address(const std::string& string) {
38 1
    const auto data = Address::decodeLegacyAddress(string);
39 1
    if (data.has_value()) {
40 1
        std::copy(std::begin(*data), std::end(*data), std::begin(bytes));
41 1
    } else {
42 1
        if (!Address::isValid(string)) {
43 0
             throw std::invalid_argument("Invalid address string!");
44
        }
45 1
        const auto parsed = parse_hex(string);
46 1
        std::copy(std::begin(parsed), std::end(parsed), std::begin(bytes));
47
    }
48
}
49

50
/// Initializes a NEAR address from a public key.
51 1
Address::Address(const PublicKey& publicKey) {
52
    // copy the raw, compressed key data
53 1
    auto data = publicKey.compressed().bytes;
54 1
    std::copy(std::begin(data), std::end(data), std::begin(bytes));
55
}
56

57
/// Returns a string representation of the NEAR address.
58 1
std::string Address::string() const {
59 1
    return hex(bytes);
60
}

Read our documentation on viewing source code .

Loading