forked from trustwallet/wallet-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBase58.h
54 lines (45 loc) · 1.98 KB
/
Base58.h
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
// SPDX-License-Identifier: Apache-2.0
//
// Copyright © 2017 Trust Wallet.
#pragma once
#include "Data.h"
#include "Hash.h"
#include "rust/bindgen/WalletCoreRSBindgen.h"
#include "rust/Wrapper.h"
#include <string>
namespace TW::Base58 {
/// Decodes a base 58 string into `result`, returns `false` on failure.
static inline Data decode(const std::string& string, Rust::Base58Alphabet alphabet = Rust::Base58Alphabet::Bitcoin) {
if (string.empty()) {
return {};
}
Rust::CByteArrayResultWrapper res = Rust::decode_base58(string.c_str(), alphabet);
return res.unwrap_or_default().data;
}
static inline Data decodeCheck(const std::string& string, Rust::Base58Alphabet alphabet = Rust::Base58Alphabet::Bitcoin, Hash::Hasher hasher = Hash::HasherSha256d) {
auto result = decode(string, alphabet);
if (result.size() < 4) {
return {};
}
// re-calculate the checksum, ensure it matches the included 4-byte checksum
auto hash = Hash::hash(hasher, result.data(), result.size() - 4);
if (!std::equal(hash.begin(), hash.begin() + 4, result.end() - 4)) {
return {};
}
return Data(result.begin(), result.end() - 4);
}
template <typename T>
static inline std::string encode(const T& data, Rust::Base58Alphabet alphabet = Rust::Base58Alphabet::Bitcoin) {
auto encoded = encode_base58(data.data(), data.size(), alphabet);
std::string encoded_str(encoded);
Rust::free_string(encoded);
return encoded_str;
}
template <typename T>
static inline std::string encodeCheck(const T& data, Rust::Base58Alphabet alphabet = Rust::Base58Alphabet::Bitcoin, Hash::Hasher hasher = Hash::HasherSha256d) {
auto hash = Hash::hash(hasher, data);
Data toBeEncoded(std::begin(data), std::end(data));
toBeEncoded.insert(toBeEncoded.end(), hash.begin(), hash.begin() + 4);
return encode(toBeEncoded, alphabet);
}
}