Bitcoin ABC 0.33.10
P2P Digital Currency
proof.cpp
Go to the documentation of this file.
1// Copyright (c) 2020 The Bitcoin developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <avalanche/proof.h>
6
8#include <coins.h>
9#include <common/args.h>
10#include <hash.h>
11#include <policy/policy.h>
12#include <script/standard.h>
13#include <streams.h>
14#include <util/strencodings.h>
15#include <util/translation.h>
16#include <validation.h>
17
18#include <tinyformat.h>
19
20#include <limits>
21#include <numeric>
22#include <unordered_set>
23#include <variant>
24
25namespace avalanche {
26
27StakeCommitment::StakeCommitment(int64_t expirationTime,
28 const CPubKey &master) {
29 HashWriter ss{};
30 ss << expirationTime;
31 ss << master;
32 const uint256 &hash = ss.GetHash();
33 memcpy(m_data, hash.data(), sizeof(m_data));
34}
35
37 HashWriter ss{};
38 ss << *this;
39 stakeid = StakeId(ss.GetHash());
40}
41
42uint256 Stake::getHash(const StakeCommitment &commitment) const {
43 HashWriter ss{};
44 ss << commitment;
45 ss << *this;
46 return ss.GetHash();
47}
48
49bool SignedStake::verify(const StakeCommitment &commitment) const {
50 return stake.getPubkey().VerifySchnorr(stake.getHash(commitment), sig);
51}
52
53bool Proof::FromHex(Proof &proof, const std::string &hexProof,
54 bilingual_str &errorOut) {
55 if (!IsHex(hexProof)) {
56 errorOut = _("Proof must be an hexadecimal string.");
57 return false;
58 }
59
60 DataStream ss{ParseHex(hexProof)};
61
62 try {
63 ss >> proof;
64 } catch (std::exception &e) {
65 errorOut = strprintf(_("Proof has invalid format: %s"), e.what());
66 return false;
67 }
68
69 return true;
70}
71
72std::string Proof::ToHex() const {
73 DataStream ss{};
74 ss << *this;
75 return HexStr(ss);
76}
77
79 HashWriter ss{};
80 ss << sequence;
81 ss << expirationTime;
83
84 WriteCompactSize(ss, stakes.size());
85 for (const SignedStake &s : stakes) {
86 ss << s.getStake();
87 }
88
89 limitedProofId = LimitedProofId(ss.GetHash());
91}
92
95}
96
97uint32_t Proof::amountToScore(Amount amount) {
98 amount = MoneyClamp(amount);
99 // After clamping, (100 * amount) is guaranteed not to overflow int64_t,
100 // and the resulting score fits in uint32_t.
101 static_assert(MAX_MONEY <=
102 (std::numeric_limits<int64_t>::max() / 100) * SATOSHI);
103 static_assert((100 * MAX_MONEY) / COIN <=
104 std::numeric_limits<uint32_t>::max());
105 return (100 * amount) / COIN;
106}
107
109 // Each add is at most MAX_MONEY + MAX_MONEY, which fits in int64_t.
110 static_assert(MAX_MONEY <=
111 (std::numeric_limits<int64_t>::max() / 2) * SATOSHI);
112 return std::accumulate(
113 stakes.begin(), stakes.end(), Amount::zero(),
114 [](Amount total, const SignedStake &ss) {
115 return MoneyClamp(total + MoneyClamp(ss.getStake().getAmount()));
116 });
117}
118
119static bool IsStandardPayoutScript(const CScript &scriptPubKey) {
120 // Check the script's standardness against the default max OP_RETURN size,
121 // so that a proof's validity is not affected by a local relay policy
122 // parameter (see -datacarriersize config option)
123 TxoutType scriptType;
124 return IsStandard(scriptPubKey, MAX_OP_RETURN_RELAY, scriptType);
125}
126
127bool Proof::verify(const Amount &stakeUtxoDustThreshold,
128 ProofValidationState &state) const {
129 if (stakes.empty()) {
130 return state.Invalid(ProofValidationResult::NO_STAKE, "no-stake");
131 }
132
133 if (stakes.size() > AVALANCHE_MAX_PROOF_STAKES) {
134 return state.Invalid(
136 strprintf("%u > %u", stakes.size(), AVALANCHE_MAX_PROOF_STAKES));
137 }
138
141 "payout-script-non-standard");
142 }
143
146 "invalid-proof-signature");
147 }
148
149 StakeId prevId = uint256::ZERO;
150 std::unordered_set<COutPoint, SaltedOutpointHasher> utxos;
151 for (const SignedStake &ss : stakes) {
152 const Stake &s = ss.getStake();
153 if (s.getAmount() < stakeUtxoDustThreshold) {
155 "amount-below-dust-threshold",
156 strprintf("%s < %s", s.getAmount().ToString(),
157 stakeUtxoDustThreshold.ToString()));
158 }
159
160 if (s.getId() < prevId) {
162 "wrong-stake-ordering");
163 }
164 prevId = s.getId();
165
166 if (!utxos.insert(s.getUTXO()).second) {
168 "duplicated-stake");
169 }
170
171 if (!ss.verify(getStakeCommitment())) {
172 return state.Invalid(
174 "invalid-stake-signature",
175 strprintf("TxId: %s", s.getUTXO().GetTxId().ToString()));
176 }
177 }
178
179 return true;
180}
181
182bool Proof::verify(const Amount &stakeUtxoDustThreshold,
183 const ChainstateManager &chainman,
184 ProofValidationState &state) const {
186 if (!verify(stakeUtxoDustThreshold, state)) {
187 // state is set by verify.
188 return false;
189 }
190
191 const CBlockIndex *activeTip = chainman.ActiveTip();
192 const int64_t tipMedianTimePast =
193 activeTip ? activeTip->GetMedianTimePast() : 0;
194 if (expirationTime > 0 && tipMedianTimePast >= expirationTime) {
195 return state.Invalid(ProofValidationResult::EXPIRED, "expired-proof");
196 }
197
198 const int64_t activeHeight = chainman.ActiveHeight();
199 const int64_t stakeUtxoMinConfirmations =
200 gArgs.GetIntArg("-avaproofstakeutxoconfirmations",
202
203 for (const SignedStake &ss : stakes) {
204 const Stake &s = ss.getStake();
205 const COutPoint &utxo = s.getUTXO();
206
207 auto coin{chainman.ActiveChainstate().CoinsTip().GetCoin(utxo)};
208 if (!coin) {
209 // The coins are not in the UTXO set.
211 "utxo-missing-or-spent");
212 }
213
214 if ((s.getHeight() + stakeUtxoMinConfirmations - 1) > activeHeight) {
215 return state.Invalid(
217 strprintf("TxId: %s, block height: %d, chaintip height: %d",
218 s.getUTXO().GetTxId().ToString(), s.getHeight(),
219 activeHeight));
220 }
221
222 if (s.isCoinbase() != coin->IsCoinBase()) {
223 return state.Invalid(
224 ProofValidationResult::COINBASE_MISMATCH, "coinbase-mismatch",
225 strprintf("expected %s, found %s",
226 s.isCoinbase() ? "true" : "false",
227 coin->IsCoinBase() ? "true" : "false"));
228 }
229
230 if (s.getHeight() != coin->GetHeight()) {
232 "height-mismatch",
233 strprintf("expected %u, found %u",
234 s.getHeight(), coin->GetHeight()));
235 }
236
237 const CTxOut &out = coin->GetTxOut();
238 if (s.getAmount() != out.nValue) {
239 // Wrong amount.
240 return state.Invalid(
242 strprintf("expected %s, found %s", s.getAmount().ToString(),
243 out.nValue.ToString()));
244 }
245
246 CTxDestination dest;
247 if (!ExtractDestination(out.scriptPubKey, dest)) {
248 // Can't extract destination.
249 return state.Invalid(
251 "non-standard-destination");
252 }
253
254 PKHash *pkhash = std::get_if<PKHash>(&dest);
255 if (!pkhash) {
256 // Only PKHash are supported.
257 return state.Invalid(
259 "destination-type-not-supported");
260 }
261
262 const CPubKey &pubkey = s.getPubkey();
263 if (*pkhash != PKHash(pubkey)) {
264 // Wrong pubkey.
266 "destination-mismatch");
267 }
268 }
269
270 return true;
271}
272
273} // namespace avalanche
static constexpr Amount SATOSHI
Definition: amount.h:149
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:171
Amount MoneyClamp(const Amount nValue)
Definition: amount.h:176
static constexpr Amount COIN
Definition: amount.h:150
ArgsManager gArgs
Definition: args.cpp:39
int64_t GetIntArg(const std::string &strArg, int64_t nDefault) const
Return integer argument or default value.
Definition: args.cpp:494
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
int64_t GetMedianTimePast() const
Definition: blockindex.h:172
An encapsulated public key.
Definition: pubkey.h:31
bool VerifySchnorr(const uint256 &hash, const std::array< uint8_t, SCHNORR_SIZE > &sig) const
Verify a Schnorr signature (=64 bytes).
Definition: pubkey.cpp:206
An output of a transaction.
Definition: transaction.h:128
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1170
SnapshotCompletionResult MaybeCompleteSnapshotValidation() EXCLUSIVE_LOCKS_REQUIRED(const CBlockIndex *GetSnapshotBaseBlock() const EXCLUSIVE_LOCKS_REQUIRED(Chainstate ActiveChainstate)() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
Definition: validation.h:1424
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1431
int ActiveHeight() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1428
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:118
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:99
bool Invalid(Result result, const std::string &reject_reason="", const std::string &debug_message="")
Definition: validation.h:101
static bool FromHex(Proof &proof, const std::string &hexProof, bilingual_str &errorOut)
Definition: proof.cpp:53
bool verify(const Amount &stakeUtxoDustThreshold, ProofValidationState &state) const
Definition: proof.cpp:127
int64_t expirationTime
Definition: proof.h:102
void computeProofId()
Definition: proof.cpp:78
Amount getStakedAmount() const
Definition: proof.cpp:108
CScript payoutScriptPubKey
Definition: proof.h:105
std::string ToHex() const
Definition: proof.cpp:72
const StakeCommitment getStakeCommitment() const
Definition: proof.h:169
void computeScore()
Definition: proof.cpp:93
LimitedProofId limitedProofId
Definition: proof.h:108
uint64_t sequence
Definition: proof.h:101
uint32_t score
Definition: proof.h:112
std::vector< SignedStake > stakes
Definition: proof.h:104
CPubKey master
Definition: proof.h:103
ProofId proofid
Definition: proof.h:109
SchnorrSig signature
Definition: proof.h:106
static uint32_t amountToScore(Amount amount)
Definition: proof.cpp:97
SchnorrSig sig
Definition: proof.h:85
bool verify(const StakeCommitment &commitment) const
Definition: proof.cpp:49
uint256 getHash(const StakeCommitment &commitment) const
Definition: proof.cpp:42
Amount getAmount() const
Definition: proof.h:73
bool isCoinbase() const
Definition: proof.h:75
uint32_t getHeight() const
Definition: proof.h:74
StakeId stakeid
Definition: proof.h:55
void computeStakeId()
Definition: proof.cpp:36
const CPubKey & getPubkey() const
Definition: proof.h:76
const COutPoint & getUTXO() const
Definition: proof.h:72
const StakeId & getId() const
Definition: proof.h:80
uint8_t m_data[WIDTH]
Definition: uint256.h:21
const uint8_t * data() const
Definition: uint256.h:82
256-bit opaque blob.
Definition: uint256.h:129
static const uint256 ZERO
Definition: uint256.h:134
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
uint256 StakeId
Definition: proof.h:42
static bool IsStandardPayoutScript(const CScript &scriptPubKey)
Definition: proof.cpp:119
bool IsStandard(const CScript &scriptPubKey, const std::optional< unsigned > &max_datacarrier_bytes, TxoutType &whichType)
Definition: policy.cpp:38
static constexpr int AVALANCHE_DEFAULT_STAKE_UTXO_CONFIRMATIONS
Minimum number of confirmations before a stake utxo is mature enough to be included into a proof.
Definition: proof.h:33
static constexpr int AVALANCHE_MAX_PROOF_STAKES
How many UTXOs can be used for a single proof.
Definition: proof.h:27
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition: serialize.h:1258
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:158
static const unsigned int MAX_OP_RETURN_RELAY
Default setting for nMaxDatacarrierBytes.
Definition: standard.h:36
TxoutType
Definition: standard.h:38
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:85
Definition: amount.h:22
static constexpr Amount zero() noexcept
Definition: amount.h:35
std::string ToString() const
Definition: amount.cpp:22
ProofId computeProofId(const CPubKey &proofMaster) const
Definition: proofid.cpp:12
StakeCommitment(int64_t expirationTime, const CPubKey &master)
Definition: proof.cpp:27
Bilingual messages:
Definition: translation.h:17
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
template std::vector< std::byte > ParseHex(std::string_view)
bool IsHex(std::string_view str)
Returns true if each character in str is a hex character, and has an even number of hex digits.
AssertLockHeld(pool.cs)