ci: various linter / CI compiler error fixes

Includes changing TRUE to OP_TRUE for anyone-can-spend output name,
to avoid symbol conflict on win64 builds, which is really obnoxious.
This commit is contained in:
Andrew Poelstra 2020-12-04 15:20:42 +00:00
parent 1e98c9fa9e
commit 68bfd70b43
41 changed files with 132 additions and 116 deletions

View file

@ -166,7 +166,7 @@ class AuthServiceProxy(object):
def _get_response(self):
try:
http_response = self.__conn.getresponse()
except socket.timeout as e:
except socket.timeout:
raise JSONRPCException({
'code': -344,
'message': '%r RPC took longer than %f seconds. Consider '

View file

@ -24,7 +24,6 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <deque>
#include <event2/thread.h>
#include <event2/buffer.h>

View file

@ -2093,7 +2093,7 @@ bool AppInitMain(const util::Ref& context, NodeContext& node, interfaces::BlockA
CScheduler::Function reevaluationLoop = [&node]{ node.reverification_scheduler->serviceQueue(); };
threadGroup.create_thread(std::bind(&TraceThread<CScheduler::Function>, "reevaluation_scheduler", reevaluationLoop));
CScheduler::Function f2 = boost::bind(&MainchainRPCCheck, false);
CScheduler::Function f2 = std::bind(&MainchainRPCCheck, false);
unsigned int check_rpc_every = gArgs.GetArg("-recheckpeginblockinterval", 120);
if (check_rpc_every) {
node.reverification_scheduler->scheduleEvery(f2, std::chrono::seconds(check_rpc_every));

View file

@ -456,7 +456,7 @@ std::vector<std::pair<CScript, CScript>> GetValidFedpegScripts(const CBlockIndex
std::vector<std::pair<CScript, CScript>> fedpegscripts;
const int32_t epoch_length = params.dynamic_epoch_length;
const int32_t epoch_length = (int32_t) params.dynamic_epoch_length;
const int32_t epoch_age = pblockindex->nHeight % epoch_length;
const int32_t epoch_start_height = pblockindex->nHeight - epoch_age;

View file

@ -38,7 +38,7 @@ public:
if (!(s.GetType() & SER_GETHASH))
s >> *(CScriptBase*)(&solution);
}
void SetNull()
{
challenge.clear();

View file

@ -8,7 +8,6 @@
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
#include <qt/qvaluecombobox.h>
#include <qt/guiutil.h>
#include <assetsdir.h>
#include <chainparams.h>

View file

@ -179,7 +179,7 @@ static bool SignStep(const SigningProvider& provider, const BaseSignatureCreator
sigdata.missing_witness_script = uint256(vSolutions[0]);
return false;
case TxoutType::TRUE:
case TxoutType::OP_TRUE:
return Params().anyonecanspend_aremine;
default:

View file

@ -69,7 +69,7 @@ std::string GetTxnOutputType(TxoutType t)
case TxoutType::WITNESS_V0_SCRIPTHASH: return "witness_v0_scripthash";
case TxoutType::WITNESS_V1_TAPROOT: return "witness_v1_taproot";
case TxoutType::WITNESS_UNKNOWN: return "witness_unknown";
case TxoutType::TRUE: return "true";
case TxoutType::OP_TRUE: return "true";
case TxoutType::FEE: return "fee";
}
assert(false);
@ -126,7 +126,7 @@ TxoutType Solver(const CScript& scriptPubKey, std::vector<std::vector<unsigned c
vSolutionsRet.clear();
if (Params().anyonecanspend_aremine && scriptPubKey == CScript() << OP_TRUE) {
return TxoutType::TRUE;
return TxoutType::OP_TRUE;
}
// Fee outputs are for elements-style transactions only

View file

@ -146,7 +146,7 @@ enum class TxoutType {
WITNESS_V0_KEYHASH,
WITNESS_V1_TAPROOT,
WITNESS_UNKNOWN, //!< Only for Witness versions not already defined above
TRUE, // For testing purposes only
OP_TRUE, // For testing purposes only
// ELEMENTS:
FEE,
};

View file

@ -274,8 +274,8 @@ BOOST_AUTO_TEST_CASE(naive_blinding_test)
BOOST_CHECK(secp256k1_rangeproof_info(ctx, &exp, &mantissa, &min_value, &max_value, tx4.witness.vtxoutwit[2].vchRangeproof.data(), proof_size) == 1);
BOOST_CHECK_EQUAL(exp, 0);
BOOST_CHECK_EQUAL(mantissa, 52); // 52 bit default
BOOST_CHECK_EQUAL(min_value, 1);
BOOST_CHECK_EQUAL(max_value, 4503599627370496);
BOOST_CHECK_EQUAL(min_value, 1ULL);
BOOST_CHECK_EQUAL(max_value, 4503599627370496ULL);
}
{
inputs.clear();

View file

@ -39,13 +39,13 @@ void test_one_input(const std::vector<uint8_t>& buffer)
const unsigned int batch_size = fuzzed_data_provider.ConsumeIntegralInRange<unsigned int>(0, 1024);
CCheckQueue<DumbCheck> check_queue_1{batch_size};
CCheckQueue<DumbCheck> check_queue_2{batch_size};
std::vector<DumbCheck> checks_1;
std::vector<DumbCheck> checks_2;
std::vector<DumbCheck*> checks_1;
std::vector<DumbCheck*> checks_2;
const int size = fuzzed_data_provider.ConsumeIntegralInRange<int>(0, 1024);
for (int i = 0; i < size; ++i) {
const bool result = fuzzed_data_provider.ConsumeBool();
checks_1.emplace_back(result);
checks_2.emplace_back(result);
checks_1.emplace_back(new DumbCheck(result));
checks_2.emplace_back(new DumbCheck(result));
}
if (fuzzed_data_provider.ConsumeBool()) {
check_queue_1.Add(checks_1);

View file

@ -132,7 +132,15 @@ void test_one_input(const std::vector<uint8_t>& buffer)
}
coins_cache_entry.coin = *opt_coin;
}
coins_map.emplace(random_out_point, std::move(coins_cache_entry));
// ELEMENTS
if (fuzzed_data_provider.ConsumeBool()) {
// non-pegin
coins_map.emplace(std::pair(uint256(), random_out_point), std::move(coins_cache_entry));
} else {
// pegin
const uint256 genhash(fuzzed_data_provider.ConsumeBytes<unsigned char>(sizeof(uint256)));
coins_map.emplace(std::pair(genhash, random_out_point), std::move(coins_cache_entry));
}
}
bool expected_code_path = false;
try {
@ -235,7 +243,7 @@ void test_one_input(const std::vector<uint8_t>& buffer)
}
case 2: {
TxValidationState state;
CAmount tx_fee_out;
CAmountMap tx_fee_map;
const CTransaction transaction{random_mutable_transaction};
if (ContainsSpentInput(transaction, coins_view_cache)) {
// Avoid:
@ -243,8 +251,10 @@ void test_one_input(const std::vector<uint8_t>& buffer)
break;
}
try {
(void)Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max()), tx_fee_out);
assert(MoneyRange(tx_fee_out));
std::vector<std::pair<CScript, CScript>> fedpegscripts; // ELEMENTS: we ought to populate this and have a more useful fuzztest
std::set<std::pair<uint256, COutPoint> > setPeginsSpent;
(void)Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max()), tx_fee_map, setPeginsSpent, NULL, false, true, fedpegscripts);
assert(MoneyRange(tx_fee_map));
} catch (const std::runtime_error&) {
}
break;

View file

@ -21,8 +21,8 @@ void test_one_input(const std::vector<uint8_t>& buffer)
const CTxIn tx_in{*out_point, script, fuzzed_data_provider.ConsumeIntegral<uint32_t>()};
(void)tx_in;
}
const CTxOut tx_out_1{ConsumeMoney(fuzzed_data_provider), script};
const CTxOut tx_out_2{ConsumeMoney(fuzzed_data_provider), ConsumeScript(fuzzed_data_provider)};
const CTxOut tx_out_1{CAsset(), ConsumeMoney(fuzzed_data_provider), script};
const CTxOut tx_out_2{CAsset(), ConsumeMoney(fuzzed_data_provider), ConsumeScript(fuzzed_data_provider)};
assert((tx_out_1 == tx_out_2) != (tx_out_1 != tx_out_2));
const std::optional<CMutableTransaction> mutable_tx_1 = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider);
const std::optional<CMutableTransaction> mutable_tx_2 = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider);

View file

@ -157,8 +157,9 @@ void Test(const std::string& str)
bool final = test.exists("final") && test["final"].get_bool();
if (test.exists("success")) {
tx.witness.vtxinwit.resize(tx.vin.size());
tx.vin[idx].scriptSig = ScriptFromHex(test["success"]["scriptSig"].get_str());
tx.vin[idx].scriptWitness = ScriptWitnessFromJSON(test["success"]["witness"]);
tx.witness.vtxinwit[idx].scriptWitness = ScriptWitnessFromJSON(test["success"]["witness"]);
PrecomputedTransactionData txdata;
txdata.Init(tx, std::vector<CTxOut>(prevouts));
MutableTransactionSignatureChecker txcheck(&tx, idx, prevouts[idx].nValue, txdata);
@ -166,21 +167,22 @@ void Test(const std::string& str)
// "final": true tests are valid for all flags. Others are only valid with flags that are
// a subset of test_flags.
if (final || ((flags & test_flags) == flags)) {
(void)VerifyScript(tx.vin[idx].scriptSig, prevouts[idx].scriptPubKey, &tx.vin[idx].scriptWitness, flags, txcheck, nullptr);
(void)VerifyScript(tx.vin[idx].scriptSig, prevouts[idx].scriptPubKey, &tx.witness.vtxinwit[idx].scriptWitness, flags, txcheck, nullptr);
}
}
}
if (test.exists("failure")) {
tx.witness.vtxinwit.resize(tx.vin.size());
tx.vin[idx].scriptSig = ScriptFromHex(test["failure"]["scriptSig"].get_str());
tx.vin[idx].scriptWitness = ScriptWitnessFromJSON(test["failure"]["witness"]);
tx.witness.vtxinwit[idx].scriptWitness = ScriptWitnessFromJSON(test["failure"]["witness"]);
PrecomputedTransactionData txdata;
txdata.Init(tx, std::vector<CTxOut>(prevouts));
MutableTransactionSignatureChecker txcheck(&tx, idx, prevouts[idx].nValue, txdata);
for (const auto flags : ALL_FLAGS) {
// If a test is supposed to fail with test_flags, it should also fail with any superset thereof.
if ((flags & test_flags) == test_flags) {
(void)VerifyScript(tx.vin[idx].scriptSig, prevouts[idx].scriptPubKey, &tx.vin[idx].scriptWitness, flags, txcheck, nullptr);
(void)VerifyScript(tx.vin[idx].scriptSig, prevouts[idx].scriptPubKey, &tx.witness.vtxinwit[idx].scriptWitness, flags, txcheck, nullptr);
}
}
}

View file

@ -17,7 +17,7 @@ void test_one_input(const std::vector<uint8_t>& buffer)
FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
const std::vector<uint8_t> random_bytes_1 = ConsumeRandomLengthByteVector(fuzzed_data_provider);
const std::vector<uint8_t> random_bytes_2 = ConsumeRandomLengthByteVector(fuzzed_data_provider);
const CAmount money = ConsumeMoney(fuzzed_data_provider);
const std::optional<CConfidentialValue> money = ConsumeDeserializable<CConfidentialValue>(fuzzed_data_provider);
bitcoinconsensus_error err;
bitcoinconsensus_error* err_p = fuzzed_data_provider.ConsumeBool() ? &err : nullptr;
const unsigned int n_in = fuzzed_data_provider.ConsumeIntegral<unsigned int>();
@ -27,5 +27,9 @@ void test_one_input(const std::vector<uint8_t>& buffer)
return;
}
(void)bitcoinconsensus_verify_script(random_bytes_1.data(), random_bytes_1.size(), random_bytes_2.data(), random_bytes_2.size(), n_in, flags, err_p);
(void)bitcoinconsensus_verify_script_with_amount(random_bytes_1.data(), random_bytes_1.size(), money, random_bytes_2.data(), random_bytes_2.size(), n_in, flags, err_p);
if (money) {
CDataStream data_stream(SER_NETWORK, PROTOCOL_VERSION);
data_stream << *money;
(void)bitcoinconsensus_verify_script_with_amount(random_bytes_1.data(), random_bytes_1.size(), (unsigned char*) data_stream.data(), data_stream.size(), random_bytes_2.data(), random_bytes_2.size(), n_in, flags, err_p);
}
}

View file

@ -91,8 +91,10 @@ void test_one_input(const std::vector<uint8_t>& buffer)
const unsigned int n_in = fuzzed_data_provider.ConsumeIntegral<unsigned int>();
if (mutable_transaction && tx_out && mutable_transaction->vin.size() > n_in) {
SignatureData signature_data_1 = DataFromTransaction(*mutable_transaction, n_in, *tx_out);
CTxIn input;
UpdateInput(input, signature_data_1);
CMutableTransaction mtx;
mtx.vin.resize(1);
mtx.witness.vtxinwit.resize(1);
UpdateTransaction(mtx, 0, signature_data_1);
const CScript script = ConsumeScript(fuzzed_data_provider);
SignatureData signature_data_2{script};
signature_data_1.MergeSignatureData(signature_data_2);

View file

@ -114,7 +114,7 @@ void test_one_input(const std::vector<uint8_t>& buffer)
} catch (const std::runtime_error&) {
}
(void)args_manager.GetHelpMessage();
(void)args_manager.GetUnrecognizedSections();
//(void)args_manager.GetUnrecognizedSections(); // ELEMENTS
(void)args_manager.GetUnsuitableSectionOnlyArgs();
(void)args_manager.IsArgNegated(s1);
(void)args_manager.IsArgSet(s1);

View file

@ -75,7 +75,7 @@ void test_one_input(const std::vector<uint8_t>& buffer)
(void)tx.GetHash();
(void)tx.GetTotalSize();
try {
(void)tx.GetValueOut();
(void)tx.GetValueOutMap();
} catch (const std::runtime_error&) {
}
(void)tx.GetWitnessHash();
@ -86,6 +86,8 @@ void test_one_input(const std::vector<uint8_t>& buffer)
(void)EncodeHexTx(tx);
(void)GetLegacySigOpCount(tx);
(void)GetTransactionInputWeight(tx, 0); // ELEMENTS: moved from tx_in.cpp
(void)GetVirtualTransactionInputSize(tx); // ELEMENTS: moved from tx_in.cpp
(void)GetTransactionWeight(tx);
(void)GetVirtualTransactionSize(tx);
(void)IsFinalTx(tx, /* nBlockHeight= */ 1024, /* nBlockTime= */ 1024);
@ -103,7 +105,7 @@ void test_one_input(const std::vector<uint8_t>& buffer)
// ValueFromAmount(i) not defined when i == std::numeric_limits<int64_t>::min()
bool skip_tx_to_univ = false;
for (const CTxOut& txout : tx.vout) {
if (txout.nValue == std::numeric_limits<int64_t>::min()) {
if (txout.nValue.GetAmount() == std::numeric_limits<int64_t>::min()) {
skip_tx_to_univ = true;
}
}

View file

@ -25,8 +25,6 @@ void test_one_input(const std::vector<uint8_t>& buffer)
return;
}
(void)GetTransactionInputWeight(tx_in);
(void)GetVirtualTransactionInputSize(tx_in);
(void)RecursiveDynamicUsage(tx_in);
(void)tx_in.ToString();

View file

@ -149,7 +149,8 @@ NODISCARD inline CTxMemPoolEntry ConsumeTxMemPoolEntry(FuzzedDataProvider& fuzze
const unsigned int entry_height = fuzzed_data_provider.ConsumeIntegral<unsigned int>();
const bool spends_coinbase = fuzzed_data_provider.ConsumeBool();
const unsigned int sig_op_cost = fuzzed_data_provider.ConsumeIntegralInRange<unsigned int>(0, MAX_BLOCK_SIGOPS_COST);
return CTxMemPoolEntry{MakeTransactionRef(tx), fee, time, entry_height, spends_coinbase, sig_op_cost, {}};
std::set<std::pair<uint256, COutPoint>> setPeginsSpent;
return CTxMemPoolEntry{MakeTransactionRef(tx), fee, time, entry_height, spends_coinbase, sig_op_cost, {}, setPeginsSpent};
}
NODISCARD inline CTxDestination ConsumeTxDestination(FuzzedDataProvider& fuzzed_data_provider) noexcept

View file

@ -116,9 +116,9 @@ BOOST_AUTO_TEST_CASE(PeginSpent_validity)
coinsCache.SetPeginSpent(outpoint4, true);
// Check the final state of coinsCache.mapCoins is sane.
BOOST_CHECK_EQUAL(coins.mapCoinsWritten.size(), 0);
BOOST_CHECK_EQUAL(coins.mapCoinsWritten.size(), 0U);
coinsCache.Flush();
BOOST_CHECK_EQUAL(coins.mapCoinsWritten.size(), 4);
BOOST_CHECK_EQUAL(coins.mapCoinsWritten.size(), 4U);
BOOST_CHECK_EQUAL(coins.mapCoinsWritten[outpoint].flags, CCoinsCacheEntry::DIRTY | CCoinsCacheEntry::FRESH | CCoinsCacheEntry::PEGIN);
BOOST_CHECK_EQUAL(coins.mapCoinsWritten[outpoint].peginSpent, true);
BOOST_CHECK_EQUAL(coins.mapCoinsWritten[outpoint2].flags, CCoinsCacheEntry::FRESH | CCoinsCacheEntry::PEGIN);
@ -133,7 +133,7 @@ BOOST_AUTO_TEST_CASE(PeginSpent_validity)
CCoinsViewCache coinsCache2(&coins2);
BOOST_CHECK(coinsCache2.BatchWrite(coins.mapCoinsWritten, uint256()));
coinsCache2.Flush();
BOOST_CHECK_EQUAL(coins2.mapCoinsWritten.size(), 3);
BOOST_CHECK_EQUAL(coins2.mapCoinsWritten.size(), 3U);
BOOST_CHECK_EQUAL(coins2.mapCoinsWritten[outpoint].flags, CCoinsCacheEntry::DIRTY | CCoinsCacheEntry::FRESH | CCoinsCacheEntry::PEGIN);
BOOST_CHECK_EQUAL(coins2.mapCoinsWritten[outpoint].peginSpent, true);
BOOST_CHECK_EQUAL(coins2.mapCoinsWritten[outpoint3].flags, CCoinsCacheEntry::DIRTY | CCoinsCacheEntry::FRESH | CCoinsCacheEntry::PEGIN);

View file

@ -34,8 +34,6 @@
#include <utility>
#include <vector>
#include <atomic>
#include <primitives/pak.h> // CPAKList
class CChainState;

View file

@ -4746,7 +4746,7 @@ static RPCHelpMan walletsignpsbt()
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::STR, "psbt", "the base64-encoded partially signed transaction"},
{RPCResult::Type::BOOL, "complete", "whether the transaction has a complete set of signatures"},
{RPCResult::Type::BOOL, "complete", "whether the transaction has a complete set of signatures"},
},
},
RPCExamples{
@ -4822,7 +4822,7 @@ static RPCHelpMan walletprocesspsbt()
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::STR, "psbt", "the base64-encoded partially signed transaction"},
{RPCResult::Type::BOOL, "complete", "whether the transaction has a complete set of signatures"},
{RPCResult::Type::BOOL, "complete", "whether the transaction has a complete set of signatures"},
},
},
RPCExamples{
@ -5235,7 +5235,7 @@ static RPCHelpMan getpeginaddress()
RPCResult::Type::OBJ, "", "",
{
{RPCResult::Type::STR, "mainchain_address", "mainchain deposit address to send bitcoin to"},
{RPCResult::Type::STR_HEX, "claim_script", "claim script committed to by the mainchain address. This may be required in `claimpegin` to retrieve pegged-in funds\n"},
{RPCResult::Type::STR_HEX, "claim_script", "claim script committed to by the mainchain address. This may be required in `claimpegin` to retrieve pegged-in funds\n"},
},
},
RPCExamples{

View file

@ -193,7 +193,7 @@ IsMineResult IsMineInner(const LegacyScriptPubKeyMan& keystore, const CScript& s
}
break;
}
case TxoutType::TRUE:
case TxoutType::OP_TRUE:
if (Params().anyonecanspend_aremine) {
return IsMineResult::SPENDABLE;
}

View file

@ -2591,7 +2591,7 @@ bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAm
mapValueFromPresetInputs[coin.asset] += coin.value;
if (coin.m_input_bytes <= 0) {
// ELEMENTS: if we're here we can't compute the coin's effective value. At
// this point in the rebase this is only used for BnB, and our functional
// this point in the rebase this is only used for BnB, and our functional
// tests expect the user to get a "missing data" error rather than an
// "insufficient funds" error, which means we need some way to make
// SelectCoins pass. So rather than "return false;" as in upstream we
@ -5279,7 +5279,7 @@ const CKeyingMaterial& CWallet::GetEncryptionKey() const
{
return vMasterKey;
}
bool CWallet::HasEncryptionKeys() const
{
return !mapMasterKeys.empty();

View file

@ -34,21 +34,21 @@ from test_framework import script as sc
from test_framework.blocktools import create_tx_with_script, MAX_BLOCK_SIGOPS
from test_framework.script import (
CScript,
OP_CAT,
OP_SUBSTR,
OP_LEFT,
OP_RIGHT,
OP_INVERT,
OP_AND,
OP_OR,
OP_XOR,
# OP_CAT,
# OP_SUBSTR,
# OP_LEFT,
# OP_RIGHT,
# OP_INVERT,
# OP_AND,
# OP_OR,
# OP_XOR,
OP_2MUL,
OP_2DIV,
OP_MUL,
OP_DIV,
OP_MOD,
OP_LSHIFT,
OP_RSHIFT
# OP_LSHIFT,
# OP_RSHIFT
)
basic_p2sh = sc.CScript([sc.OP_HASH160, sc.hash160(sc.CScript([sc.OP_0])), sc.OP_EQUAL])

View file

@ -1,8 +1,6 @@
#!/usr/bin/env python3
import codecs
import hashlib
import random
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (assert_raises_rpc_error, assert_equal)

View file

@ -406,8 +406,8 @@ class IssuanceTest(BitcoinTestFramework):
utxo_info = utxo
assert_equal(blinded_multisig, self.nodes[0].getaddressinfo(utxo_info["address"])["confidential"])
break
assert utxo_info is not None
assert utxo_info["amountblinder"] != "0000000000000000000000000000000000000000000000000000000000000000"
assert utxo_info is not None
assert utxo_info["amountblinder"] != "0000000000000000000000000000000000000000000000000000000000000000"
# Now make transaction spending that input
raw_tx = self.nodes[0].createrawtransaction([], {issued_address:1}, 0, False, {issued_address:issued_asset["token"]})

View file

@ -101,11 +101,11 @@ class SegWitTest(BitcoinTestFramework):
self.log.info("Verify sigops are counted in GBT with pre-BIP141 rules before the fork")
txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1)
tmpl = self.nodes[0].getblocktemplate({'rules': ['segwit']})
assert tmpl['sizelimit'] == 1000000
assert 'weightlimit' not in tmpl
assert tmpl['sigoplimit'] == 20000
assert tmpl['transactions'][0]['txid'] == txid
assert tmpl['transactions'][0]['sigops'] == 2
assert tmpl['sizelimit'] == 1000000
assert 'weightlimit' not in tmpl
assert tmpl['sigoplimit'] == 20000
assert tmpl['transactions'][0]['txid'] == txid
assert tmpl['transactions'][0]['sigops'] == 2
assert '!segwit' not in tmpl['rules']
self.nodes[0].generate(1) # block 162

View file

@ -6,7 +6,6 @@
from decimal import Decimal
from io import BytesIO
from decimal import Decimal
import math
from test_framework.test_framework import BitcoinTestFramework

View file

@ -585,7 +585,7 @@ class SegWitTest(BitcoinTestFramework):
else:
# For segwit-aware nodes, check the version bit and the witness
# commitment are correct.
assert 'default_witness_commitment' in gbt_results
assert 'default_witness_commitment' in gbt_results
# ELEMENTS: disabled
#witness_commitment = gbt_results['default_witness_commitment']
@ -969,7 +969,7 @@ class SegWitTest(BitcoinTestFramework):
for _ in range(NUM_OUTPUTS):
parent_tx.vout.append(CTxOut(child_value, script_pubkey))
parent_tx.vout[0].nValue.setToAmount(parent_tx.vout[0].nValue.getAmount() - 50000)
assert parent_tx.vout[0].nValue.getAmount() > 0
assert parent_tx.vout[0].nValue.getAmount() > 0
fee = value - (NUM_OUTPUTS*child_value) + 50000
if fee > 0:
parent_tx.vout.append(CTxOut(fee))
@ -1239,7 +1239,7 @@ class SegWitTest(BitcoinTestFramework):
for _ in range(10):
tx.vout.append(CTxOut(int(value / 10), script_pubkey))
tx.vout[0].nValue.setToAmount(tx.vout[0].nValue.getAmount() - 1000)
assert tx.vout[0].nValue.getAmount() >= 0
assert tx.vout[0].nValue.getAmount() >= 0
tx.vout.append(CTxOut(1000 + value - 10 * int(value / 10))) # fee
block = self.build_next_block()

View file

@ -25,8 +25,6 @@ from test_framework.blocktools import (
TIME_GENESIS_BLOCK,
)
from test_framework.messages import (
CBlockHeader,
FromHex,
msg_block,
)
from test_framework.p2p import P2PInterface

View file

@ -395,7 +395,7 @@ class RawTransactionsTest(BitcoinTestFramework):
# Compare fee.
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert feeDelta <= self.fee_tolerance
assert feeDelta <= self.fee_tolerance
def test_fee_p2pkh_multi_out(self):
"""Compare fee of a standard pubkeyhash transaction with multiple outputs."""
@ -418,7 +418,7 @@ class RawTransactionsTest(BitcoinTestFramework):
# Compare fee.
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert feeDelta <= self.fee_tolerance
assert feeDelta <= self.fee_tolerance
def test_fee_p2sh(self):
"""Compare fee of a 2-of-2 multisig p2sh transaction."""
@ -442,7 +442,7 @@ class RawTransactionsTest(BitcoinTestFramework):
# Compare fee.
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert feeDelta <= self.fee_tolerance
assert feeDelta <= self.fee_tolerance
def test_fee_4of5(self):
"""Compare fee of a standard pubkeyhash transaction."""
@ -483,7 +483,7 @@ class RawTransactionsTest(BitcoinTestFramework):
# Compare fee.
feeDelta = Decimal(fundedTx['fee']) - Decimal(signedFee)
assert feeDelta <= self.fee_tolerance
assert feeDelta <= self.fee_tolerance
def test_spend_2of2(self):
"""Spend a 2-of-2 multisig transaction over fundraw."""
@ -611,7 +611,6 @@ class RawTransactionsTest(BitcoinTestFramework):
outputs = {self.nodes[0].getnewaddress():0.15,self.nodes[0].getnewaddress():0.04}
rawtx = self.nodes[1].createrawtransaction(inputs, outputs)
fundedTx = self.nodes[1].fundrawtransaction(rawtx)
blindedTx = self.nodes[1].blindrawtransaction(fundedTx['hex'])
# Create same transaction over sendtoaddress.
txId = self.nodes[1].sendmany("", outputs)

View file

@ -7,7 +7,7 @@
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_approx,
# assert_approx,
assert_equal,
assert_greater_than,
assert_raises_rpc_error,
@ -246,14 +246,18 @@ class PSBTTest(BitcoinTestFramework):
fee_rate_sb = 10000
self.log.info("Test walletcreatefundedpsbt fee rate of 10000 sat/vB and 0.1 BTC/kvB produces a total fee at or slightly below -maxtxfee (~0.05290000)")
res1 = self.nodes[1].walletcreatefundedpsbt(inputs, outputs, 0, {"fee_rate": fee_rate_sb, "add_inputs": True})
#res1 =
self.nodes[1].walletcreatefundedpsbt(inputs, outputs, 0, {"fee_rate": fee_rate_sb, "add_inputs": True})
#assert_approx(res1["fee"], 0.055, 0.005) # ELEMENTS: no "fee" field
res2 = self.nodes[1].walletcreatefundedpsbt(inputs, outputs, 0, {"feeRate": fee_rate_sb / 100000.0, "add_inputs": True})
#res2 =
self.nodes[1].walletcreatefundedpsbt(inputs, outputs, 0, {"feeRate": fee_rate_sb / 100000.0, "add_inputs": True})
#assert_approx(res2["fee"], 0.055, 0.005) # ELEMENTS: no "fee" field
self.log.info("Test min fee rate checks with walletcreatefundedpsbt are bypassed, e.g. a fee_rate under 1 sat/vB is allowed")
res3 = self.nodes[1].walletcreatefundedpsbt(inputs, outputs, 0, {"fee_rate": 0.99999999, "add_inputs": True})
#res3 =
self.nodes[1].walletcreatefundedpsbt(inputs, outputs, 0, {"fee_rate": 0.99999999, "add_inputs": True})
#assert_approx(res3["fee"], 0.00000381, 0.0000001) # ELEMENTS: no "fee" field
res4 = self.nodes[1].walletcreatefundedpsbt(inputs, outputs, 0, {"feeRate": 0.00000999, "add_inputs": True})
#res4 =
self.nodes[1].walletcreatefundedpsbt(inputs, outputs, 0, {"feeRate": 0.00000999, "add_inputs": True})
#assert_approx(res4["fee"], 0.00000381, 0.0000001) # ELEMENTS: no "fee" field
self.log.info("Test invalid fee rate settings")

View file

@ -253,55 +253,55 @@ class RawTransactionsTest(BitcoinTestFramework):
# 2of2 test
addr1 = self.nodes[2].getnewaddress()
addr2 = self.nodes[2].getnewaddress()
addr1Obj = self.nodes[2].getaddressinfo(addr1)
addr2Obj = self.nodes[2].getaddressinfo(addr2)
# Tests for createmultisig and addmultisigaddress
assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 1, ["01020304"])
self.nodes[0].createmultisig(2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) # createmultisig can only take public keys
assert_raises_rpc_error(-5, "Invalid public key", self.nodes[0].createmultisig, 2, [addr1Obj['pubkey'], addr1]) # addmultisigaddress can take both pubkeys and addresses so long as they are in the wallet, which is tested here.
mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr1])['address']
#use balance deltas instead of absolute values
bal = self.nodes[2].getbalance()['bitcoin']
# send 1.2 BTC to msig adr
txId = self.nodes[0].sendtoaddress(mSigObj, 1.2)
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
assert_equal(self.nodes[2].getbalance()['bitcoin'], bal+Decimal('1.20000000')) #node2 has both keys of the 2of2 ms addr., tx should affect the balance
# 2of3 test from different nodes
bal = self.nodes[2].getbalance()['bitcoin']
addr1 = self.nodes[1].getnewaddress()
addr2 = self.nodes[2].getnewaddress()
addr3 = self.nodes[2].getnewaddress()
addr1Obj = self.nodes[1].getaddressinfo(addr1)
addr2Obj = self.nodes[2].getaddressinfo(addr2)
addr3Obj = self.nodes[2].getaddressinfo(addr3)
mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey']])['address']
txId = self.nodes[0].sendtoaddress(mSigObj, 2.2)
decTx = self.nodes[0].gettransaction(txId)
rawTx = self.nodes[0].decoderawtransaction(decTx['hex'])
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
#THIS IS AN INCOMPLETE FEATURE
#NODE2 HAS TWO OF THREE KEY AND THE FUNDS SHOULD BE SPENDABLE AND COUNT AT BALANCE CALCULATION
assert_equal(self.nodes[2].getbalance()['bitcoin'], bal) #for now, assume the funds of a 2of3 multisig tx are not marked as spendable
txDetails = self.nodes[0].gettransaction(txId, True)
rawTx = self.nodes[0].decoderawtransaction(txDetails['hex'])
vout = next(o for o in rawTx['vout'] if o['value'] == Decimal('2.20000000'))
bal = self.nodes[0].getbalance()['bitcoin']
inputs = [{ "txid" : txId, "vout" : vout['n'], "scriptPubKey" : vout['scriptPubKey']['hex'], "amount" : vout['value']}]
outputs = { self.nodes[0].getnewaddress() : 2.19 }
@ -309,7 +309,7 @@ class RawTransactionsTest(BitcoinTestFramework):
rawTx = self.nodes[2].createrawtransaction(inputs, outputs)
rawTxPartialSigned = self.nodes[1].signrawtransactionwithwallet(rawTx, inputs)
assert_equal(rawTxPartialSigned['complete'], False) #node1 only has one key, can't comp. sign the tx
rawTxSigned = self.nodes[2].signrawtransactionwithwallet(rawTx, inputs)
assert_equal(rawTxSigned['complete'], True) #node2 can sign the tx compl., own two of three keys
self.nodes[2].sendrawtransaction(rawTxSigned['hex'])
@ -318,32 +318,32 @@ class RawTransactionsTest(BitcoinTestFramework):
self.nodes[0].generate(1)
self.sync_all()
assert_equal(self.nodes[0].getbalance()['bitcoin'], bal+Decimal('50.00000000')+Decimal('2.19000000')) #block reward + tx
# 2of2 test for combining transactions
bal = self.nodes[2].getbalance()['bitcoin']
addr1 = self.nodes[1].getnewaddress()
addr2 = self.nodes[2].getnewaddress()
addr1Obj = self.nodes[1].getaddressinfo(addr1)
addr2Obj = self.nodes[2].getaddressinfo(addr2)
self.nodes[1].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address']
mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address']
mSigObjValid = self.nodes[2].getaddressinfo(mSigObj)
txId = self.nodes[0].sendtoaddress(mSigObj, 2.2)
decTx = self.nodes[0].gettransaction(txId)
rawTx2 = self.nodes[0].decoderawtransaction(decTx['hex'])
self.sync_all()
self.nodes[0].generate(1)
self.sync_all()
assert_equal(self.nodes[2].getbalance()['bitcoin'], bal) # the funds of a 2of2 multisig tx should not be marked as spendable
txDetails = self.nodes[0].gettransaction(txId, True)
rawTx2 = self.nodes[0].decoderawtransaction(txDetails['hex'])
vout = next(o for o in rawTx2['vout'] if o['value'] == Decimal('2.20000000'))
bal = self.nodes[0].getbalance()['bitcoin']
inputs = [{ "txid" : txId, "vout" : vout['n'], "scriptPubKey" : vout['scriptPubKey']['hex'], "redeemScript" : mSigObjValid['hex'], "amount" : vout['value']}]
outputs = { self.nodes[0].getnewaddress() : 2.19 }
@ -352,7 +352,7 @@ class RawTransactionsTest(BitcoinTestFramework):
rawTxPartialSigned1 = self.nodes[1].signrawtransactionwithwallet(rawTx2, inputs)
self.log.debug(rawTxPartialSigned1)
assert_equal(rawTxPartialSigned1['complete'], False) #node1 only has one key, can't comp. sign the tx
rawTxPartialSigned2 = self.nodes[2].signrawtransactionwithwallet(rawTx2, inputs)
self.log.debug(rawTxPartialSigned2)
assert_equal(rawTxPartialSigned2['complete'], False) #node2 only has one key, can't comp. sign the tx

View file

@ -76,7 +76,7 @@ def base58_to_byte(s):
def keyhash_to_p2pkh(hash, main=False):
assert len(hash) == 20
assert len(hash) == 20
version = 235
return byte_to_base58(hash, version)

View file

@ -930,7 +930,9 @@ class DynaFedParamEntry:
# null = 0
# signblock-related fields = 1, required for m_current on non-epoch-starts
# all fields = 2, required for epoch starts
def __init__(self, m_signblockscript=b"", m_signblock_witness_limit=0, m_fedpeg_program=b"", m_fedpegscript=b"", m_extension_space=[], m_elided_root=0):
def __init__(self, m_signblockscript=b"", m_signblock_witness_limit=0, m_fedpeg_program=b"", m_fedpegscript=b"", m_extension_space=None, m_elided_root=0):
if m_extension_space is None:
m_extension_space = []
self.m_signblockscript = m_signblockscript
self.m_signblock_witness_limit = m_signblock_witness_limit
self.m_fedpeg_program = m_fedpeg_program

View file

@ -39,7 +39,7 @@ except UnicodeDecodeError:
CROSS = "x "
CIRCLE = "o "
if os.name != 'nt' or sys.getwindowsversion() >= (10, 0, 14393):
if os.name != 'nt' or sys.getwindowsversion() >= (10, 0, 14393): # type: ignore[attr-defined]
if os.name == 'nt':
import ctypes
kernel32 = ctypes.windll.kernel32 # type: ignore

View file

@ -22,9 +22,9 @@ class DisableWalletTest (BitcoinTestFramework):
# Make sure wallet is really disabled
assert_raises_rpc_error(-32601, 'Method not found', self.nodes[0].getwalletinfo)
x = self.nodes[0].validateaddress('3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy')
assert x['isvalid'] == False
assert x['isvalid'] == False
x = self.nodes[0].validateaddress('CTEsjYXANAynYYMzu5BUyvfNAVToxGh3s17kjZvELXuBG37qsfzz65vfhxEocbo55AnrvGbWBuMbJMCz')
assert x['isvalid'] == True
assert x['isvalid'] == True
# Checking mining to an address without a wallet. Generating to a valid address should succeed
# but generating to an invalid address will fail.

View file

@ -6,7 +6,6 @@
from decimal import Decimal
from test_framework import liquid_addr
from test_framework.address import key_to_p2wpkh
from test_framework.key import ECKey
from test_framework.test_framework import BitcoinTestFramework
from test_framework.script import hash160
@ -44,7 +43,7 @@ class ImportPrunedFundsTest(BitcoinTestFramework):
address3_privkey = bytes_to_wif(eckey.get_bytes())
address3_blindingkey = blinding_eckey.get_bytes().hex()
conf_addrdata = blinding_eckey.get_pubkey().get_bytes() + hash160(eckey.get_pubkey().get_bytes())
conf_addrdata = blinding_eckey.get_pubkey().get_bytes() + hash160(eckey.get_pubkey().get_bytes())
address3 = liquid_addr.encode("el", 0, conf_addrdata)
self.nodes[0].importprivkey(address3_privkey)

View file

@ -11,7 +11,7 @@ from test_framework.authproxy import JSONRPCException
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
assert_equal,
assert_fee_amount,
# assert_fee_amount,
assert_greater_than,
assert_raises_rpc_error,
)
@ -226,9 +226,11 @@ class WalletSendTest(BitcoinTestFramework):
self.log.info("Create transaction that spends to address, but don't broadcast...")
self.test_send(from_wallet=w0, to_wallet=w1, amount=1, add_to_wallet=False)
# conf_target & estimate_mode can be set as argument or option
res1 = self.test_send(from_wallet=w0, to_wallet=w1, amount=1, arg_conf_target=1, arg_estimate_mode="economical", add_to_wallet=False)
res2 = self.test_send(from_wallet=w0, to_wallet=w1, amount=1, conf_target=1, estimate_mode="economical", add_to_wallet=False)
# ELEMENTS: we do not have the "fee" field. After #900 we should uncomment all of this.
#res1 =
self.test_send(from_wallet=w0, to_wallet=w1, amount=1, arg_conf_target=1, arg_estimate_mode="economical", add_to_wallet=False)
#res2 =
self.test_send(from_wallet=w0, to_wallet=w1, amount=1, conf_target=1, estimate_mode="economical", add_to_wallet=False)
#assert_equal(self.nodes[1].decodepsbt(res1["psbt"])["fee"],
# self.nodes[1].decodepsbt(res2["psbt"])["fee"])
# but not at the same time
@ -259,8 +261,8 @@ class WalletSendTest(BitcoinTestFramework):
# ELEMENTS: we do not have the "fee" field, several lines are commented out here that should
# be revisited after #900
self.log.info("Test setting explicit fee rate")
res1 = self.test_send(from_wallet=w0, to_wallet=w1, amount=1, arg_fee_rate=1, add_to_wallet=False)
res2 = self.test_send(from_wallet=w0, to_wallet=w1, amount=1, fee_rate=1, add_to_wallet=False)
#res1 = self.test_send(from_wallet=w0, to_wallet=w1, amount=1, arg_fee_rate=1, add_to_wallet=False)
#res2 = self.test_send(from_wallet=w0, to_wallet=w1, amount=1, fee_rate=1, add_to_wallet=False)
#assert_equal(self.nodes[1].decodepsbt(res1["psbt"])["fee"], self.nodes[1].decodepsbt(res2["psbt"])["fee"])
# Passing conf_target 0, estimate_mode "" as placeholder arguments should allow fee_rate to apply.