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
#include "Address.h"
7

8
#include <TrezorCrypto/ecdsa.h>
9

10
#include "../Base58.h"
11
#include "../BinaryCoding.h"
12
#include "../HexCoding.h"
13

14
using namespace TW;
15
using namespace TW::NULS;
16

17 1
const std::string Address::prefix("NULSd");
18
const std::array<byte, 2> Address::mainnetId = {0x01, 0x00};
19

20 1
bool Address::isValid(const std::string& string) {
21 1
    if (string.empty()) {
22 0
        return false;
23
    }
24 1
    if (string.length() <=  prefix.length()) {
25 1
        return false;
26
    }
27

28 1
    std::string address = string.substr(prefix.length(), string.length() - prefix.length());
29 1
    Data decoded = Base58::bitcoin.decode(address);
30 1
    if (decoded.size() != size) {
31 1
        return false;
32
    }
33

34
    // Check Xor
35 1
    uint8_t checkSum = 0x00;
36 1
    for (int i = 0; i < 23; ++i) {
37 1
        checkSum ^= decoded[i];
38
    }
39

40 1
    return decoded[23] == checkSum;
41
}
42

43 1
Address::Address(const TW::PublicKey& publicKey) {
44
    // Main-Net chainID
45 1
    bytes[0] = mainnetId[0];
46 1
    bytes[1] = mainnetId[1];
47
    // Address Type
48 1
    bytes[2] = addressType;
49 1
    ecdsa_get_pubkeyhash(publicKey.bytes.data(), HASHER_SHA2_RIPEMD, bytes.begin() + 3);
50 1
    bytes[23] = checksum(bytes);
51
}
52

53 1
Address::Address(const std::string& string) {
54 1
    if (false == isValid(string)){
55 0
        throw std::invalid_argument("Invalid address string");
56
    }
57 1
    std::string address = string.substr(prefix.length(), string.length() - prefix.length()); 
58 1
    const auto decoded = Base58::bitcoin.decode(address);
59 1
    std::copy(decoded.begin(), decoded.end(), bytes.begin());
60
}
61

62 1
uint16_t Address::chainID() const {
63 1
    return decode16LE(bytes.data());
64
}
65

66 1
uint8_t Address::type() const {
67 1
    return bytes[2];
68
}
69

70 1
std::string Address::string() const {
71 1
    return prefix + Base58::bitcoin.encode(bytes.begin(), bytes.end());
72
}
73

74 1
uint8_t Address::checksum(std::array<byte, size>& byteArray) const{
75 1
    uint8_t checkSum = 0x00;
76 1
    for (int i = 0; i < 23; ++i) {
77 1
        checkSum ^= byteArray[i];
78
    }
79 1
    return checkSum;
80
}
81

82

Read our documentation on viewing source code .

Loading