Merge pull request #3276 from PastaPastaPasta/backports-0.16-pr2

Backports 0.16 pr2
This commit is contained in:
Alexander Block 2020-01-12 01:17:33 +01:00 committed by GitHub
commit cb33702b74
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
145 changed files with 1080 additions and 782 deletions

View File

@ -15,6 +15,8 @@ export CCACHE_SIZE=${CCACHE_SIZE:-400M}
if [ "$PULL_REQUEST" != "false" ]; then contrib/devtools/commit-script-check.sh $COMMIT_RANGE; fi
#if [ "$CHECK_DOC" = 1 ]; then contrib/devtools/check-doc.py; fi TODO reenable after all Bitcoin PRs have been merged and docs fully fixed
if [ "$CHECK_DOC" = 1 ]; then contrib/devtools/check-rpc-mappings.py .; fi
if [ "$CHECK_DOC" = 1 ]; then contrib/devtools/lint-all.sh; fi
ccache --max-size=$CCACHE_SIZE

View File

@ -30,7 +30,7 @@ _dashd() {
;;
*)
# only parse -help if senseful
# only parse -help if sensible
if [[ -z "$cur" || "$cur" =~ ^- ]]; then
local helpopts
helpopts=$($dashd -help 2>&1 | awk '$1 ~ /^-/ { sub(/=.*/, "="); print $1 }' )

View File

@ -150,11 +150,11 @@ Perform basic ELF security checks on a series of executables.
symbol-check.py
===============
A script to check that the (Linux) executables produced by gitian only contain
A script to check that the (Linux) executables produced by Gitian only contain
allowed gcc, glibc and libstdc++ version symbols. This makes sure they are
still compatible with the minimum supported Linux distribution versions.
Example usage after a gitian build:
Example usage after a Gitian build:
find ../gitian-builder/build -type f -executable | xargs python contrib/devtools/symbol-check.py

View File

@ -0,0 +1,163 @@
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Check RPC argument consistency."""
from collections import defaultdict
import os
import re
import sys
# Source files (relative to root) to scan for dispatch tables
SOURCES = [
"src/rpc/server.cpp",
"src/rpc/blockchain.cpp",
"src/rpc/governance.cpp",
"src/rpc/masternode.cpp",
"src/rpc/mining.cpp",
"src/rpc/misc.cpp",
"src/rpc/net.cpp",
"src/rpc/privatesend.cpp",
"src/rpc/rawtransaction.cpp",
"src/rpc/rpcevo.cpp",
"src/rpc/rpcquorums.cpp",
"src/wallet/rpcwallet.cpp",
]
# Source file (relative to root) containing conversion mapping
SOURCE_CLIENT = 'src/rpc/client.cpp'
# Argument names that should be ignored in consistency checks
IGNORE_DUMMY_ARGS = {'dummy', 'arg0', 'arg1', 'arg2', 'arg3', 'arg4', 'arg5', 'arg6', 'arg7', 'arg8', 'arg9'}
class RPCCommand:
def __init__(self, name, args):
self.name = name
self.args = args
class RPCArgument:
def __init__(self, names, idx):
self.names = names
self.idx = idx
self.convert = False
def parse_string(s):
assert s[0] == '"'
assert s[-1] == '"'
return s[1:-1]
def process_commands(fname):
"""Find and parse dispatch table in implementation file `fname`."""
cmds = []
in_rpcs = False
with open(fname, "r") as f:
for line in f:
line = line.rstrip()
if not in_rpcs:
if re.match("static const CRPCCommand .*\[\] =", line):
in_rpcs = True
else:
if line.startswith('};'):
in_rpcs = False
elif '{' in line and '"' in line:
m = re.search('{ *("[^"]*"), *("[^"]*"), *&([^,]*), *{([^}]*)} *},', line)
assert m, 'No match to table expression: %s' % line
name = parse_string(m.group(2))
args_str = m.group(4).strip()
if args_str:
args = [RPCArgument(parse_string(x.strip()).split('|'), idx) for idx, x in enumerate(args_str.split(','))]
else:
args = []
cmds.append(RPCCommand(name, args))
assert not in_rpcs, "Something went wrong with parsing the C++ file: update the regexps"
return cmds
def process_mapping(fname):
"""Find and parse conversion table in implementation file `fname`."""
cmds = []
in_rpcs = False
with open(fname, "r") as f:
for line in f:
line = line.rstrip()
if not in_rpcs:
if line == 'static const CRPCConvertParam vRPCConvertParams[] =':
in_rpcs = True
else:
if line.startswith('};'):
in_rpcs = False
elif '{' in line and '"' in line:
m = re.search('{ *("[^"]*"), *([0-9]+) *, *("[^"]*") *},', line)
assert m, 'No match to table expression: %s' % line
name = parse_string(m.group(1))
idx = int(m.group(2))
argname = parse_string(m.group(3))
cmds.append((name, idx, argname))
assert not in_rpcs
return cmds
def main():
root = sys.argv[1]
# Get all commands from dispatch tables
cmds = []
for fname in SOURCES:
cmds += process_commands(os.path.join(root, fname))
cmds_by_name = {}
for cmd in cmds:
cmds_by_name[cmd.name] = cmd
# Get current convert mapping for client
client = SOURCE_CLIENT
mapping = set(process_mapping(os.path.join(root, client)))
print('* Checking consistency between dispatch tables and vRPCConvertParams')
# Check mapping consistency
errors = 0
for (cmdname, argidx, argname) in mapping:
try:
rargnames = cmds_by_name[cmdname].args[argidx].names
except IndexError:
print('ERROR: %s argument %i (named %s in vRPCConvertParams) is not defined in dispatch table' % (cmdname, argidx, argname))
errors += 1
continue
if argname not in rargnames:
print('ERROR: %s argument %i is named %s in vRPCConvertParams but %s in dispatch table' % (cmdname, argidx, argname, rargnames), file=sys.stderr)
errors += 1
# Check for conflicts in vRPCConvertParams conversion
# All aliases for an argument must either be present in the
# conversion table, or not. Anything in between means an oversight
# and some aliases won't work.
for cmd in cmds:
for arg in cmd.args:
convert = [((cmd.name, arg.idx, argname) in mapping) for argname in arg.names]
if any(convert) != all(convert):
print('ERROR: %s argument %s has conflicts in vRPCConvertParams conversion specifier %s' % (cmd.name, arg.names, convert))
errors += 1
arg.convert = all(convert)
# Check for conversion difference by argument name.
# It is preferable for API consistency that arguments with the same name
# have the same conversion, so bin by argument name.
all_methods_by_argname = defaultdict(list)
converts_by_argname = defaultdict(list)
for cmd in cmds:
for arg in cmd.args:
for argname in arg.names:
all_methods_by_argname[argname].append(cmd.name)
converts_by_argname[argname].append(arg.convert)
for argname, convert in converts_by_argname.items():
if all(convert) != any(convert):
if argname in IGNORE_DUMMY_ARGS:
# these are testing or dummy, don't warn for them
continue
print('WARNING: conversion mismatch for argument named %s (%s)' %
(argname, list(zip(all_methods_by_argname[argname], converts_by_argname[argname]))))
sys.exit(errors > 0)
if __name__ == '__main__':
main()

View File

@ -197,9 +197,10 @@ def main():
print("ERROR: Cannot check out branch %s." % (branch), file=stderr)
sys.exit(3)
try:
subprocess.check_call([GIT,'fetch','-q',host_repo,'+refs/pull/'+pull+'/*:refs/heads/pull/'+pull+'/*'])
subprocess.check_call([GIT,'fetch','-q',host_repo,'+refs/pull/'+pull+'/*:refs/heads/pull/'+pull+'/*',
'+refs/heads/'+branch+':refs/heads/'+base_branch])
except subprocess.CalledProcessError as e:
print("ERROR: Cannot find pull request #%s on %s." % (pull,host_repo), file=stderr)
print("ERROR: Cannot find pull request #%s or branch %s on %s." % (pull,branch,host_repo), file=stderr)
sys.exit(3)
try:
subprocess.check_call([GIT,'log','-q','-1','refs/heads/'+head_branch], stdout=devnull, stderr=stdout)
@ -211,11 +212,6 @@ def main():
except subprocess.CalledProcessError as e:
print("ERROR: Cannot find merge of pull request #%s on %s." % (pull,host_repo), file=stderr)
sys.exit(3)
try:
subprocess.check_call([GIT,'fetch','-q',host_repo,'+refs/heads/'+branch+':refs/heads/'+base_branch])
except subprocess.CalledProcessError as e:
print("ERROR: Cannot find branch %s on %s." % (branch,host_repo), file=stderr)
sys.exit(3)
subprocess.check_call([GIT,'checkout','-q',base_branch])
subprocess.call([GIT,'branch','-q','-D',local_merge_branch], stderr=devnull)
subprocess.check_call([GIT,'checkout','-q','-b',local_merge_branch])

22
contrib/devtools/lint-all.sh Executable file
View File

@ -0,0 +1,22 @@
#!/bin/bash
#
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# This script runs all contrib/devtools/lint-*.sh files, and fails if any exit
# with a non-zero status code.
set -u
SCRIPTDIR=$(dirname "${BASH_SOURCE[0]}")
LINTALL=$(basename "${BASH_SOURCE[0]}")
for f in "${SCRIPTDIR}"/lint-*.sh; do
if [ "$(basename "$f")" != "$LINTALL" ]; then
if ! "$f"; then
echo "^---- failure generated from $f"
exit 1
fi
fi
done

View File

@ -0,0 +1,88 @@
#!/bin/bash
#
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Check for new lines in diff that introduce trailing whitespace.
# We can't run this check unless we know the commit range for the PR.
if [ -z "${COMMIT_RANGE}" ]; then
echo "Cannot run lint-whitespace.sh without commit range. To run locally, use:"
echo "COMMIT_RANGE='<commit range>' .lint-whitespace.sh"
echo "For example:"
echo "COMMIT_RANGE='47ba2c3...ee50c9e' .lint-whitespace.sh"
exit 1
fi
showdiff() {
if ! git diff -U0 "${COMMIT_RANGE}" -- "." ":(exclude)src/leveldb/" ":(exclude)src/secp256k1/" ":(exclude)src/univalue/" ":(exclude)doc/release-notes/"; then
echo "Failed to get a diff"
exit 1
fi
}
showcodediff() {
if ! git diff -U0 "${COMMIT_RANGE}" -- *.cpp *.h *.md *.py *.sh ":(exclude)src/leveldb/" ":(exclude)src/secp256k1/" ":(exclude)src/univalue/" ":(exclude)doc/release-notes/"; then
echo "Failed to get a diff"
exit 1
fi
}
RET=0
# Check if trailing whitespace was found in the diff.
if showdiff | grep -E -q '^\+.*\s+$'; then
echo "This diff appears to have added new lines with trailing whitespace."
echo "The following changes were suspected:"
FILENAME=""
SEEN=0
while read -r line; do
if [[ "$line" =~ ^diff ]]; then
FILENAME="$line"
SEEN=0
elif [[ "$line" =~ ^@@ ]]; then
LINENUMBER="$line"
else
if [ "$SEEN" -eq 0 ]; then
# The first time a file is seen with trailing whitespace, we print the
# filename (preceded by a newline).
echo
echo "$FILENAME"
echo "$LINENUMBER"
SEEN=1
fi
echo "$line"
fi
done < <(showdiff | grep -E '^(diff --git |@@|\+.*\s+$)')
RET=1
fi
# Check if tab characters were found in the diff.
if showcodediff | grep -P -q '^\+.*\t'; then
echo "This diff appears to have added new lines with tab characters instead of spaces."
echo "The following changes were suspected:"
FILENAME=""
SEEN=0
while read -r line; do
if [[ "$line" =~ ^diff ]]; then
FILENAME="$line"
SEEN=0
elif [[ "$line" =~ ^@@ ]]; then
LINENUMBER="$line"
else
if [ "$SEEN" -eq 0 ]; then
# The first time a file is seen with a tab character, we print the
# filename (preceded by a newline).
echo
echo "$FILENAME"
echo "$LINENUMBER"
SEEN=1
fi
echo "$line"
fi
done < <(showcodediff | grep -P '^(diff --git |@@|\+.*\t)')
RET=1
fi
exit $RET

View File

@ -3,7 +3,7 @@
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
A script to check that the (Linux) executables produced by gitian only contain
A script to check that the (Linux) executables produced by Gitian only contain
allowed gcc, glibc and libstdc++ version symbols. This makes sure they are
still compatible with the minimum supported Linux distribution versions.

View File

@ -1,4 +1,4 @@
### Gavin's notes on getting gitian builds up and running using KVM
### Gavin's notes on getting Gitian builds up and running using KVM
These instructions distilled from
[https://help.ubuntu.com/community/KVM/Installation](https://help.ubuntu.com/community/KVM/Installation).
@ -56,10 +56,10 @@ Here's a description of Gavin's setup on OSX 10.6:
4. Inside the running Ubuntu desktop, install:
sudo apt-get install debootstrap lxc ruby apache2 git apt-cacher-ng python-vm-builder
sudo apt-get install debootstrap lxc ruby apache2 git apt-cacher-ng python-vm-builder
5. Still inside Ubuntu, tell gitian-builder to use LXC, then follow the "Once you've got the right hardware and software" instructions above:
export USE_LXC=1
git clone git://github.com/dashpay/dash.git
... etc
export USE_LXC=1
git clone git://github.com/dashpay/dash.git
... etc

View File

@ -3,7 +3,7 @@ PGP keys
This folder contains the public keys of developers and active contributors.
The keys are mainly used to sign git commits or the build results of gitian
The keys are mainly used to sign git commits or the build results of Gitian
builds.
You can import the keys into gpg as follows. Also, make sure to fetch the

View File

@ -30,12 +30,12 @@ pre-start script
echo
echo "This password is security critical to securing wallets "
echo "and must not be the same as the rpcuser setting."
echo "You can generate a suitable random password using the following"
echo "You can generate a suitable random password using the following "
echo "command from the shell:"
echo
echo "bash -c 'tr -dc a-zA-Z0-9 < /dev/urandom | head -c32 && echo'"
echo
echo "It is also recommended that you also set alertnotify so you are "
echo "It is recommended that you also set alertnotify so you are "
echo "notified of problems:"
echo
echo "ie: alertnotify=echo %%s | mail -s \"Dash Core Alert\"" \

View File

@ -76,12 +76,12 @@ checkconfig()
eerror ""
eerror "This password is security critical to securing wallets "
eerror "and must not be the same as the rpcuser setting."
eerror "You can generate a suitable random password using the following"
eerror "You can generate a suitable random password using the following "
eerror "command from the shell:"
eerror ""
eerror "bash -c 'tr -dc a-zA-Z0-9 < /dev/urandom | head -c32 && echo'"
eerror ""
eerror "It is also recommended that you also set alertnotify so you are "
eerror "It is recommended that you also set alertnotify so you are "
eerror "notified of problems:"
eerror ""
eerror "ie: alertnotify=echo %%s | mail -s \"Dash Core Alert\"" \

View File

@ -9,7 +9,7 @@ define $(package)_preprocess_cmds
endef
define $(package)_set_vars
$(package)_config_opts=--disable-shared --disable-openssl --disable-libevent-regress
$(package)_config_opts=--disable-shared --disable-openssl --disable-libevent-regress --disable-samples
$(package)_config_opts_release=--disable-debug-mode
$(package)_config_opts_linux=--with-pic
endef

View File

@ -560,6 +560,26 @@ Git and GitHub tips
or `git fetch upstream-pull`. Afterwards, you can use `upstream-pull/NUMBER/head` in arguments to `git show`,
`git checkout` and anywhere a commit id would be acceptable to see the changes from pull request NUMBER.
Scripted diffs
--------------
For reformatting and refactoring commits where the changes can be easily automated using a bash script, we use
scripted-diff commits. The bash script is included in the commit message and our Travis CI job checks that
the result of the script is identical to the commit. This aids reviewers since they can verify that the script
does exactly what it's supposed to do. It is also helpful for rebasing (since the same script can just be re-run
on the new master commit).
To create a scripted-diff:
- start the commit message with `scripted-diff:` (and then a description of the diff on the same line)
- in the commit message include the bash script between lines containing just the following text:
- `-BEGIN VERIFY SCRIPT-`
- `-END VERIFY SCRIPT-`
The scripted-diff is verified by the tool `contrib/devtools/commit-script-check.sh`
Commit `bb81e173` is an example of a scripted-diff.
RPC interface guidelines
--------------------------

View File

@ -361,7 +361,7 @@ Building Dash Core
----------------
To build Dash Core (for Linux, OS X and Windows) just follow the steps under 'perform
Gitian builds' in [doc/release-process.md](release-process.md#perform-gitian-builds) in the Dash Core repository.
Gitian builds' in [doc/release-process.md](release-process.md#setup-and-perform-gitian-builds) in the Dash Core repository.
This may take some time as it will build all the dependencies needed for each descriptor.
These dependencies will be cached after a successful build to avoid rebuilding them when possible.

View File

@ -243,9 +243,9 @@ dash-${VERSION}-win32.zip
dash-${VERSION}-win64-setup.exe
dash-${VERSION}-win64.zip
```
The `*-debug*` files generated by the gitian build contain debug symbols
The `*-debug*` files generated by the Gitian build contain debug symbols
for troubleshooting by developers. It is assumed that anyone that is interested
in debugging can run gitian to generate the files for themselves. To avoid
in debugging can run Gitian to generate the files for themselves. To avoid
end-user confusion about which file to pick, as well as save storage
space *do not upload these to the dash.org server*.

View File

@ -38,9 +38,9 @@ that the bitcoin-qt.exe file inside the installer had not been tampered with.
However, an attacker could modify the installer's code, so when the setup.exe
was run it compromised users' systems. A volunteer to write an auditing tool
that checks the setup.exe for tampering, and checks the files in it against
the list of gitian signatures, is needed.
the list of Gitian signatures, is needed.
The long-term solution is something like the 'gitian downloader' system, which
uses signatures from multiple developers to determine whether or not a binary
should be trusted. However, that just pushes the problem to "how will
non-technical users securely get the gitian downloader code to start?"
non-technical users securely get the Gitian downloader code to start?"

View File

@ -252,6 +252,8 @@ BITCOIN_CORE_H = \
wallet/coincontrol.h \
wallet/crypter.h \
wallet/db.h \
wallet/fees.h \
wallet/init.h \
wallet/rpcwallet.h \
wallet/wallet.h \
wallet/walletdb.h \
@ -374,6 +376,8 @@ libdash_wallet_a_SOURCES = \
privatesend/privatesend-util.cpp \
wallet/crypter.cpp \
wallet/db.cpp \
wallet/fees.cpp \
wallet/init.cpp \
wallet/rpcdump.cpp \
wallet/rpcwallet.cpp \
wallet/wallet.cpp \

View File

@ -37,7 +37,7 @@ public:
SetNull();
}
CBanEntry(int64_t nCreateTimeIn)
explicit CBanEntry(int64_t nCreateTimeIn)
{
SetNull();
nCreateTime = nCreateTimeIn;

View File

@ -218,7 +218,7 @@ private:
CBitcoinAddress* addr;
public:
CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
explicit CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
@ -276,11 +276,11 @@ bool CBitcoinAddress::GetIndexKey(uint160& hashBytes, int& type) const
if (!IsValid()) {
return false;
} else if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) {
memcpy(&hashBytes, &vchData[0], 20);
memcpy(&hashBytes, vchData.data(), 20);
type = 1;
return true;
} else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) {
memcpy(&hashBytes, &vchData[0], 20);
memcpy(&hashBytes, vchData.data(), 20);
type = 2;
return true;
}

View File

@ -67,7 +67,7 @@ static void CCheckQueueSpeedPrevectorJob(benchmark::State& state)
prevector<PREVECTOR_SIZE, uint8_t> p;
PrevectorJob(){
}
PrevectorJob(FastRandomContext& insecure_rand){
explicit PrevectorJob(FastRandomContext& insecure_rand){
p.resize(insecure_rand.randrange(PREVECTOR_SIZE*2));
}
bool operator()()

View File

@ -48,7 +48,7 @@ static void HASH_SHA256_0032b(benchmark::State& state)
std::vector<uint8_t> in(32,0);
while (state.KeepRunning()) {
for (int i = 0; i < 1000000; i++) {
CSHA256().Write(in.data(), in.size()).Finalize(&in[0]);
CSHA256().Write(in.data(), in.size()).Finalize(in.data());
}
}
}
@ -66,7 +66,7 @@ static void HASH_DSHA256_0032b(benchmark::State& state)
std::vector<uint8_t> in(32,0);
while (state.KeepRunning()) {
for (int i = 0; i < 1000000; i++) {
CHash256().Write(in.data(), in.size()).Finalize(&in[0]);
CHash256().Write(in.data(), in.size()).Finalize(in.data());
}
}
}
@ -123,42 +123,42 @@ static void HASH_DSHA256_0032b_single(benchmark::State& state)
{
std::vector<uint8_t> in(32,0);
while (state.KeepRunning())
CHash256().Write(in.data(), in.size()).Finalize(&in[0]);
CHash256().Write(in.data(), in.size()).Finalize(in.data());
}
static void HASH_DSHA256_0080b_single(benchmark::State& state)
{
std::vector<uint8_t> in(80,0);
while (state.KeepRunning())
CHash256().Write(in.data(), in.size()).Finalize(&in[0]);
CHash256().Write(in.data(), in.size()).Finalize(in.data());
}
static void HASH_DSHA256_0128b_single(benchmark::State& state)
{
std::vector<uint8_t> in(128,0);
while (state.KeepRunning())
CHash256().Write(in.data(), in.size()).Finalize(&in[0]);
CHash256().Write(in.data(), in.size()).Finalize(in.data());
}
static void HASH_DSHA256_0512b_single(benchmark::State& state)
{
std::vector<uint8_t> in(512,0);
while (state.KeepRunning())
CHash256().Write(in.data(), in.size()).Finalize(&in[0]);
CHash256().Write(in.data(), in.size()).Finalize(in.data());
}
static void HASH_DSHA256_1024b_single(benchmark::State& state)
{
std::vector<uint8_t> in(1024,0);
while (state.KeepRunning())
CHash256().Write(in.data(), in.size()).Finalize(&in[0]);
CHash256().Write(in.data(), in.size()).Finalize(in.data());
}
static void HASH_DSHA256_2048b_single(benchmark::State& state)
{
std::vector<uint8_t> in(2048,0);
while (state.KeepRunning())
CHash256().Write(in.data(), in.size()).Finalize(&in[0]);
CHash256().Write(in.data(), in.size()).Finalize(in.data());
}
static void HASH_X11(benchmark::State& state)

View File

@ -37,7 +37,7 @@ SecureString CMnemonic::Generate(int strength)
return SecureString();
}
SecureVector data(32);
GetStrongRandBytes(&data[0], 32);
GetStrongRandBytes(data.data(), 32);
SecureString mnemonic = FromData(data, strength / 8);
return mnemonic;
}
@ -50,11 +50,11 @@ SecureString CMnemonic::FromData(const SecureVector& data, int len)
}
SecureVector checksum(32);
CSHA256().Write(&data[0], len).Finalize(&checksum[0]);
CSHA256().Write(data.data(), len).Finalize(checksum.data());
// data
SecureVector bits(len);
memcpy(&bits[0], &data[0], len);
memcpy(bits.data(), data.data(), len);
// checksum
bits.push_back(checksum[0]);
@ -132,7 +132,7 @@ bool CMnemonic::Check(SecureString mnemonic)
return false;
}
bits[32] = bits[nWordCount * 4 / 3];
CSHA256().Write(&bits[0], nWordCount * 4 / 3).Finalize(&bits[0]);
CSHA256().Write(bits.data(), nWordCount * 4 / 3).Finalize(bits.data());
bool fResult = 0;
if (nWordCount == 12) {
@ -158,5 +158,5 @@ void CMnemonic::ToSeed(SecureString mnemonic, SecureString passphrase, SecureVec
// const unsigned char *salt, int saltlen, int iter,
// const EVP_MD *digest,
// int keylen, unsigned char *out);
PKCS5_PBKDF2_HMAC(mnemonic.c_str(), mnemonic.size(), &vchSalt[0], vchSalt.size(), 2048, EVP_sha512(), 64, &seedRet[0]);
PKCS5_PBKDF2_HMAC(mnemonic.c_str(), mnemonic.size(), vchSalt.data(), vchSalt.size(), 2048, EVP_sha512(), 64, seedRet.data());
}

View File

@ -16,7 +16,7 @@ struct TransactionCompressor {
private:
CTransactionRef& tx;
public:
TransactionCompressor(CTransactionRef& txIn) : tx(txIn) {}
explicit TransactionCompressor(CTransactionRef& txIn) : tx(txIn) {}
ADD_SERIALIZE_METHODS;
@ -75,7 +75,7 @@ public:
std::vector<CTransactionRef> txn;
BlockTransactions() {}
BlockTransactions(const BlockTransactionsRequest& req) :
explicit BlockTransactions(const BlockTransactionsRequest& req) :
blockhash(req.blockhash), txn(req.indexes.size()) {}
ADD_SERIALIZE_METHODS;
@ -198,7 +198,7 @@ protected:
CTxMemPool* pool;
public:
CBlockHeader header;
PartiallyDownloadedBlock(CTxMemPool* poolIn) : pool(poolIn) {}
explicit PartiallyDownloadedBlock(CTxMemPool* poolIn) : pool(poolIn) {}
// extra_txn is a list of extra transactions to look at, in <hash, reference> form
ReadStatus InitData(const CBlockHeaderAndShortTxIDs& cmpctblock, const std::vector<std::pair<uint256, CTransactionRef>>& extra_txn);

View File

@ -158,7 +158,7 @@ private:
std::map<uint256, std::shared_future<CBLSPublicKey> > publicKeyShareCache;
public:
CBLSWorkerCache(CBLSWorker& _worker) :
explicit CBLSWorkerCache(CBLSWorker& _worker) :
worker(_worker) {}
BLSVerificationVectorPtr BuildQuorumVerificationVector(const uint256& cacheKey, const std::vector<BLSVerificationVectorPtr>& vvecs)

View File

@ -70,7 +70,7 @@ private:
map_t mapIndex;
public:
CacheMap(size_type nMaxSizeIn = 0)
explicit CacheMap(size_type nMaxSizeIn = 0)
: nMaxSize(nMaxSizeIn),
listItems(),
mapIndex()

View File

@ -128,7 +128,7 @@ arith_uint256 GetBlockProof(const CBlockIndex& block)
// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
// as it's too large for an arith_uint256. However, as 2**256 is at least as large
// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
// or ~bnTarget / (nTarget+1) + 1.
// or ~bnTarget / (bnTarget+1) + 1.
return (~bnTarget / (bnTarget + 1)) + 1;
}

View File

@ -204,14 +204,14 @@ public:
unsigned int nChainTx;
//! Verification status of this block. See enum BlockStatus
unsigned int nStatus;
uint32_t nStatus;
//! block header
int nVersion;
int32_t nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
uint32_t nTime;
uint32_t nBits;
uint32_t nNonce;
//! (memory only) Sequential id assigned to distinguish order in which blocks are received.
int32_t nSequenceId;
@ -247,7 +247,7 @@ public:
SetNull();
}
CBlockIndex(const CBlockHeader& block)
explicit CBlockIndex(const CBlockHeader& block)
{
SetNull();

View File

@ -131,7 +131,7 @@ public:
boost::mutex ControlMutex;
//! Create a new check queue
CCheckQueue(unsigned int nBatchSizeIn) : nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {}
explicit CCheckQueue(unsigned int nBatchSizeIn) : nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {}
//! Worker thread
void Thread()

View File

@ -53,7 +53,7 @@ protected:
unsigned int GetSpecialSize(unsigned int nSize) const;
bool Decompress(unsigned int nSize, const std::vector<unsigned char> &out);
public:
CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
explicit CScriptCompressor(CScript &scriptIn) : script(scriptIn) { }
template<typename Stream>
void Serialize(Stream &s) const {
@ -99,7 +99,7 @@ public:
static uint64_t CompressAmount(uint64_t nAmount);
static uint64_t DecompressAmount(uint64_t nAmount);
CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
explicit CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
ADD_SERIALIZE_METHODS;

View File

@ -22,7 +22,7 @@ private:
AES128_ctx ctx;
public:
AES128Encrypt(const unsigned char key[16]);
explicit AES128Encrypt(const unsigned char key[16]);
~AES128Encrypt();
void Encrypt(unsigned char ciphertext[16], const unsigned char plaintext[16]) const;
};
@ -34,7 +34,7 @@ private:
AES128_ctx ctx;
public:
AES128Decrypt(const unsigned char key[16]);
explicit AES128Decrypt(const unsigned char key[16]);
~AES128Decrypt();
void Decrypt(unsigned char plaintext[16], const unsigned char ciphertext[16]) const;
};
@ -46,7 +46,7 @@ private:
AES256_ctx ctx;
public:
AES256Encrypt(const unsigned char key[32]);
explicit AES256Encrypt(const unsigned char key[32]);
~AES256Encrypt();
void Encrypt(unsigned char ciphertext[16], const unsigned char plaintext[16]) const;
};
@ -58,7 +58,7 @@ private:
AES256_ctx ctx;
public:
AES256Decrypt(const unsigned char key[32]);
explicit AES256Decrypt(const unsigned char key[32]);
~AES256Decrypt();
void Decrypt(unsigned char plaintext[16], const unsigned char ciphertext[16]) const;
};

View File

@ -58,7 +58,7 @@ public:
* @post All calls to bit_is_set (without subsequent bit_unset) will return
* true.
*/
bit_packed_atomic_flags(uint32_t size)
explicit bit_packed_atomic_flags(uint32_t size)
{
// pad out the size if needed
size = (size + 7) / 8;

View File

@ -24,7 +24,7 @@ static const size_t DBWRAPPER_PREALLOC_VALUE_SIZE = 1024;
class dbwrapper_error : public std::runtime_error
{
public:
dbwrapper_error(const std::string& msg) : std::runtime_error(msg) {}
explicit dbwrapper_error(const std::string& msg) : std::runtime_error(msg) {}
};
class CDBWrapper;
@ -63,7 +63,7 @@ public:
/**
* @param[in] parent CDBWrapper that this batch is to be submitted to
*/
CDBBatch(const CDBWrapper &_parent) : parent(_parent), ssKey(SER_DISK, CLIENT_VERSION), ssValue(SER_DISK, CLIENT_VERSION), size_estimate(0) { };
explicit CDBBatch(const CDBWrapper &_parent) : parent(_parent), ssKey(SER_DISK, CLIENT_VERSION), ssValue(SER_DISK, CLIENT_VERSION), size_estimate(0) { };
void Clear()
{
@ -415,7 +415,7 @@ private:
bool curIsParent{false};
public:
CDBTransactionIterator(CDBTransaction& _transaction) :
explicit CDBTransactionIterator(CDBTransaction& _transaction) :
transaction(_transaction),
parentKey(SER_DISK, CLIENT_VERSION)
{
@ -736,7 +736,7 @@ private:
bool didCommitOrRollback{};
public:
CScopedDBTransaction(Transaction &dbTx) : dbTransaction(dbTx) {}
explicit CScopedDBTransaction(Transaction &dbTx) : dbTransaction(dbTx) {}
~CScopedDBTransaction() {
if (!didCommitOrRollback)
Rollback();

View File

@ -10,7 +10,7 @@
class CDSNotificationInterface : public CValidationInterface
{
public:
CDSNotificationInterface(CConnman& connmanIn): connman(connmanIn) {}
explicit CDSNotificationInterface(CConnman& connmanIn): connman(connmanIn) {}
virtual ~CDSNotificationInterface() = default;
// a small helper to initialize current block height in sub-modules on startup

View File

@ -52,7 +52,7 @@ public:
public:
CDeterministicMNState() {}
CDeterministicMNState(const CProRegTx& proTx)
explicit CDeterministicMNState(const CProRegTx& proTx)
{
keyIDOwner = proTx.keyIDOwner;
pubKeyOperator.Set(proTx.pubKeyOperator);
@ -632,7 +632,7 @@ private:
const CBlockIndex* tipIndex{nullptr};
public:
CDeterministicMNManager(CEvoDB& _evoDb);
explicit CDeterministicMNManager(CEvoDB& _evoDb);
bool ProcessBlock(const CBlock& block, const CBlockIndex* pindex, CValidationState& state, bool fJustCheck);
bool UndoBlock(const CBlock& block, const CBlockIndex* pindex);

View File

@ -28,7 +28,7 @@ private:
CurTransaction curDBTransaction;
public:
CEvoDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);
explicit CEvoDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);
std::unique_ptr<ScopedTransaction> BeginTransaction()
{

View File

@ -33,7 +33,7 @@ public:
public:
CSimplifiedMNListEntry() {}
CSimplifiedMNListEntry(const CDeterministicMN& dmn);
explicit CSimplifiedMNListEntry(const CDeterministicMN& dmn);
bool operator==(const CSimplifiedMNListEntry& rhs) const
{
@ -78,8 +78,8 @@ public:
public:
CSimplifiedMNList() {}
CSimplifiedMNList(const std::vector<CSimplifiedMNListEntry>& smlEntries);
CSimplifiedMNList(const CDeterministicMNList& dmnList);
explicit CSimplifiedMNList(const std::vector<CSimplifiedMNListEntry>& smlEntries);
explicit CSimplifiedMNList(const CDeterministicMNList& dmnList);
uint256 CalcMerkleRoot(bool* pmutated = nullptr) const;
};

View File

@ -97,7 +97,7 @@ private:
// read data and checksum from file
try {
filein.read((char *)&vchData[0], dataSize);
filein.read((char *)vchData.data(), dataSize);
filein >> hashIn;
}
catch (std::exception &e) {

View File

@ -141,7 +141,7 @@ private:
public:
CSuperblock();
CSuperblock(uint256& nHash);
explicit CSuperblock(uint256& nHash);
static bool IsValidBlockHeight(int nBlockHeight);
static void GetNearestSuperblocksHeights(int nBlockHeight, int& nLastSuperblockRet, int& nNextSuperblockRet);

View File

@ -102,20 +102,6 @@ inline uint256 Hash(const T1 p1begin, const T1 p1end,
return result;
}
/** Compute the 256-bit hash of the concatenation of three objects. */
template<typename T1, typename T2, typename T3>
inline uint256 Hash(const T1 p1begin, const T1 p1end,
const T2 p2begin, const T2 p2end,
const T3 p3begin, const T3 p3end) {
static const unsigned char pblank[1] = {};
uint256 result;
CHash256().Write(p1begin == p1end ? pblank : (const unsigned char*)&p1begin[0], (p1end - p1begin) * sizeof(p1begin[0]))
.Write(p2begin == p2end ? pblank : (const unsigned char*)&p2begin[0], (p2end - p2begin) * sizeof(p2begin[0]))
.Write(p3begin == p3end ? pblank : (const unsigned char*)&p3begin[0], (p3end - p3begin) * sizeof(p3begin[0]))
.Finalize((unsigned char*)&result);
return result;
}
/** Compute the 256-bit hash of the concatenation of three objects. */
template<typename T1, typename T2, typename T3, typename T4>
inline uint256 Hash(const T1 p1begin, const T1 p1end,
@ -236,7 +222,7 @@ private:
Source* source;
public:
CHashVerifier(Source* source_) : CHashWriter(source_->GetType(), source_->GetVersion()), source(source_) {}
explicit CHashVerifier(Source* source_) : CHashWriter(source_->GetType(), source_->GetVersion()), source(source_) {}
void read(char* pch, size_t nSize)
{

View File

@ -53,7 +53,7 @@ void CHDChain::Debug(const std::string& strName) const
std::cout << "seed: " << HexStr(vchSeed).c_str() << std::endl;
CExtKey extkey;
extkey.SetMaster(&vchSeed[0], vchSeed.size());
extkey.SetMaster(vchSeed.data(), vchSeed.size());
CBitcoinExtKey b58extkey;
b58extkey.SetKey(extkey);
@ -158,7 +158,7 @@ void CHDChain::DeriveChildExtKey(uint32_t nAccountIndex, bool fInternal, uint32_
CExtKey changeKey; //key at m/purpose'/coin_type'/account'/change
CExtKey childKey; //key at m/purpose'/coin_type'/account'/change/address_index
masterKey.SetMaster(&vchSeed[0], vchSeed.size());
masterKey.SetMaster(vchSeed.data(), vchSeed.size());
// Use hardened derivation for purpose, coin_type and account
// (keys >= 0x80000000 are hardened after bip32)

View File

@ -43,7 +43,7 @@ private:
class HTTPRPCTimerInterface : public RPCTimerInterface
{
public:
HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
explicit HTTPRPCTimerInterface(struct event_base* _base) : base(_base)
{
}
const char* Name() override

View File

@ -79,7 +79,7 @@ private:
size_t maxDepth;
public:
WorkQueue(size_t _maxDepth) : running(true),
explicit WorkQueue(size_t _maxDepth) : running(true),
maxDepth(_maxDepth)
{
}

View File

@ -61,7 +61,7 @@ private:
bool replySent;
public:
HTTPRequest(struct evhttp_request* req);
explicit HTTPRequest(struct evhttp_request* req);
~HTTPRequest();
enum RequestMethod {

View File

@ -46,7 +46,7 @@
#include "utilmoneystr.h"
#include "validationinterface.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#include "wallet/init.h"
#endif
#include "masternode/activemasternode.h"
@ -134,12 +134,11 @@ static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets fRequestShutdown, which triggers
// the DetectShutdownThread(), which interrupts the main thread group.
// DetectShutdownThread() then exits, which causes AppInit() to
// continue (it .joins the shutdown thread).
// Shutdown() is then
// called to clean up database connections, and stop other
// signal handler sets fRequestShutdown, which makes main thread's
// WaitForShutdown() interrupts the thread group.
// And then, WaitForShutdown() makes all other on-going threads
// in the thread group join the main thread.
// Shutdown() is then called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
@ -173,7 +172,7 @@ bool ShutdownRequested()
class CCoinsViewErrorCatcher final : public CCoinsViewBacked
{
public:
CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override {
try {
return CCoinsViewBacked::GetCoin(outpoint, coin);
@ -238,9 +237,7 @@ void PrepareShutdown()
privateSendClient.fPrivateSendRunning = false;
privateSendClient.ResetPool();
}
for (CWalletRef pwallet : vpwallets) {
pwallet->Flush(false);
}
FlushWallets();
#endif
MapPort(false);
@ -314,9 +311,7 @@ void PrepareShutdown()
evoDb = nullptr;
}
#ifdef ENABLE_WALLET
for (CWalletRef pwallet : vpwallets) {
pwallet->Flush(true);
}
StopWallets();
#endif
#if ENABLE_ZMQ
@ -369,10 +364,7 @@ void Shutdown()
// Shutdown part 2: Stop TOR thread and delete wallet instance
StopTorControl();
#ifdef ENABLE_WALLET
for (CWalletRef pwallet : vpwallets) {
delete pwallet;
}
vpwallets.clear();
CloseWallets();
#endif
globalVerifyHandle.reset();
ECC_Stop();
@ -519,7 +511,7 @@ std::string HelpMessage(HelpMessageMode mode)
strUsage += HelpMessageOpt("-maxuploadtarget=<n>", strprintf(_("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)"), DEFAULT_MAX_UPLOAD_TARGET));
#ifdef ENABLE_WALLET
strUsage += CWallet::GetWalletHelpString(showDebug);
strUsage += GetWalletHelpString(showDebug);
if (mode == HMM_BITCOIN_QT)
strUsage += HelpMessageOpt("-windowtitle=<name>", _("Wallet window title"));
#endif
@ -1260,7 +1252,7 @@ bool AppInitParameterInteraction()
RegisterAllCoreRPCCommands(tableRPC);
#ifdef ENABLE_WALLET
RegisterWalletRPCCommands(tableRPC);
RegisterWalletRPC(tableRPC);
#endif
nConnectTimeout = gArgs.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
@ -1272,7 +1264,7 @@ bool AppInitParameterInteraction()
if (!ParseMoney(gArgs.GetArg("-minrelaytxfee", ""), n)) {
return InitError(AmountErrMsg("minrelaytxfee", gArgs.GetArg("-minrelaytxfee", "")));
}
// High fee check is done afterward in CWallet::ParameterInteraction()
// High fee check is done afterward in WalletParameterInteraction()
::minRelayTxFee = CFeeRate(n);
} else if (incrementalRelayFee > ::minRelayTxFee) {
// Allow only setting incrementalRelayFee to control both
@ -1305,7 +1297,7 @@ bool AppInitParameterInteraction()
nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp);
#ifdef ENABLE_WALLET
if (!CWallet::ParameterInteraction())
if (!WalletParameterInteraction())
return false;
#endif // ENABLE_WALLET
@ -1596,7 +1588,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
if (!CWallet::InitAutoBackup())
return false;
if (!CWallet::Verify())
if (!VerifyWallets())
return false;
// Initialize KeePass Integration
@ -1973,7 +1965,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
// ********************************************************* Step 8: load wallet
#ifdef ENABLE_WALLET
if (!CWallet::InitLoadWallet())
if (!OpenWallets())
return false;
#else
LogPrintf("No wallet support compiled in!\n");
@ -2269,9 +2261,7 @@ bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler)
uiInterface.InitMessage(_("Done loading"));
#ifdef ENABLE_WALLET
for (CWalletRef pwallet : vpwallets) {
pwallet->postInitProcess(scheduler);
}
StartWallets(scheduler);
#endif
// Final check if the user requested to kill the GUI during one of the last operations. If so, exit.

View File

@ -41,7 +41,7 @@ SecureString DecodeBase64Secure(const SecureString& sInput)
BIO *b64, *mem;
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); //Do not use newlines to flush buffer
mem = BIO_new_mem_buf((void *) &sInput[0], sInput.size());
mem = BIO_new_mem_buf((void *) sInput.data(), sInput.size());
BIO_push(b64, mem);
// Prepare buffer to receive decoded data
@ -53,7 +53,7 @@ SecureString DecodeBase64Secure(const SecureString& sInput)
// Decode the string
size_t nLen;
nLen = BIO_read(b64, (void *) &output[0], sInput.size());
nLen = BIO_read(b64, (void *) output.data(), sInput.size());
output.resize(nLen);
// Free memory
@ -72,7 +72,7 @@ SecureString EncodeBase64Secure(const SecureString& sInput)
BIO_push(b64, mem);
// Decode the string
BIO_write(b64, &sInput[0], sInput.size());
BIO_write(b64, sInput.data(), sInput.size());
(void) BIO_flush(b64);
// Create output variable from buffer mem ptr
@ -145,10 +145,10 @@ std::string CKeePassIntegrator::CKeePassRequest::getJson()
void CKeePassIntegrator::CKeePassRequest::init()
{
SecureString sIVSecure = generateRandomKey(KEEPASS_CRYPTO_BLOCK_SIZE);
strIV = std::string(&sIVSecure[0], sIVSecure.size());
strIV = std::string(sIVSecure.data(), sIVSecure.size());
// Generate Nonce, Verifier and RequestType
SecureString sNonceBase64Secure = EncodeBase64Secure(sIVSecure);
addStrParameter("Nonce", std::string(&sNonceBase64Secure[0], sNonceBase64Secure.size())); // Plain
addStrParameter("Nonce", std::string(sNonceBase64Secure.data(), sNonceBase64Secure.size())); // Plain
addStrParameter("Verifier", sNonceBase64Secure); // Encoded
addStrParameter("RequestType", strType);
}
@ -228,7 +228,7 @@ SecureString CKeePassIntegrator::generateRandomKey(size_t nSize)
SecureString sKey;
sKey.resize(nSize);
GetStrongRandBytes((unsigned char *) &sKey[0], nSize);
GetStrongRandBytes((unsigned char *) sKey.data(), nSize);
return sKey;
}
@ -463,7 +463,7 @@ void CKeePassIntegrator::rpcAssociate(std::string& strIdRet, SecureString& sKeyB
CKeePassRequest request(sKey, "associate");
sKeyBase64Ret = EncodeBase64Secure(sKey);
request.addStrParameter("Key", std::string(&sKeyBase64Ret[0], sKeyBase64Ret.size()));
request.addStrParameter("Key", std::string(sKeyBase64Ret.data(), sKeyBase64Ret.size()));
int nStatus;
std::string strResponse;

View File

@ -56,11 +56,6 @@ public:
keydata.resize(32);
}
//! Destructor (again necessary because of memlocking).
~CKey()
{
}
friend bool operator==(const CKey& a, const CKey& b)
{
return a.fCompressed == b.fCompressed &&

View File

@ -31,7 +31,7 @@ public:
//! Check whether a key corresponding to a given address is present in the store.
virtual bool HaveKey(const CKeyID &address) const =0;
virtual bool GetKey(const CKeyID &address, CKey& keyOut) const =0;
virtual void GetKeys(std::set<CKeyID> &setAddress) const =0;
virtual std::set<CKeyID> GetKeys() const =0;
virtual bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const =0;
//! Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki
@ -74,18 +74,14 @@ public:
}
return result;
}
void GetKeys(std::set<CKeyID> &setAddress) const override
std::set<CKeyID> GetKeys() const override
{
setAddress.clear();
{
LOCK(cs_KeyStore);
KeyMap::const_iterator mi = mapKeys.begin();
while (mi != mapKeys.end())
{
setAddress.insert((*mi).first);
mi++;
}
LOCK(cs_KeyStore);
std::set<CKeyID> set_address;
for (const auto& mi : mapKeys) {
set_address.insert(mi.first);
}
return set_address;
}
bool GetKey(const CKeyID &address, CKey &keyOut) const override
{

View File

@ -33,7 +33,7 @@ protected:
size_type nPruneAfterSize;
public:
unordered_limitedmap(size_type nMaxSizeIn, size_type nPruneAfterSizeIn = 0)
explicit unordered_limitedmap(size_type nMaxSizeIn, size_type nPruneAfterSizeIn = 0)
{
assert(nMaxSizeIn > 0);
nMaxSize = nMaxSizeIn;

View File

@ -35,7 +35,7 @@ private:
std::unordered_map<std::pair<Consensus::LLMQType, uint256>, bool, StaticSaltedHasher> hasMinedCommitmentCache;
public:
CQuorumBlockProcessor(CEvoDB& _evoDb) : evoDb(_evoDb) {}
explicit CQuorumBlockProcessor(CEvoDB& _evoDb) : evoDb(_evoDb) {}
void UpgradeDB();

View File

@ -78,7 +78,7 @@ private:
int64_t lastCleanupTime{0};
public:
CChainLocksHandler(CScheduler* _scheduler);
explicit CChainLocksHandler(CScheduler* _scheduler);
~CChainLocksHandler();
void Start();

View File

@ -97,7 +97,7 @@ public:
public:
CDKGComplaint() {}
CDKGComplaint(const Consensus::LLMQParams& params);
explicit CDKGComplaint(const Consensus::LLMQParams& params);
ADD_SERIALIZE_METHODS
@ -170,7 +170,7 @@ public:
public:
CDKGPrematureCommitment() {}
CDKGPrematureCommitment(const Consensus::LLMQParams& params);
explicit CDKGPrematureCommitment(const Consensus::LLMQParams& params);
int CountValidMembers() const
{

View File

@ -46,7 +46,7 @@ private:
std::set<uint256> seenMessages;
public:
CDKGPendingMessages(size_t _maxMessagesPerNode);
explicit CDKGPendingMessages(size_t _maxMessagesPerNode);
void PushPendingMessage(NodeId from, CDataStream& vRecv);
std::list<BinaryMessage> PopPendingMessages(size_t maxCount);

View File

@ -50,7 +50,7 @@ private:
unordered_lru_cache<COutPoint, uint256, SaltedOutpointHasher, 10000> outpointCache;
public:
CInstantSendDb(CDBWrapper& _db) : db(_db) {}
explicit CInstantSendDb(CDBWrapper& _db) : db(_db) {}
void WriteNewInstantSendLock(const uint256& hash, const CInstantSendLock& islock);
void RemoveInstantSendLock(CDBBatch& batch, const uint256& hash, CInstantSendLockPtr islock);
@ -112,7 +112,7 @@ private:
std::unordered_set<uint256, StaticSaltedHasher> pendingRetryTxs;
public:
CInstantSendManager(CDBWrapper& _llmqDb);
explicit CInstantSendManager(CDBWrapper& _llmqDb);
~CInstantSendManager();
void Start();

View File

@ -72,7 +72,7 @@ private:
unordered_lru_cache<uint256, bool, StaticSaltedHasher, 30000> hasSigForHashCache;
public:
CRecoveredSigsDb(CDBWrapper& _db);
explicit CRecoveredSigsDb(CDBWrapper& _db);
void ConvertInvalidTimeKeys();
void AddVoteTimeKeys();

View File

@ -35,7 +35,7 @@ private:
public:
CMasternodeMetaInfo() {}
CMasternodeMetaInfo(const uint256& _proTxHash) : proTxHash(_proTxHash) {}
explicit CMasternodeMetaInfo(const uint256& _proTxHash) : proTxHash(_proTxHash) {}
CMasternodeMetaInfo(const CMasternodeMetaInfo& ref) :
proTxHash(ref.proTxHash),
nLastDsq(ref.nLastDsq),

View File

@ -65,7 +65,7 @@ bool CHashSigner::VerifyHash(const uint256& hash, const CKeyID& keyID, const std
if(pubkeyFromSig.GetID() != keyID) {
strErrorRet = strprintf("Keys don't match: pubkey=%s, pubkeyFromSig=%s, hash=%s, vchSig=%s",
keyID.ToString(), pubkeyFromSig.GetID().ToString(), hash.ToString(),
EncodeBase64(&vchSig[0], vchSig.size()));
EncodeBase64(vchSig.data(), vchSig.size()));
return false;
}

View File

@ -136,6 +136,7 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
LOCK2(cs_main, mempool.cs);
CBlockIndex* pindexPrev = chainActive.Tip();
assert(pindexPrev != nullptr);
nHeight = pindexPrev->nHeight + 1;
bool fDIP0003Active_context = nHeight >= chainparams.GetConsensus().DIP0003Height;

View File

@ -36,7 +36,7 @@ struct CBlockTemplate
// Container for tracking updates to ancestor feerate as we include (parent)
// transactions in a block
struct CTxMemPoolModifiedEntry {
CTxMemPoolModifiedEntry(CTxMemPool::txiter entry)
explicit CTxMemPoolModifiedEntry(CTxMemPool::txiter entry)
{
iter = entry;
nSizeWithAncestors = entry->GetSizeWithAncestors();
@ -119,7 +119,7 @@ typedef indexed_modified_transaction_set::index<ancestor_score>::type::iterator
struct update_for_parent_inclusion
{
update_for_parent_inclusion(CTxMemPool::txiter it) : iter(it) {}
explicit update_for_parent_inclusion(CTxMemPool::txiter it) : iter(it) {}
void operator() (CTxMemPoolModifiedEntry &e)
{
@ -163,7 +163,7 @@ public:
CFeeRate blockMinFeeRate;
};
BlockAssembler(const CChainParams& params);
explicit BlockAssembler(const CChainParams& params);
BlockAssembler(const CChainParams& params, const Options& options);
/** Construct a new block template with coinbase to scriptPubKeyIn */

View File

@ -337,6 +337,7 @@ bool MarkBlockAsReceived(const uint256& hash) {
std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
if (itInFlight != mapBlocksInFlight.end()) {
CNodeState *state = State(itInFlight->second.first);
assert(state != nullptr);
state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders;
if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) {
// Last validated block on the queue was received.
@ -3470,7 +3471,7 @@ class CompareInvMempoolOrder
{
CTxMemPool *mp;
public:
CompareInvMempoolOrder(CTxMemPool *_mempool)
explicit CompareInvMempoolOrder(CTxMemPool *_mempool)
{
mp = _mempool;
}

View File

@ -38,7 +38,7 @@ class CNetAddr
public:
CNetAddr();
CNetAddr(const struct in_addr& ipv4Addr);
explicit CNetAddr(const struct in_addr& ipv4Addr);
void Init();
void SetIP(const CNetAddr& ip);
@ -84,7 +84,7 @@ class CNetAddr
std::vector<unsigned char> GetGroup() const;
int GetReachabilityFrom(const CNetAddr *paddrPartner = nullptr) const;
CNetAddr(const struct in6_addr& pipv6Addr, const uint32_t scope = 0);
explicit CNetAddr(const struct in6_addr& pipv6Addr, const uint32_t scope = 0);
bool GetIn6Addr(struct in6_addr* pipv6Addr) const;
friend bool operator==(const CNetAddr& a, const CNetAddr& b);
@ -148,7 +148,7 @@ class CService : public CNetAddr
CService();
CService(const CNetAddr& ip, unsigned short port);
CService(const struct in_addr& ipv4Addr, unsigned short port);
CService(const struct sockaddr_in& addr);
explicit CService(const struct sockaddr_in& addr);
void Init();
void SetPort(unsigned short portIn);
unsigned short GetPort() const;
@ -163,7 +163,7 @@ class CService : public CNetAddr
std::string ToStringIPPort(bool fUseGetnameinfo = true) const;
CService(const struct in6_addr& ipv6Addr, unsigned short port);
CService(const struct sockaddr_in6& addr);
explicit CService(const struct sockaddr_in6& addr);
ADD_SERIALIZE_METHODS;

View File

@ -30,7 +30,7 @@ class proxyType
{
public:
proxyType(): randomize_credentials(false) {}
proxyType(const CService &_proxy, bool _randomize_credentials=false): proxy(_proxy), randomize_credentials(_randomize_credentials) {}
explicit proxyType(const CService &_proxy, bool _randomize_credentials=false): proxy(_proxy), randomize_credentials(_randomize_credentials) {}
bool IsValid() const { return proxy.IsValid(); }

View File

@ -12,7 +12,7 @@
class CNetMsgMaker
{
public:
CNetMsgMaker(int nVersionIn) : nVersion(nVersionIn){}
explicit CNetMsgMaker(int nVersionIn) : nVersion(nVersionIn){}
template <typename... Args>
CSerializedNetMsg Make(int nFlags, std::string sCommand, Args&&... args) const

View File

@ -130,7 +130,7 @@ struct CBlockLocator
CBlockLocator() {}
CBlockLocator(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) {}
explicit CBlockLocator(const std::vector<uint256>& vHaveIn) : vHave(vHaveIn) {}
ADD_SERIALIZE_METHODS;

View File

@ -61,7 +61,7 @@ std::string CTxOut::ToString() const
}
CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nType(TRANSACTION_NORMAL), nLockTime(0) {}
CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), nType(tx.nType), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), vExtraPayload(tx.vExtraPayload) {}
CMutableTransaction::CMutableTransaction(const CTransaction& tx) : vin(tx.vin), vout(tx.vout), nVersion(tx.nVersion), nType(tx.nType), nLockTime(tx.nLockTime), vExtraPayload(tx.vExtraPayload) {}
uint256 CMutableTransaction::GetHash() const
{
@ -92,9 +92,9 @@ uint256 CTransaction::ComputeHash() const
}
/* For backward compatibility, the hash is initialized to 0. TODO: remove the need for this default constructor entirely. */
CTransaction::CTransaction() : nVersion(CTransaction::CURRENT_VERSION), nType(TRANSACTION_NORMAL), vin(), vout(), nLockTime(0), hash() {}
CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), nType(tx.nType), vin(tx.vin), vout(tx.vout), nLockTime(tx.nLockTime), vExtraPayload(tx.vExtraPayload), hash(ComputeHash()) {}
CTransaction::CTransaction(CMutableTransaction &&tx) : nVersion(tx.nVersion), nType(tx.nType), vin(std::move(tx.vin)), vout(std::move(tx.vout)), nLockTime(tx.nLockTime), vExtraPayload(tx.vExtraPayload), hash(ComputeHash()) {}
CTransaction::CTransaction() : vin(), vout(), nVersion(CTransaction::CURRENT_VERSION), nType(TRANSACTION_NORMAL), nLockTime(0), hash() {}
CTransaction::CTransaction(const CMutableTransaction &tx) : vin(tx.vin), vout(tx.vout), nVersion(tx.nVersion), nType(tx.nType), nLockTime(tx.nLockTime), vExtraPayload(tx.vExtraPayload), hash(ComputeHash()) {}
CTransaction::CTransaction(CMutableTransaction &&tx) : vin(std::move(tx.vin)), vout(std::move(tx.vout)), nVersion(tx.nVersion), nType(tx.nType), nLockTime(tx.nLockTime), vExtraPayload(tx.vExtraPayload), hash(ComputeHash()) {}
CAmount CTransaction::GetValueOut() const
{

View File

@ -212,10 +212,10 @@ public:
// actually immutable; deserialization and assignment are implemented,
// and bypass the constness. This is safe, as they update the entire
// structure, including the hash.
const int16_t nVersion;
const int16_t nType;
const std::vector<CTxIn> vin;
const std::vector<CTxOut> vout;
const int16_t nVersion;
const int16_t nType;
const uint32_t nLockTime;
const std::vector<uint8_t> vExtraPayload; // only available for special transaction types
@ -290,10 +290,10 @@ public:
/** A mutable version of CTransaction. */
struct CMutableTransaction
{
int16_t nVersion;
int16_t nType;
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
int16_t nVersion;
int16_t nType;
uint32_t nLockTime;
std::vector<uint8_t> vExtraPayload; // only available for special transaction types

View File

@ -39,7 +39,7 @@ public:
};
typedef unsigned char MessageStartChars[MESSAGE_START_SIZE];
CMessageHeader(const MessageStartChars& pchMessageStartIn);
explicit CMessageHeader(const MessageStartChars& pchMessageStartIn);
CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn);
std::string GetCommand() const;

View File

@ -30,7 +30,7 @@ class CKeyID : public uint160
{
public:
CKeyID() : uint160() {}
CKeyID(const uint160& in) : uint160(in) {}
explicit CKeyID(const uint160& in) : uint160(in) {}
};
typedef uint256 ChainCode;
@ -88,7 +88,7 @@ public:
}
//! Construct a public key from a byte vector.
CPubKey(const std::vector<unsigned char>& _vch)
explicit CPubKey(const std::vector<unsigned char>& _vch)
{
Set(_vch.begin(), _vch.end());
}

View File

@ -16,7 +16,7 @@ class FunctionCallback : public Callback
F f;
public:
FunctionCallback(F f_) : f(std::move(f_)) {}
explicit FunctionCallback(F f_) : f(std::move(f_)) {}
~FunctionCallback() override {}
void call() override { f(this); }
};

View File

@ -19,6 +19,7 @@
#include "policy/fees.h"
#include "policy/policy.h"
#include "validation.h" // For mempool
#include "wallet/fees.h"
#include "wallet/wallet.h"
#include "privatesend/privatesend-client.h"
@ -547,7 +548,7 @@ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog)
nBytes -= 34;
// Fee
nPayFee = CWallet::GetMinimumFee(nBytes, *coinControl, ::mempool, ::feeEstimator, nullptr /* FeeCalculation */);
nPayFee = GetMinimumFee(nBytes, *coinControl, ::mempool, ::feeEstimator, nullptr /* FeeCalculation */);
if (nPayAmount > 0)
{

View File

@ -30,9 +30,9 @@ namespace Ui {
class CCoinControlWidgetItem : public QTreeWidgetItem
{
public:
CCoinControlWidgetItem(QTreeWidget *parent, int type = Type) : QTreeWidgetItem(parent, type) {}
CCoinControlWidgetItem(int type = Type) : QTreeWidgetItem(type) {}
CCoinControlWidgetItem(QTreeWidgetItem *parent, int type = Type) : QTreeWidgetItem(parent, type) {}
explicit CCoinControlWidgetItem(QTreeWidget *parent, int type = Type) : QTreeWidgetItem(parent, type) {}
explicit CCoinControlWidgetItem(int type = Type) : QTreeWidgetItem(type) {}
explicit CCoinControlWidgetItem(QTreeWidgetItem *parent, int type = Type) : QTreeWidgetItem(parent, type) {}
bool operator<(const QTreeWidgetItem &other) const;
};

View File

@ -44,7 +44,7 @@ class FreespaceChecker : public QObject
Q_OBJECT
public:
FreespaceChecker(Intro *intro);
explicit FreespaceChecker(Intro *intro);
enum Status {
ST_OK,

View File

@ -7,20 +7,17 @@
#include <QObject>
/** Macintosh-specific notification handler (supports UserNotificationCenter and Growl).
/** Macintosh-specific notification handler (supports UserNotificationCenter).
*/
class MacNotificationHandler : public QObject
{
Q_OBJECT
public:
/** shows a 10.8+ UserNotification in the UserNotificationCenter
/** shows a macOS 10.8+ UserNotification in the UserNotificationCenter
*/
void showNotification(const QString &title, const QString &text);
/** executes AppleScript */
void sendAppleScript(const QString &script);
/** check if OS can handle UserNotifications */
bool hasUserNotificationCenterSupport(void);
static MacNotificationHandler *instance();

View File

@ -47,20 +47,6 @@ void MacNotificationHandler::showNotification(const QString &title, const QStrin
}
}
// sendAppleScript just take a QString and executes it as apple script
void MacNotificationHandler::sendAppleScript(const QString &script)
{
QByteArray utf8 = script.toUtf8();
char* cString = (char *)utf8.constData();
NSString *scriptApple = [[NSString alloc] initWithUTF8String:cString];
NSAppleScript *as = [[NSAppleScript alloc] initWithSource:scriptApple];
NSDictionary *err = nil;
[as executeAndReturnError:&err];
[as release];
[scriptApple release];
}
bool MacNotificationHandler::hasUserNotificationCenterSupport(void)
{
Class possibleClass = NSClassFromString(@"NSUserNotificationCenter");

View File

@ -60,22 +60,6 @@ Notificator::Notificator(const QString &_programName, QSystemTrayIcon *_trayIcon
if( MacNotificationHandler::instance()->hasUserNotificationCenterSupport()) {
mode = UserNotificationCenter;
}
else {
// Check if Growl is installed (based on Qt's tray icon implementation)
CFURLRef cfurl;
OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, CFSTR("growlTicket"), kLSRolesAll, 0, &cfurl);
if (status != kLSApplicationNotFoundErr) {
CFBundleRef bundle = CFBundleCreate(0, cfurl);
if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR("com.Growl.GrowlHelperApp"), kCFCompareCaseInsensitive | kCFCompareBackwards) == kCFCompareEqualTo) {
if (CFStringHasSuffix(CFURLGetString(cfurl), CFSTR("/Growl.app/")))
mode = Growl13;
else
mode = Growl12;
}
CFRelease(cfurl);
CFRelease(bundle);
}
}
#endif
}
@ -93,7 +77,7 @@ class FreedesktopImage
{
public:
FreedesktopImage() {}
FreedesktopImage(const QImage &img);
explicit FreedesktopImage(const QImage &img);
static int metaType();
@ -241,52 +225,6 @@ void Notificator::notifySystray(Class cls, const QString &title, const QString &
// Based on Qt's tray icon implementation
#ifdef Q_OS_MAC
void Notificator::notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon)
{
const QString script(
"tell application \"%5\"\n"
" set the allNotificationsList to {\"Notification\"}\n" // -- Make a list of all the notification types (all)
" set the enabledNotificationsList to {\"Notification\"}\n" // -- Make a list of the notifications (enabled)
" register as application \"%1\" all notifications allNotificationsList default notifications enabledNotificationsList\n" // -- Register our script with Growl
" notify with name \"Notification\" title \"%2\" description \"%3\" application name \"%1\"%4\n" // -- Send a Notification
"end tell"
);
QString notificationApp(QApplication::applicationName());
if (notificationApp.isEmpty())
notificationApp = "Application";
QPixmap notificationIconPixmap;
if (icon.isNull()) { // If no icon specified, set icon based on class
QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
switch (cls)
{
case Information: sicon = QStyle::SP_MessageBoxInformation; break;
case Warning: sicon = QStyle::SP_MessageBoxWarning; break;
case Critical: sicon = QStyle::SP_MessageBoxCritical; break;
}
notificationIconPixmap = QApplication::style()->standardPixmap(sicon);
}
else {
QSize size = icon.actualSize(QSize(48, 48));
notificationIconPixmap = icon.pixmap(size);
}
QString notificationIcon;
QTemporaryFile notificationIconFile;
if (!notificationIconPixmap.isNull() && notificationIconFile.open()) {
QImageWriter writer(&notificationIconFile, "PNG");
if (writer.write(notificationIconPixmap.toImage()))
notificationIcon = QString(" image from location \"file://%1\"").arg(notificationIconFile.fileName());
}
QString quotedTitle(title), quotedText(text);
quotedTitle.replace("\\", "\\\\").replace("\"", "\\");
quotedText.replace("\\", "\\\\").replace("\"", "\\");
QString growlApp(this->mode == Notificator::Growl13 ? "Growl" : "GrowlHelperApp");
MacNotificationHandler::instance()->sendAppleScript(script.arg(notificationApp, quotedTitle, quotedText, notificationIcon, growlApp));
}
void Notificator::notifyMacUserNotificationCenter(Class cls, const QString &title, const QString &text, const QIcon &icon) {
// icon is not supported by the user notification center yet. OSX will use the app icon.
MacNotificationHandler::instance()->showNotification(title, text);
@ -310,10 +248,6 @@ void Notificator::notify(Class cls, const QString &title, const QString &text, c
case UserNotificationCenter:
notifyMacUserNotificationCenter(cls, title, text, icon);
break;
case Growl12:
case Growl13:
notifyGrowl(cls, title, text, icon);
break;
#endif
default:
if(cls == Critical)

View File

@ -58,8 +58,6 @@ private:
None, /**< Ignore informational notifications, and show a modal pop-up dialog for Critical notifications. */
Freedesktop, /**< Use DBus org.freedesktop.Notifications */
QSystemTray, /**< Use QSystemTray::showMessage */
Growl12, /**< Use the Growl 1.2 notification system (Mac only) */
Growl13, /**< Use the Growl 1.3 notification system (Mac only) */
UserNotificationCenter /**< Use the 10.8+ User Notification Center (Mac only) */
};
QString programName;
@ -72,7 +70,6 @@ private:
#endif
void notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout);
#ifdef Q_OS_MAC
void notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon);
void notifyMacUserNotificationCenter(Class cls, const QString &title, const QString &text, const QIcon &icon);
#endif
};

View File

@ -18,8 +18,6 @@
#include "txdb.h" // for -dbcache defaults
#ifdef ENABLE_WALLET
#include "wallet/wallet.h" // for CWallet::GetRequiredFee()
#include "privatesend/privatesend-client.h"
#endif // ENABLE_WALLET
@ -82,14 +80,14 @@ OptionsDialog::OptionsDialog(QWidget *parent, bool enableWallet) :
}
/* Display elements init */
/* Number of displayed decimal digits selector */
QString digits;
for(int index = 2; index <=8; index++){
digits.setNum(index);
ui->digits->addItem(digits, digits);
}
/* Theme selector */
ui->theme->addItem(QString("Dark"), QVariant("dark"));
ui->theme->addItem(QString("Light"), QVariant("light"));

View File

@ -34,7 +34,7 @@ class TxViewDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
TxViewDelegate(const PlatformStyle *_platformStyle, QObject *parent=nullptr):
explicit TxViewDelegate(const PlatformStyle *_platformStyle, QObject *parent=nullptr):
QAbstractItemDelegate(), unit(BitcoinUnits::DASH),
platformStyle(_platformStyle)
{

View File

@ -22,7 +22,7 @@
class SSLVerifyError : public std::runtime_error
{
public:
SSLVerifyError(std::string err) : std::runtime_error(err) { }
explicit SSLVerifyError(std::string err) : std::runtime_error(err) { }
};
bool PaymentRequestPlus::parse(const QByteArray& data)

View File

@ -72,7 +72,7 @@ public:
static bool ipcSendCommandLine();
// parent should be QApplication object
PaymentServer(QObject* parent, bool startLocalServer = true);
explicit PaymentServer(QObject* parent, bool startLocalServer = true);
~PaymentServer();
// Load root certificate authorities. Pass nullptr (default)

View File

@ -22,7 +22,7 @@
#include "ui_interface.h"
#include "txmempool.h"
#include "policy/fees.h"
#include "wallet/wallet.h"
#include "wallet/fees.h"
#include "privatesend/privatesend.h"
#include "privatesend/privatesend-client.h"
@ -210,7 +210,7 @@ void SendCoinsDialog::setModel(WalletModel *_model)
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(setMinimumFee()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateFeeSectionControls()));
connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels()));
ui->customFee->setSingleStep(CWallet::GetRequiredFee(1000));
ui->customFee->setSingleStep(GetRequiredFee(1000));
updateFeeSectionControls();
updateMinFeeLabel();
updateSmartFeeLabel();
@ -709,7 +709,7 @@ void SendCoinsDialog::on_buttonMinimizeFee_clicked()
void SendCoinsDialog::setMinimumFee()
{
ui->customFee->setValue(CWallet::GetRequiredFee(1000));
ui->customFee->setValue(GetRequiredFee(1000));
}
void SendCoinsDialog::updateFeeSectionControls()
@ -741,7 +741,7 @@ void SendCoinsDialog::updateMinFeeLabel()
{
if (model && model->getOptionsModel())
ui->checkBoxMinimumFee->setText(tr("Pay only the required fee of %1").arg(
BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::GetRequiredFee(1000)) + "/kB")
BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), GetRequiredFee(1000)) + "/kB")
);
}
@ -765,7 +765,7 @@ void SendCoinsDialog::updateSmartFeeLabel()
updateCoinControlState(coin_control);
coin_control.m_feerate.reset(); // Explicitly use only fee estimation rate for smart fee labels
FeeCalculation feeCalc;
CFeeRate feeRate = CFeeRate(CWallet::GetMinimumFee(1000, coin_control, ::mempool, ::feeEstimator, &feeCalc));
CFeeRate feeRate = CFeeRate(GetMinimumFee(1000, coin_control, ::mempool, ::feeEstimator, &feeCalc));
ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB");

View File

@ -175,7 +175,7 @@ void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
ui->statusLabel_SM->setStyleSheet(GUIUtil::getThemedStyleQString(GUIUtil::ThemedStyle::TS_SUCCESS));
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));
ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(vchSig.data(), vchSig.size())));
}
void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()

View File

@ -24,7 +24,7 @@ X509 *parse_b64der_cert(const char* cert_data)
{
std::vector<unsigned char> data = DecodeBase64(cert_data);
assert(data.size() > 0);
const unsigned char* dptr = &data[0];
const unsigned char* dptr = data.data();
X509 *cert = d2i_X509(nullptr, &dptr, data.size());
assert(cert);
return cert;
@ -43,7 +43,7 @@ static SendCoinsRecipient handleRequest(PaymentServer* server, std::vector<unsig
// Write data to a temp file:
QTemporaryFile f;
f.open();
f.write((const char*)&data[0], data.size());
f.write((const char*)data.data(), data.size());
f.close();
// Create a QObject, install event filter from PaymentServer
@ -139,7 +139,7 @@ void PaymentServerTests::paymentServerTests()
// Contains a testnet paytoaddress, so payment request network doesn't match client network:
data = DecodeBase64(paymentrequest1_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
byteArray = QByteArray((const char*)data.data(), data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized, because network "main" is default, even for
// uninitialized payment requests and that will fail our test here.
@ -148,7 +148,7 @@ void PaymentServerTests::paymentServerTests()
// Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):
data = DecodeBase64(paymentrequest2_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
byteArray = QByteArray((const char*)data.data(), data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
@ -159,7 +159,7 @@ void PaymentServerTests::paymentServerTests()
// 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t)
// -1 is 1969-12-31 23:59:59 (for a 32 bit time values)
data = DecodeBase64(paymentrequest3_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
byteArray = QByteArray((const char*)data.data(), data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
@ -170,7 +170,7 @@ void PaymentServerTests::paymentServerTests()
// 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t)
// 0 is 1970-01-01 00:00:00 (for a 32 bit time values)
data = DecodeBase64(paymentrequest4_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
byteArray = QByteArray((const char*)data.data(), data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());
@ -190,7 +190,7 @@ void PaymentServerTests::paymentServerTests()
// Payment request with amount overflow (amount is set to 21000001 BTC):
data = DecodeBase64(paymentrequest5_cert2_BASE64);
byteArray = QByteArray((const char*)&data[0], data.size());
byteArray = QByteArray((const char*)data.data(), data.size());
r.paymentRequest.parse(byteArray);
// Ensure the request is initialized
QVERIFY(r.paymentRequest.IsInitialized());

View File

@ -47,7 +47,7 @@ class ShutdownWindow : public QWidget
Q_OBJECT
public:
ShutdownWindow(QWidget *parent=0, Qt::WindowFlags f=0);
explicit ShutdownWindow(QWidget *parent=0, Qt::WindowFlags f=0);
static QWidget *showShutdownWindow(BitcoinGUI *window);
protected:

View File

@ -7,6 +7,7 @@
#include "bitcoingui.h"
#include "walletview.h"
#include <cassert>
#include <cstdio>
#include <QHBoxLayout>
@ -69,6 +70,7 @@ bool WalletFrame::setCurrentWallet(const QString& name)
WalletView *walletView = mapWalletViews.value(name);
walletStack->setCurrentWidget(walletView);
assert(walletView);
walletView->updateEncryptionStatus();
return true;
}

View File

@ -387,7 +387,7 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(WalletModelTransaction &tran
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << *newTx->tx;
transaction_array.append(&(ssTx[0]), ssTx.size());
transaction_array.append(ssTx.data(), ssTx.size());
}
// Add addresses / update labels that we've sent to the address book,

View File

@ -48,7 +48,7 @@ struct CCoin {
ADD_SERIALIZE_METHODS;
CCoin() : nHeight(0) {}
CCoin(Coin&& in) : nHeight(in.nHeight), out(std::move(in.out)) {}
explicit CCoin(Coin&& in) : nHeight(in.nHeight), out(std::move(in.out)) {}
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)

View File

@ -17,7 +17,7 @@ class reverse_range
T &m_x;
public:
reverse_range(T &x) : m_x(x) {}
explicit reverse_range(T &x) : m_x(x) {}
auto begin() const -> decltype(this->m_x.rbegin())
{

View File

@ -1080,6 +1080,7 @@ static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash,
static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)
{
std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor());
assert(pcursor);
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
stats.hashBlock = pcursor->GetBestBlock();
@ -1643,7 +1644,7 @@ UniValue getmempoolinfo(const JSONRPCRequest& request)
" \"bytes\": xxxxx, (numeric) Sum of all tx sizes\n"
" \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
" \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
" \"mempoolminfee\": xxxxx (numeric) Minimum feerate (" + CURRENCY_UNIT + " per KB) for tx to be accepted\n"
" \"mempoolminfee\": xxxxx (numeric) Minimum fee rate in " + CURRENCY_UNIT + "/kB for tx to be accepted\n"
" \"instantsendlocks\": xxxxx, (numeric) Number of unconfirmed instant send locks\n"
"}\n"
"\nExamples:\n"
@ -1816,6 +1817,8 @@ UniValue getchaintxstats(const JSONRPCRequest& request)
}
}
assert(pindex != nullptr);
if (blockcount < 1 || blockcount >= pindex->nHeight) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid block count: should be between 1 and the block's height");
}

View File

@ -43,8 +43,6 @@ static const CRPCConvertParam vRPCConvertParams[] =
{ "sendtoaddress", 5, "use_is" },
{ "sendtoaddress", 6, "use_ps" },
{ "sendtoaddress", 7, "conf_target" },
{ "instantsendtoaddress", 1, "address" },
{ "instantsendtoaddress", 4, "comment_to" },
{ "settxfee", 0, "amount" },
{ "getreceivedbyaddress", 1, "minconf" },
{ "getreceivedbyaddress", 2, "addlocked" },

View File

@ -1098,7 +1098,7 @@ static const CRPCCommand commands[] =
{ "dash", "getgovernanceinfo", &getgovernanceinfo, {} },
{ "dash", "getsuperblockbudget", &getsuperblockbudget, {"index"} },
{ "dash", "gobject", &gobject, {} },
{ "dash", "voteraw", &voteraw, {} },
{ "dash", "voteraw", &voteraw, {"tx_hash","tx_index","gov_hash","signal","outcome","time","sig"} },
};

View File

@ -721,7 +721,7 @@ public:
bool found;
CValidationState state;
submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
explicit submitblock_StateCatcher(const uint256 &hashIn) : hash(hashIn), found(false), state() {}
protected:
void BlockChecked(const CBlock& block, const CValidationState& stateIn) override {
@ -850,7 +850,7 @@ UniValue estimatesmartfee(const JSONRPCRequest& request)
" \"CONSERVATIVE\"\n"
"\nResult:\n"
"{\n"
" \"feerate\" : x.x, (numeric, optional) estimate fee-per-kilobyte (in " + CURRENCY_UNIT + ")\n"
" \"feerate\" : x.x, (numeric, optional) estimate fee rate in " + CURRENCY_UNIT + "/kB\n"
" \"errors\": [ str... ] (json array of strings, optional) Errors encountered during processing\n"
" \"blocks\" : n (numeric) block number where estimate was found\n"
"}\n"
@ -908,7 +908,7 @@ UniValue estimaterawfee(const JSONRPCRequest& request)
"\nResult:\n"
"{\n"
" \"short\" : { (json object, optional) estimate for short time horizon\n"
" \"feerate\" : x.x, (numeric, optional) estimate fee-per-kilobyte (in " + CURRENCY_UNIT + ")\n"
" \"feerate\" : x.x, (numeric, optional) estimate fee rate in " + CURRENCY_UNIT + "/kB\n"
" \"decay\" : x.x, (numeric) exponential decay (per block) for historical moving average of confirmation data\n"
" \"scale\" : x, (numeric) The resolution of confirmation targets at this time horizon\n"
" \"pass\" : { (json object, optional) information about the lowest range of feerates to succeed in meeting the threshold\n"
@ -1004,7 +1004,7 @@ static const CRPCCommand commands[] =
#endif // ENABLE_MINER
{ "util", "estimatefee", &estimatefee, {"nblocks"} },
{ "util", "estimatesmartfee", &estimatesmartfee, {"nblocks", "estimate_mode"} },
{ "util", "estimatesmartfee", &estimatesmartfee, {"conf_target", "estimate_mode"} },
{ "hidden", "estimaterawfee", &estimaterawfee, {"conf_target", "threshold"} },
};

View File

@ -211,7 +211,7 @@ class DescribeAddressVisitor : public boost::static_visitor<UniValue>
public:
CWallet * const pwallet;
DescribeAddressVisitor(CWallet *_pwallet) : pwallet(_pwallet) {}
explicit DescribeAddressVisitor(CWallet *_pwallet) : pwallet(_pwallet) {}
UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }
@ -623,7 +623,7 @@ UniValue signmessagewithprivkey(const JSONRPCRequest& request)
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
return EncodeBase64(vchSig.data(), vchSig.size());
}
UniValue setmocktime(const JSONRPCRequest& request)
@ -1307,7 +1307,7 @@ static const CRPCCommand commands[] =
/* Dash features */
{ "dash", "mnsync", &mnsync, {} },
{ "dash", "spork", &spork, {"value"} },
{ "dash", "spork", &spork, {"arg0","value"} },
/* Not shown in help */
{ "hidden", "setmocktime", &setmocktime, {"timestamp"}},

View File

@ -28,7 +28,7 @@ namespace RPCServer
/** Wrapper for UniValue::VType, which includes typeAny:
* Used to denote don't care type. Only used by RPCTypeCheckObj */
struct UniValueType {
UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
explicit UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {}
UniValueType() : typeAny(true) {}
bool typeAny;
UniValue::VType type;

View File

@ -174,7 +174,7 @@ void SingleThreadedSchedulerClient::ProcessQueue() {
// to ensure both happen safely even if callback() throws.
struct RAIICallbacksRunning {
SingleThreadedSchedulerClient* instance;
RAIICallbacksRunning(SingleThreadedSchedulerClient* _instance) : instance(_instance) {}
explicit RAIICallbacksRunning(SingleThreadedSchedulerClient* _instance) : instance(_instance) {}
~RAIICallbacksRunning() {
{
LOCK(instance->m_cs_callbacks_pending);

View File

@ -102,7 +102,7 @@ private:
void ProcessQueue();
public:
SingleThreadedSchedulerClient(CScheduler *pschedulerIn) : m_pscheduler(pschedulerIn) {}
explicit SingleThreadedSchedulerClient(CScheduler *pschedulerIn) : m_pscheduler(pschedulerIn) {}
void AddToProcessQueue(std::function<void (void)> func);
// Processes all remaining queue members on the calling thread, blocking until queue is empty

View File

@ -98,7 +98,7 @@ struct PrecomputedTransactionData
{
uint256 hashPrevouts, hashSequence, hashOutputs;
PrecomputedTransactionData(const CTransaction& tx);
explicit PrecomputedTransactionData(const CTransaction& tx);
};
enum SigVersion

View File

@ -21,7 +21,7 @@ protected:
const CKeyStore* keystore;
public:
BaseSignatureCreator(const CKeyStore* keystoreIn) : keystore(keystoreIn) {}
explicit BaseSignatureCreator(const CKeyStore* keystoreIn) : keystore(keystoreIn) {}
const CKeyStore& KeyStore() const { return *keystore; };
virtual ~BaseSignatureCreator() {}
virtual const BaseSignatureChecker& Checker() const =0;
@ -54,7 +54,7 @@ public:
/** A signature creator that just produces 72-byte empty signatures. */
class DummySignatureCreator : public BaseSignatureCreator {
public:
DummySignatureCreator(const CKeyStore* keystoreIn) : BaseSignatureCreator(keystoreIn) {}
explicit DummySignatureCreator(const CKeyStore* keystoreIn) : BaseSignatureCreator(keystoreIn) {}
const BaseSignatureChecker& Checker() const override;
bool CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override;
};

View File

@ -232,7 +232,7 @@ class CScriptVisitor : public boost::static_visitor<bool>
private:
CScript *script;
public:
CScriptVisitor(CScript *scriptin) { script = scriptin; }
explicit CScriptVisitor(CScript *scriptin) { script = scriptin; }
bool operator()(const CNoDestination &dest) const {
script->clear();

View File

@ -578,7 +578,7 @@ class CVarInt
protected:
I &n;
public:
CVarInt(I& nIn) : n(nIn) { }
explicit CVarInt(I& nIn) : n(nIn) { }
template<typename Stream>
void Serialize(Stream &s) const {
@ -596,7 +596,7 @@ class CCompactSize
protected:
uint64_t &n;
public:
CCompactSize(uint64_t& nIn) : n(nIn) { }
explicit CCompactSize(uint64_t& nIn) : n(nIn) { }
unsigned int GetSerializeSize() const {
return GetSizeOfCompactSize(n);
@ -619,7 +619,7 @@ class LimitedString
protected:
std::string& string;
public:
LimitedString(std::string& _string) : string(_string) {}
explicit LimitedString(std::string& _string) : string(_string) {}
template<typename Stream>
void Unserialize(Stream& s)

Some files were not shown because too many files have changed in this diff Show More