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
#include "OpCode.h"
9
#include "ParamsBuilder.h"
10

11
#include "../Hash.h"
12

13
#include <TrezorCrypto/base58.h>
14

15
#include <stdexcept>
16
#include <string>
17

18
using namespace TW;
19
using namespace TW::Ontology;
20

21 1
Address::Address(const PublicKey& publicKey) {
22 1
    std::vector<uint8_t> builder(publicKey.bytes);
23 1
    builder.insert(builder.begin(), PUSH_BYTE_33);
24 1
    builder.push_back(CHECK_SIG);
25 1
    auto builderData = toScriptHash(builder);
26 1
    std::copy(builderData.begin(), builderData.end(), data.begin());
27
}
28

29 1
Address::Address(const std::string& b58Address) {
30 1
    if (!Address::isValid(b58Address)) {
31 1
        throw std::runtime_error("Invalid base58 encode address.");
32
    }
33 1
    Data addressWithVersion(size + 1);
34 1
    base58_decode_check(b58Address.c_str(), HASHER_SHA2D, addressWithVersion.data(), size + 1);
35 1
    std::copy(addressWithVersion.begin() + 1, addressWithVersion.end(), data.begin());
36
}
37

38 0
Address::Address(const std::vector<uint8_t>& bytes) {
39 0
    if (bytes.size() != size) {
40 0
        throw std::runtime_error("Invalid bytes data.");
41
    }
42 0
    std::copy(bytes.begin(), bytes.end(), data.begin());
43
}
44

45 1
Address::Address(uint8_t m, const std::vector<Data>& publicKeys) {
46 1
    auto builderData = toScriptHash(ParamsBuilder::fromMultiPubkey(m, publicKeys));
47 1
    std::copy(builderData.begin(), builderData.end(), data.begin());
48
}
49

50 1
Data Address::toScriptHash(const Data& data) {
51 1
    return Hash::ripemd(Hash::sha256(data));
52
}
53

54 1
bool Address::isValid(const std::string& b58Address) noexcept {
55 1
    if (b58Address.length() != 34) {
56 1
        return false;
57
    }
58 1
    Data addressWithVersion(size + 1);
59 1
    auto len =
60 1
        base58_decode_check(b58Address.c_str(), HASHER_SHA2D, addressWithVersion.data(), size + 1);
61 1
    return len == size + 1;
62
}
63

64 1
std::string Address::string() const {
65 1
    std::vector<uint8_t> encodeData(size + 1);
66 1
    encodeData[0] = version;
67 1
    std::copy(data.begin(), data.end(), encodeData.begin() + 1);
68 1
    size_t b58StrSize = 34;
69 1
    std::string b58Str(b58StrSize, ' ');
70 1
    base58_encode_check(encodeData.data(), (int)encodeData.size(), HASHER_SHA2D, &b58Str[0],
71 1
                        (int)b58StrSize + 1);
72 1
    return b58Str;
73
}

Read our documentation on viewing source code .

Loading