Coverage Report

Created: 2026-11-13 17:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/univalue/lib/univalue_get.cpp
Line
Count
Source
1
// Copyright 2014 BitPay Inc.
2
// Copyright (c) 2015-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or https://opensource.org/licenses/mit-license.php.
5
6
#include <univalue.h>
7
8
#include <cstring>
9
#include <locale>
10
#include <optional>
11
#include <sstream>
12
#include <stdexcept>
13
#include <string>
14
#include <vector>
15
16
namespace
17
{
18
static bool ParsePrechecks(const std::string& str)
19
170
{
20
170
    if (str.empty()) // No empty string allowed
21
0
        return false;
22
170
    if (str.size() >= 1 && (json_isspace(str[0]) || json_isspace(str[str.size()-1]))) // No padding allowed
23
0
        return false;
24
170
    if (str.size() != strlen(str.c_str())) // No embedded NUL characters allowed
25
0
        return false;
26
170
    return true;
27
170
}
28
29
std::optional<double> ParseDouble(const std::string& str)
30
170
{
31
170
    if (!ParsePrechecks(str))
32
0
        return std::nullopt;
33
170
    if (str.size() >= 2 && str[0] == '0' && str[1] == 'x') // No hexadecimal floats allowed
34
0
        return std::nullopt;
35
170
    std::istringstream text(str);
36
170
    text.imbue(std::locale::classic());
37
170
    double result;
38
170
    text >> result;
39
170
    if (!text.eof() || text.fail()) {
40
0
        return std::nullopt;
41
0
    }
42
170
    return result;
43
170
}
44
}
45
46
const std::vector<std::string>& UniValue::getKeys() const
47
133k
{
48
133k
    checkType(VOBJ);
49
133k
    return keys;
50
133k
}
51
52
const std::vector<UniValue>& UniValue::getValues() const
53
136k
{
54
136k
    if (typ != VOBJ && typ != VARR)
55
1
        throw std::runtime_error("JSON value is not an object or array as expected");
56
136k
    return values;
57
136k
}
58
59
bool UniValue::get_bool() const
60
81.9k
{
61
81.9k
    checkType(VBOOL);
62
81.9k
    return isTrue();
63
81.9k
}
64
65
const std::string& UniValue::get_str() const
66
1.46M
{
67
1.46M
    checkType(VSTR);
68
1.46M
    return getValStr();
69
1.46M
}
70
71
double UniValue::get_real() const
72
170
{
73
170
    checkType(VNUM);
74
170
    if (const auto retval{ParseDouble(getValStr())}) {
75
170
        return *retval;
76
170
    }
77
0
    throw std::runtime_error("JSON double out of range");
78
170
}
79
80
const UniValue& UniValue::get_obj() const
81
1.20M
{
82
1.20M
    checkType(VOBJ);
83
1.20M
    return *this;
84
1.20M
}
85
86
const UniValue& UniValue::get_array() const
87
2.34M
{
88
2.34M
    checkType(VARR);
89
2.34M
    return *this;
90
2.34M
}