Coverage Report

Created: 2026-04-29 19:21

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 2015 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
43
{
20
43
    if (str.empty()) // No empty string allowed
21
0
        return false;
22
43
    if (str.size() >= 1 && (json_isspace(str[0]) || json_isspace(str[str.size()-1]))) // No padding allowed
23
0
        return false;
24
43
    if (str.size() != strlen(str.c_str())) // No embedded NUL characters allowed
25
0
        return false;
26
43
    return true;
27
43
}
28
29
std::optional<double> ParseDouble(const std::string& str)
30
43
{
31
43
    if (!ParsePrechecks(str))
32
0
        return std::nullopt;
33
43
    if (str.size() >= 2 && str[0] == '0' && str[1] == 'x') // No hexadecimal floats allowed
34
0
        return std::nullopt;
35
43
    std::istringstream text(str);
36
43
    text.imbue(std::locale::classic());
37
43
    double result;
38
43
    text >> result;
39
43
    if (!text.eof() || text.fail()) {
40
0
        return std::nullopt;
41
0
    }
42
43
    return result;
43
43
}
44
}
45
46
const std::vector<std::string>& UniValue::getKeys() const
47
99.5k
{
48
99.5k
    checkType(VOBJ);
49
99.5k
    return keys;
50
99.5k
}
51
52
const std::vector<UniValue>& UniValue::getValues() const
53
100k
{
54
100k
    if (typ != VOBJ && typ != VARR)
55
1
        throw std::runtime_error("JSON value is not an object or array as expected");
56
100k
    return values;
57
100k
}
58
59
bool UniValue::get_bool() const
60
11.1k
{
61
11.1k
    checkType(VBOOL);
62
11.1k
    return isTrue();
63
11.1k
}
64
65
const std::string& UniValue::get_str() const
66
1.22M
{
67
1.22M
    checkType(VSTR);
68
1.22M
    return getValStr();
69
1.22M
}
70
71
double UniValue::get_real() const
72
43
{
73
43
    checkType(VNUM);
74
43
    if (const auto retval{ParseDouble(getValStr())}) {
75
43
        return *retval;
76
43
    }
77
0
    throw std::runtime_error("JSON double out of range");
78
43
}
79
80
const UniValue& UniValue::get_obj() const
81
819k
{
82
819k
    checkType(VOBJ);
83
819k
    return *this;
84
819k
}
85
86
const UniValue& UniValue::get_array() const
87
2.29M
{
88
2.29M
    checkType(VARR);
89
2.29M
    return *this;
90
2.29M
}