Bitcoin ABC 0.32.8
P2P Digital Currency
avalanche.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
10#include <avalanche/proof.h>
14#include <common/args.h>
15#include <config.h>
16#include <core_io.h>
17#include <index/txindex.h>
18#include <key_io.h>
19#include <net_processing.h>
20#include <node/context.h>
22#include <rpc/blockchain.h>
24#include <rpc/server.h>
25#include <rpc/server_util.h>
26#include <rpc/util.h>
27#include <util/strencodings.h>
28#include <util/translation.h>
29
30#include <univalue.h>
31
34
36 return RPCHelpMan{
37 "getavalanchekey",
38 "Returns the key used to sign avalanche messages.\n",
39 {},
41 RPCExamples{HelpExampleRpc("getavalanchekey", "")},
42 [&](const RPCHelpMan &self, const Config &config,
43 const JSONRPCRequest &request) -> UniValue {
44 NodeContext &node = EnsureAnyNodeContext(request.context);
46 return HexStr(avalanche.getSessionPubKey());
47 },
48 };
49}
50
51static CPubKey ParsePubKey(const UniValue &param) {
52 const std::string &keyHex = param.get_str();
53 if ((keyHex.length() != 2 * CPubKey::COMPRESSED_SIZE &&
54 keyHex.length() != 2 * CPubKey::SIZE) ||
55 !IsHex(keyHex)) {
57 strprintf("Invalid public key: %s\n", keyHex));
58 }
59
60 return HexToPubKey(keyHex);
61}
62
66 auto localProof = avalanche.getLocalProof();
67 if (localProof && localProof->getId() == proof->getId()) {
68 return true;
69 }
70
71 return avalanche.withPeerManager([&](avalanche::PeerManager &pm) {
72 return pm.getProof(proof->getId()) || pm.registerProof(proof, state);
73 });
74}
75
77 avalanche::ProofRef proof) {
79 return registerProofIfNeeded(avalanche, std::move(proof), state);
80}
81
83 const std::string &dgHex, CPubKey &auth) {
84 bilingual_str error;
85 if (!avalanche::Delegation::FromHex(dg, dgHex, error)) {
87 }
88
90 if (!dg.verify(state, auth)) {
92 "The delegation is invalid: " + state.ToString());
93 }
94}
95
97 const std::string &proofHex) {
98 bilingual_str error;
99 if (!avalanche::Proof::FromHex(proof, proofHex, error)) {
101 }
102
103 Amount stakeUtxoDustThreshold = avalanche::PROOF_DUST_THRESHOLD;
104 if (node.avalanche) {
105 // If Avalanche is enabled, use the configured dust threshold
106 node.avalanche->withPeerManager([&](avalanche::PeerManager &pm) {
107 stakeUtxoDustThreshold = pm.getStakeUtxoDustThreshold();
108 });
109 }
110
112 {
113 LOCK(cs_main);
114 if (!proof.verify(stakeUtxoDustThreshold, *Assert(node.chainman),
115 state)) {
117 "The proof is invalid: " + state.ToString());
118 }
119 }
120}
121
123 return RPCHelpMan{
124 "addavalanchenode",
125 "Add a node in the set of peers to poll for avalanche.\n",
126 {
128 "Node to be added to avalanche."},
130 "The public key of the node."},
132 "Proof that the node is not a sybil."},
134 "The proof delegation the the node public key"},
135 },
137 "Whether the addition succeeded or not."},
139 HelpExampleRpc("addavalanchenode", "5, \"<pubkey>\", \"<proof>\"")},
140 [&](const RPCHelpMan &self, const Config &config,
141 const JSONRPCRequest &request) -> UniValue {
142 const NodeId nodeid = request.params[0].getInt<int64_t>();
143 CPubKey key = ParsePubKey(request.params[1]);
144
145 auto proof = RCUPtr<avalanche::Proof>::make();
146 NodeContext &node = EnsureAnyNodeContext(request.context);
148
149 verifyProofOrThrow(node, *proof, request.params[2].get_str());
150
151 const avalanche::ProofId &proofid = proof->getId();
152 if (key != proof->getMaster()) {
153 if (request.params.size() < 4 || request.params[3].isNull()) {
154 throw JSONRPCError(
156 "The public key does not match the proof");
157 }
158
160 CPubKey auth;
161 verifyDelegationOrThrow(dg, request.params[3].get_str(), auth);
162
163 if (dg.getProofId() != proofid) {
164 throw JSONRPCError(
166 "The delegation does not match the proof");
167 }
168
169 if (key != auth) {
170 throw JSONRPCError(
172 "The public key does not match the delegation");
173 }
174 }
175
176 if (!registerProofIfNeeded(avalanche, proof)) {
178 "The proof has conflicting utxos");
179 }
180
181 if (!node.connman->ForNode(nodeid, [&](CNode *pnode) {
182 LOCK(pnode->cs_avalanche_pubkey);
183 bool expected = false;
184 if (pnode->m_avalanche_enabled.compare_exchange_strong(
185 expected, true)) {
186 pnode->m_avalanche_pubkey = std::move(key);
187 }
188 return true;
189 })) {
190 throw JSONRPCError(
192 strprintf("The node does not exist: %d", nodeid));
193 }
194
195 return avalanche.withPeerManager([&](avalanche::PeerManager &pm) {
196 if (!pm.addNode(nodeid, proofid)) {
197 return false;
198 }
199
200 pm.addUnbroadcastProof(proofid);
201 return true;
202 });
203 },
204 };
205}
206
208 return RPCHelpMan{
209 "buildavalancheproof",
210 "Build a proof for avalanche's sybil resistance.\n",
211 {
213 "The proof's sequence"},
215 "A timestamp indicating when the proof expire"},
217 "The master private key in base58-encoding"},
218 {
219 "stakes",
222 "The stakes to be signed and associated private keys",
223 {
224 {
225 "stake",
228 "A stake to be attached to this proof",
229 {
230 {"txid", RPCArg::Type::STR_HEX,
231 RPCArg::Optional::NO, "The transaction id"},
233 "The output number"},
234 {"amount", RPCArg::Type::AMOUNT,
235 RPCArg::Optional::NO, "The amount in this UTXO"},
237 "The height at which this UTXO was mined"},
238 {"iscoinbase", RPCArg::Type::BOOL,
239 RPCArg::Default{false},
240 "Indicate wether the UTXO is a coinbase"},
241 {"privatekey", RPCArg::Type::STR,
243 "private key in base58-encoding"},
244 },
245 },
246 },
247 },
248 {"payoutAddress", RPCArg::Type::STR, RPCArg::Optional::NO,
249 "A payout address"},
250 },
252 "A string that is a serialized, hex-encoded proof data."},
253 RPCExamples{HelpExampleRpc("buildavalancheproof",
254 "0 1234567800 \"<master>\" []")},
255 [&](const RPCHelpMan &self, const Config &config,
256 const JSONRPCRequest &request) -> UniValue {
257 const uint64_t sequence = request.params[0].getInt<int64_t>();
258 const int64_t expiration = request.params[1].getInt<int64_t>();
259
260 CKey masterKey = DecodeSecret(request.params[2].get_str());
261 if (!masterKey.IsValid()) {
262 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid master key");
263 }
264
265 CTxDestination payoutAddress = DecodeDestination(
266 request.params[4].get_str(), config.GetChainParams());
267
268 if (!IsValidDestination(payoutAddress)) {
270 "Invalid payout address");
271 }
272
273 avalanche::ProofBuilder pb(sequence, expiration, masterKey,
274 GetScriptForDestination(payoutAddress));
275
276 const UniValue &stakes = request.params[3].get_array();
277 for (size_t i = 0; i < stakes.size(); i++) {
278 const UniValue &stake = stakes[i];
280 stake,
281 {
282 {"txid", UniValue::VSTR},
283 {"vout", UniValue::VNUM},
284 // "amount" is also required but check is done below
285 // due to UniValue::VNUM erroneously not accepting
286 // quoted numerics (which are valid JSON)
287 {"height", UniValue::VNUM},
288 {"privatekey", UniValue::VSTR},
289 });
290
291 int nOut = stake.find_value("vout").getInt<int>();
292 if (nOut < 0) {
294 "vout cannot be negative");
295 }
296
297 const int height = stake.find_value("height").getInt<int>();
298 if (height < 1) {
300 "height must be positive");
301 }
302
303 const TxId txid(ParseHashO(stake, "txid"));
304 const COutPoint utxo(txid, nOut);
305
306 if (!stake.exists("amount")) {
307 throw JSONRPCError(RPC_INVALID_PARAMETER, "Missing amount");
308 }
309
310 const Amount amount =
311 AmountFromValue(stake.find_value("amount"));
312
313 const UniValue &iscbparam = stake.find_value("iscoinbase");
314 const bool iscoinbase =
315 iscbparam.isNull() ? false : iscbparam.get_bool();
316 CKey key =
317 DecodeSecret(stake.find_value("privatekey").get_str());
318
319 if (!key.IsValid()) {
321 "Invalid private key");
322 }
323
324 if (!pb.addUTXO(utxo, amount, uint32_t(height), iscoinbase,
325 std::move(key))) {
327 "Duplicated stake");
328 }
329 }
330
331 const avalanche::ProofRef proof = pb.build();
332
333 return proof->ToHex();
334 },
335 };
336}
337
339 return RPCHelpMan{
340 "decodeavalancheproof",
341 "Convert a serialized, hex-encoded proof, into JSON object. "
342 "The validity of the proof is not verified.\n",
343 {
345 "The proof hex string"},
346 },
347 RPCResult{
349 "",
350 "",
351 {
352 {RPCResult::Type::NUM, "sequence",
353 "The proof's sequential number"},
354 {RPCResult::Type::NUM, "expiration",
355 "A timestamp indicating when the proof expires"},
356 {RPCResult::Type::STR_HEX, "master", "The master public key"},
357 {RPCResult::Type::STR, "signature",
358 "The proof signature (base64 encoded)"},
360 "payoutscript",
361 "The proof payout script",
362 {
363 {RPCResult::Type::STR, "asm", "Decoded payout script"},
365 "Raw payout script in hex format"},
366 {RPCResult::Type::STR, "type",
367 "The output type (e.g. " + GetAllOutputTypes() + ")"},
368 {RPCResult::Type::NUM, "reqSigs",
369 "The required signatures"},
371 "addresses",
372 "",
373 {
374 {RPCResult::Type::STR, "address", "eCash address"},
375 }},
376 }},
377 {RPCResult::Type::STR_HEX, "limitedid",
378 "A hash of the proof data excluding the master key."},
379 {RPCResult::Type::STR_HEX, "proofid",
380 "A hash of the limitedid and master key."},
381 {RPCResult::Type::STR_AMOUNT, "staked_amount",
382 "The total staked amount of this proof in " +
383 Currency::get().ticker + "."},
384 {RPCResult::Type::NUM, "score", "The score of this proof."},
386 "stakes",
387 "",
388 {
390 "",
391 "",
392 {
394 "The transaction id"},
395 {RPCResult::Type::NUM, "vout", "The output number"},
397 "The amount in this UTXO"},
398 {RPCResult::Type::NUM, "height",
399 "The height at which this UTXO was mined"},
400 {RPCResult::Type::BOOL, "iscoinbase",
401 "Indicate whether the UTXO is a coinbase"},
402 {RPCResult::Type::STR_HEX, "pubkey",
403 "This UTXO's public key"},
404 {RPCResult::Type::STR, "signature",
405 "Signature of the proofid with this UTXO's private "
406 "key (base64 encoded)"},
407 }},
408 }},
409 }},
410 RPCExamples{HelpExampleCli("decodeavalancheproof", "\"<hex proof>\"") +
411 HelpExampleRpc("decodeavalancheproof", "\"<hex proof>\"")},
412 [&](const RPCHelpMan &self, const Config &config,
413 const JSONRPCRequest &request) -> UniValue {
414 avalanche::Proof proof;
415 bilingual_str error;
416 if (!avalanche::Proof::FromHex(proof, request.params[0].get_str(),
417 error)) {
419 }
420
421 UniValue result(UniValue::VOBJ);
422 result.pushKV("sequence", proof.getSequence());
423 result.pushKV("expiration", proof.getExpirationTime());
424 result.pushKV("master", HexStr(proof.getMaster()));
425 result.pushKV("signature", EncodeBase64(proof.getSignature()));
426
427 const auto payoutScript = proof.getPayoutScript();
428 UniValue payoutScriptObj(UniValue::VOBJ);
429 ScriptPubKeyToUniv(payoutScript, payoutScriptObj,
430 /* fIncludeHex */ true);
431 result.pushKV("payoutscript", payoutScriptObj);
432
433 result.pushKV("limitedid", proof.getLimitedId().ToString());
434 result.pushKV("proofid", proof.getId().ToString());
435
436 result.pushKV("staked_amount", proof.getStakedAmount());
437 result.pushKV("score", uint64_t(proof.getScore()));
438
439 UniValue stakes(UniValue::VARR);
440 for (const avalanche::SignedStake &s : proof.getStakes()) {
441 const COutPoint &utxo = s.getStake().getUTXO();
443 stake.pushKV("txid", utxo.GetTxId().ToString());
444 stake.pushKV("vout", uint64_t(utxo.GetN()));
445 stake.pushKV("amount", s.getStake().getAmount());
446 stake.pushKV("height", uint64_t(s.getStake().getHeight()));
447 stake.pushKV("iscoinbase", s.getStake().isCoinbase());
448 stake.pushKV("pubkey", HexStr(s.getStake().getPubkey()));
449 // Only PKHash destination is supported, so this is safe
450 stake.pushKV("address",
451 EncodeDestination(PKHash(s.getStake().getPubkey()),
452 config));
453 stake.pushKV("signature", EncodeBase64(s.getSignature()));
454 stakes.push_back(stake);
455 }
456 result.pushKV("stakes", stakes);
457
458 return result;
459 },
460 };
461}
462
464 return RPCHelpMan{
465 "delegateavalancheproof",
466 "Delegate the avalanche proof to another public key.\n",
467 {
469 "The limited id of the proof to be delegated."},
471 "The private key in base58-encoding. Must match the proof master "
472 "public key or the upper level parent delegation public key if "
473 " supplied."},
475 "The public key to delegate the proof to."},
477 "A string that is the serialized, hex-encoded delegation for the "
478 "proof and which is a parent for the delegation to build."},
479 },
481 "A string that is a serialized, hex-encoded delegation."},
483 HelpExampleRpc("delegateavalancheproof",
484 "\"<limitedproofid>\" \"<privkey>\" \"<pubkey>\"")},
485 [&](const RPCHelpMan &self, const Config &config,
486 const JSONRPCRequest &request) -> UniValue {
487 avalanche::LimitedProofId limitedProofId{
488 ParseHashV(request.params[0], "limitedproofid")};
489
490 const CKey privkey = DecodeSecret(request.params[1].get_str());
491 if (!privkey.IsValid()) {
493 "The private key is invalid");
494 }
495
496 const CPubKey pubkey = ParsePubKey(request.params[2]);
497
498 std::unique_ptr<avalanche::DelegationBuilder> dgb;
499 if (request.params.size() >= 4 && !request.params[3].isNull()) {
501 CPubKey auth;
502 verifyDelegationOrThrow(dg, request.params[3].get_str(), auth);
503
504 if (dg.getProofId() !=
505 limitedProofId.computeProofId(dg.getProofMaster())) {
506 throw JSONRPCError(
508 "The delegation does not match the proof");
509 }
510
511 if (privkey.GetPubKey() != auth) {
512 throw JSONRPCError(
514 "The private key does not match the delegation");
515 }
516
517 dgb = std::make_unique<avalanche::DelegationBuilder>(dg);
518 } else {
519 dgb = std::make_unique<avalanche::DelegationBuilder>(
520 limitedProofId, privkey.GetPubKey());
521 }
522
523 if (!dgb->addLevel(privkey, pubkey)) {
525 "Unable to build the delegation");
526 }
527
528 DataStream ss{};
529 ss << dgb->build();
530 return HexStr(ss);
531 },
532 };
533}
534
536 return RPCHelpMan{
537 "decodeavalanchedelegation",
538 "Convert a serialized, hex-encoded avalanche proof delegation, into "
539 "JSON object. \n"
540 "The validity of the delegation is not verified.\n",
541 {
543 "The delegation hex string"},
544 },
545 RPCResult{
547 "",
548 "",
549 {
550 {RPCResult::Type::STR_HEX, "pubkey",
551 "The public key the proof is delegated to."},
552 {RPCResult::Type::STR_HEX, "proofmaster",
553 "The delegated proof master public key."},
554 {RPCResult::Type::STR_HEX, "delegationid",
555 "The identifier of this delegation."},
556 {RPCResult::Type::STR_HEX, "limitedid",
557 "A delegated proof data hash excluding the master key."},
558 {RPCResult::Type::STR_HEX, "proofid",
559 "A hash of the delegated proof limitedid and master key."},
560 {RPCResult::Type::NUM, "depth",
561 "The number of delegation levels."},
563 "levels",
564 "",
565 {
567 "",
568 "",
569 {
570 {RPCResult::Type::NUM, "index",
571 "The index of this delegation level."},
572 {RPCResult::Type::STR_HEX, "pubkey",
573 "This delegated public key for this level"},
574 {RPCResult::Type::STR, "signature",
575 "Signature of this delegation level (base64 "
576 "encoded)"},
577 }},
578 }},
579 }},
580 RPCExamples{HelpExampleCli("decodeavalanchedelegation",
581 "\"<hex delegation>\"") +
582 HelpExampleRpc("decodeavalanchedelegation",
583 "\"<hex delegation>\"")},
584 [&](const RPCHelpMan &self, const Config &config,
585 const JSONRPCRequest &request) -> UniValue {
586 avalanche::Delegation delegation;
587 bilingual_str error;
589 delegation, request.params[0].get_str(), error)) {
591 }
592
593 UniValue result(UniValue::VOBJ);
594 result.pushKV("pubkey", HexStr(delegation.getDelegatedPubkey()));
595 result.pushKV("proofmaster", HexStr(delegation.getProofMaster()));
596 result.pushKV("delegationid", delegation.getId().ToString());
597 result.pushKV("limitedid",
598 delegation.getLimitedProofId().ToString());
599 result.pushKV("proofid", delegation.getProofId().ToString());
600
601 auto levels = delegation.getLevels();
602 result.pushKV("depth", uint64_t(levels.size()));
603
604 UniValue levelsArray(UniValue::VARR);
605 for (auto &level : levels) {
607 obj.pushKV("pubkey", HexStr(level.pubkey));
608 obj.pushKV("signature", EncodeBase64(level.sig));
609 levelsArray.push_back(std::move(obj));
610 }
611 result.pushKV("levels", levelsArray);
612
613 return result;
614 },
615 };
616}
617
619 return RPCHelpMan{
620 "getavalancheinfo",
621 "Returns an object containing various state info regarding avalanche "
622 "networking.\n",
623 {},
624 RPCResult{
626 "",
627 "",
628 {
629 {RPCResult::Type::BOOL, "ready_to_poll",
630 "Whether the node is ready to start polling and voting."},
632 "local",
633 "Only available if -avaproof has been supplied to the node",
634 {
635 {RPCResult::Type::BOOL, "verified",
636 "Whether the node local proof has been locally verified "
637 "or not."},
638 {RPCResult::Type::STR, "verification_status",
639 "The proof verification status. Only available if the "
640 "\"verified\" flag is false."},
641 {RPCResult::Type::STR_HEX, "proofid",
642 "The node local proof id."},
643 {RPCResult::Type::STR_HEX, "limited_proofid",
644 "The node local limited proof id."},
645 {RPCResult::Type::STR_HEX, "master",
646 "The node local proof master public key."},
647 {RPCResult::Type::STR, "payout_address",
648 "The node local proof payout address. This might be "
649 "omitted if the payout script is not one of P2PK, P2PKH "
650 "or P2SH, in which case decodeavalancheproof can be used "
651 "to get more details."},
652 {RPCResult::Type::STR_AMOUNT, "stake_amount",
653 "The node local proof staked amount."},
654 }},
656 "network",
657 "",
658 {
659 {RPCResult::Type::NUM, "proof_count",
660 "The number of valid avalanche proofs we know exist "
661 "(including this node's local proof if applicable)."},
662 {RPCResult::Type::NUM, "connected_proof_count",
663 "The number of avalanche proofs with at least one node "
664 "we are connected to (including this node's local proof "
665 "if applicable)."},
666 {RPCResult::Type::NUM, "dangling_proof_count",
667 "The number of avalanche proofs with no node attached."},
668 {RPCResult::Type::NUM, "finalized_proof_count",
669 "The number of known avalanche proofs that have been "
670 "finalized by avalanche."},
671 {RPCResult::Type::NUM, "conflicting_proof_count",
672 "The number of known avalanche proofs that conflict with "
673 "valid proofs."},
674 {RPCResult::Type::NUM, "immature_proof_count",
675 "The number of known avalanche proofs that have immature "
676 "utxos."},
677 {RPCResult::Type::STR_AMOUNT, "total_stake_amount",
678 "The total staked amount over all the valid proofs in " +
680 " (including this node's local proof if "
681 "applicable)."},
682 {RPCResult::Type::STR_AMOUNT, "connected_stake_amount",
683 "The total staked amount over all the connected proofs "
684 "in " +
686 " (including this node's local proof if "
687 "applicable)."},
688 {RPCResult::Type::STR_AMOUNT, "dangling_stake_amount",
689 "The total staked amount over all the dangling proofs "
690 "in " +
692 " (including this node's local proof if "
693 "applicable)."},
694 {RPCResult::Type::STR_AMOUNT, "immature_stake_amount",
695 "The total staked amount over all the immature proofs "
696 "in " +
698 " (including this node's local proof if "
699 "applicable)."},
700 {RPCResult::Type::NUM, "node_count",
701 "The number of avalanche nodes we are connected to "
702 "(including this node if a local proof is set)."},
703 {RPCResult::Type::NUM, "connected_node_count",
704 "The number of avalanche nodes associated with an "
705 "avalanche proof (including this node if a local proof "
706 "is set)."},
707 {RPCResult::Type::NUM, "pending_node_count",
708 "The number of avalanche nodes pending for a proof."},
709 }},
710 },
711 },
712 RPCExamples{HelpExampleCli("getavalancheinfo", "") +
713 HelpExampleRpc("getavalancheinfo", "")},
714 [&](const RPCHelpMan &self, const Config &config,
715 const JSONRPCRequest &request) -> UniValue {
716 NodeContext &node = EnsureAnyNodeContext(request.context);
718
720 ret.pushKV("ready_to_poll", avalanche.isQuorumEstablished());
721
722 auto localProof = avalanche.getLocalProof();
723 if (localProof != nullptr) {
725 const bool verified = avalanche.withPeerManager(
726 [&](const avalanche::PeerManager &pm) {
727 const avalanche::ProofId &proofid = localProof->getId();
728 return pm.isBoundToPeer(proofid);
729 });
730 local.pushKV("verified", verified);
731 const bool sharing = avalanche.canShareLocalProof();
732 if (!verified) {
734 avalanche.getLocalProofRegistrationState();
735 // If the local proof is not registered but the state is
736 // valid, no registration attempt occurred yet.
737 local.pushKV("verification_status",
738 state.IsValid()
739 ? (sharing ? "pending verification"
740 : "pending inbound connections")
741 : state.GetRejectReason());
742 }
743 local.pushKV("proofid", localProof->getId().ToString());
744 local.pushKV("limited_proofid",
745 localProof->getLimitedId().ToString());
746 local.pushKV("master", HexStr(localProof->getMaster()));
747 CTxDestination destination;
748 if (ExtractDestination(localProof->getPayoutScript(),
749 destination)) {
750 local.pushKV("payout_address",
751 EncodeDestination(destination, config));
752 }
753 local.pushKV("stake_amount", localProof->getStakedAmount());
754 ret.pushKV("local", local);
755 }
756
757 avalanche.withPeerManager([&](avalanche::PeerManager &pm) {
758 UniValue network(UniValue::VOBJ);
759
760 uint64_t proofCount{0};
761 uint64_t connectedProofCount{0};
762 uint64_t finalizedProofCount{0};
763 uint64_t connectedNodeCount{0};
764 Amount totalStakes = Amount::zero();
765 Amount connectedStakes = Amount::zero();
766
767 pm.forEachPeer([&](const avalanche::Peer &peer) {
768 CHECK_NONFATAL(peer.proof != nullptr);
769
770 const bool isLocalProof =
771 localProof &&
772 peer.proof->getId() == localProof->getId();
773
774 ++proofCount;
775 const Amount proofStake = peer.proof->getStakedAmount();
776
777 totalStakes += proofStake;
778
779 if (peer.hasFinalized) {
780 ++finalizedProofCount;
781 }
782
783 if (peer.node_count > 0 || isLocalProof) {
784 ++connectedProofCount;
785 connectedStakes += proofStake;
786 }
787
788 connectedNodeCount += peer.node_count + isLocalProof;
789 });
790
791 Amount immatureStakes = Amount::zero();
793 [&](const avalanche::ProofRef &proof) {
794 immatureStakes += proof->getStakedAmount();
795 });
796
797 network.pushKV("proof_count", proofCount);
798 network.pushKV("connected_proof_count", connectedProofCount);
799 network.pushKV("dangling_proof_count",
800 proofCount - connectedProofCount);
801
802 network.pushKV("finalized_proof_count", finalizedProofCount);
803 network.pushKV(
804 "conflicting_proof_count",
805 uint64_t(pm.getConflictingProofPool().countProofs()));
806 network.pushKV(
807 "immature_proof_count",
808 uint64_t(pm.getImmatureProofPool().countProofs()));
809
810 network.pushKV("total_stake_amount", totalStakes);
811 network.pushKV("connected_stake_amount", connectedStakes);
812 network.pushKV("dangling_stake_amount",
813 totalStakes - connectedStakes);
814 network.pushKV("immature_stake_amount", immatureStakes);
815
816 const uint64_t pendingNodes = pm.getPendingNodeCount();
817 network.pushKV("node_count", connectedNodeCount + pendingNodes);
818 network.pushKV("connected_node_count", connectedNodeCount);
819 network.pushKV("pending_node_count", pendingNodes);
820
821 ret.pushKV("network", network);
822 });
823
824 return ret;
825 },
826 };
827}
828
830 return RPCHelpMan{
831 "getavalanchepeerinfo",
832 "Returns data about an avalanche peer as a json array of objects. If "
833 "no proofid is provided, returns data about all the peers.\n",
834 {
836 "The hex encoded avalanche proof identifier."},
837 },
838 RPCResult{
840 "",
841 "",
842 {{
844 "",
845 "",
846 {{
847 {RPCResult::Type::NUM, "avalanche_peerid",
848 "The avalanche internal peer identifier"},
849 {RPCResult::Type::STR_HEX, "proofid",
850 "The avalanche proof id used by this peer"},
851 {RPCResult::Type::STR_HEX, "proof",
852 "The avalanche proof used by this peer"},
853 {RPCResult::Type::NUM, "nodecount",
854 "The number of nodes for this peer"},
856 "node_list",
857 "",
858 {
859 {RPCResult::Type::NUM, "nodeid",
860 "Node id, as returned by getpeerinfo"},
861 }},
862 }},
863 }},
864 },
865 RPCExamples{HelpExampleCli("getavalanchepeerinfo", "") +
866 HelpExampleCli("getavalanchepeerinfo", "\"proofid\"") +
867 HelpExampleRpc("getavalanchepeerinfo", "") +
868 HelpExampleRpc("getavalanchepeerinfo", "\"proofid\"")},
869 [&](const RPCHelpMan &self, const Config &config,
870 const JSONRPCRequest &request) -> UniValue {
871 NodeContext &node = EnsureAnyNodeContext(request.context);
873
874 auto peerToUniv = [](const avalanche::PeerManager &pm,
875 const avalanche::Peer &peer) {
877
878 obj.pushKV("avalanche_peerid", uint64_t(peer.peerid));
879 obj.pushKV("proofid", peer.getProofId().ToString());
880 obj.pushKV("proof", peer.proof->ToHex());
881
883 pm.forEachNode(peer, [&](const avalanche::Node &n) {
884 nodes.push_back(n.nodeid);
885 });
886
887 obj.pushKV("nodecount", uint64_t(peer.node_count));
888 obj.pushKV("node_list", nodes);
889
890 return obj;
891 };
892
894
895 avalanche.withPeerManager([&](const avalanche::PeerManager &pm) {
896 // If a proofid is provided, only return the associated peer
897 if (!request.params[0].isNull()) {
898 const avalanche::ProofId proofid =
899 avalanche::ProofId::fromHex(
900 request.params[0].get_str());
901 if (!pm.isBoundToPeer(proofid)) {
902 throw JSONRPCError(RPC_INVALID_PARAMETER,
903 "Proofid not found");
904 }
905
906 pm.forPeer(proofid, [&](const avalanche::Peer &peer) {
907 ret.push_back(peerToUniv(pm, peer));
908 return true;
909 });
910
911 return;
912 }
913
914 // If no proofid is provided, return all the peers
915 pm.forEachPeer([&](const avalanche::Peer &peer) {
916 ret.push_back(peerToUniv(pm, peer));
917 });
918 });
919
920 return ret;
921 },
922 };
923}
924
926 return RPCHelpMan{
927 "getavalancheproofs",
928 "Returns an object containing all tracked proofids.\n",
929 {},
930 RPCResult{
932 "",
933 "",
934 {
936 "valid",
937 "",
938 {
939 {RPCResult::Type::STR_HEX, "proofid",
940 "Avalanche proof id"},
941 }},
943 "conflicting",
944 "",
945 {
946 {RPCResult::Type::STR_HEX, "proofid",
947 "Avalanche proof id"},
948 }},
950 "immature",
951 "",
952 {
953 {RPCResult::Type::STR_HEX, "proofid",
954 "Avalanche proof id"},
955 }},
956 },
957 },
958 RPCExamples{HelpExampleCli("getavalancheproofs", "") +
959 HelpExampleRpc("getavalancheproofs", "")},
960 [&](const RPCHelpMan &self, const Config &config,
961 const JSONRPCRequest &request) -> UniValue {
962 NodeContext &node = EnsureAnyNodeContext(request.context);
964
966 avalanche.withPeerManager([&](avalanche::PeerManager &pm) {
967 auto appendProofIds = [&ret](const avalanche::ProofPool &pool,
968 const std::string &key) {
969 UniValue arrOut(UniValue::VARR);
970 for (const avalanche::ProofId &proofid :
971 pool.getProofIds()) {
972 arrOut.push_back(proofid.ToString());
973 }
974 ret.pushKV(key, arrOut);
975 };
976
977 appendProofIds(pm.getValidProofPool(), "valid");
978 appendProofIds(pm.getConflictingProofPool(), "conflicting");
979 appendProofIds(pm.getImmatureProofPool(), "immature");
980 });
981
982 return ret;
983 },
984 };
985}
986
988 return RPCHelpMan{
989 "getstakingreward",
990 "Return a list of possible staking reward winners based on the "
991 "previous "
992 "block hash.\n",
993 {
995 "The previous block hash, hex encoded."},
996 {"recompute", RPCArg::Type::BOOL, RPCArg::Default{false},
997 "Whether to recompute the staking reward winner if there is a "
998 "cached value."},
999 },
1000 RPCResult{
1002 "",
1003 "",
1004 {
1006 "winner",
1007 "The winning proof",
1008 {
1009 {RPCResult::Type::STR_HEX, "proofid",
1010 "The winning proofid"},
1011 {RPCResult::Type::STR, "asm", "Decoded payout script"},
1013 "Raw payout script in hex format"},
1014 {RPCResult::Type::STR, "type",
1015 "The output type (e.g. " + GetAllOutputTypes() + ")"},
1016 {RPCResult::Type::NUM, "reqSigs",
1017 "The required signatures"},
1019 "addresses",
1020 "",
1021 {
1022 {RPCResult::Type::STR, "address", "eCash address"},
1023 }},
1024 }},
1025 }},
1026 RPCExamples{HelpExampleRpc("getstakingreward", "<blockhash>")},
1027 [&](const RPCHelpMan &self, const Config &config,
1028 const JSONRPCRequest &request) -> UniValue {
1029 const NodeContext &node = EnsureAnyNodeContext(request.context);
1032
1033 const BlockHash blockhash(
1034 ParseHashV(request.params[0], "blockhash"));
1035
1036 const CBlockIndex *pprev;
1037 {
1038 LOCK(cs_main);
1039 pprev = chainman.m_blockman.LookupBlockIndex(blockhash);
1040 }
1041
1042 if (!pprev) {
1043 throw JSONRPCError(
1045 strprintf("Block not found: %s\n", blockhash.ToString()));
1046 }
1047
1049 config.GetChainParams().GetConsensus(), pprev)) {
1050 throw JSONRPCError(
1052 strprintf(
1053 "Staking rewards are not activated for block %s\n",
1054 blockhash.ToString()));
1055 }
1056
1057 if (!request.params[1].isNull() && request.params[1].get_bool()) {
1058 // Force recompute the staking reward winner by first erasing
1059 // the cached entry if any
1060 avalanche.eraseStakingRewardWinner(blockhash);
1061 }
1062
1063 if (!avalanche.computeStakingReward(pprev)) {
1064 throw JSONRPCError(
1066 strprintf("Unable to determine a staking reward winner "
1067 "for block %s\n",
1068 blockhash.ToString()));
1069 }
1070
1071 std::vector<std::pair<avalanche::ProofId, CScript>> winners;
1072 if (!avalanche.getStakingRewardWinners(blockhash, winners)) {
1073 throw JSONRPCError(
1075 strprintf("Unable to retrieve the staking reward winner "
1076 "for block %s\n",
1077 blockhash.ToString()));
1078 }
1079
1080 UniValue winnersArr(UniValue::VARR);
1081 for (auto &winner : winners) {
1082 UniValue stakingRewardsObj(UniValue::VOBJ);
1083 ScriptPubKeyToUniv(winner.second, stakingRewardsObj,
1084 /*fIncludeHex=*/true);
1085 stakingRewardsObj.pushKV("proofid", winner.first.GetHex());
1086 winnersArr.push_back(stakingRewardsObj);
1087 }
1088
1089 return winnersArr;
1090 },
1091 };
1092}
1093
1095 return RPCHelpMan{
1096 "hasstakingreward",
1097 "Return true if a staking reward winner exists based on the previous "
1098 "block hash.\n",
1099 {
1101 "The previous block hash, hex encoded."},
1102 },
1104 "Whether staking reward winner has been computed for "
1105 "previous block hash or not."},
1106 RPCExamples{HelpExampleRpc("hasstakingreward", "<blockhash>")},
1107 [&](const RPCHelpMan &self, const Config &config,
1108 const JSONRPCRequest &request) -> UniValue {
1109 const NodeContext &node = EnsureAnyNodeContext(request.context);
1112
1113 const BlockHash blockhash(
1114 ParseHashV(request.params[0], "blockhash"));
1115
1116 const CBlockIndex *pprev;
1117 {
1118 LOCK(cs_main);
1119 pprev = chainman.m_blockman.LookupBlockIndex(blockhash);
1120 }
1121
1122 if (!pprev) {
1123 throw JSONRPCError(
1125 strprintf("Block not found: %s\n", blockhash.ToString()));
1126 }
1127
1129 config.GetChainParams().GetConsensus(), pprev)) {
1130 throw JSONRPCError(
1132 strprintf(
1133 "Staking rewards are not activated for block %s\n",
1134 blockhash.ToString()));
1135 }
1136
1137 std::vector<std::pair<avalanche::ProofId, CScript>> winners;
1138 if (!avalanche.getStakingRewardWinners(blockhash, winners)) {
1139 return false;
1140 }
1141 return winners.size() > 0;
1142 },
1143 };
1144}
1145
1147 return RPCHelpMan{
1148 "setstakingreward",
1149 "Set the staking reward winner for the given previous block hash.\n",
1150 {
1152 "The previous block hash, hex encoded."},
1154 "The payout script for the staking reward, hex encoded."},
1155 {"append", RPCArg::Type::BOOL, RPCArg::Default{false},
1156 "Append to the list of possible winners instead of replacing."},
1157 },
1159 "Whether the payout script was set or not"},
1161 HelpExampleRpc("setstakingreward", "<blockhash> <payout script>")},
1162 [&](const RPCHelpMan &self, const Config &config,
1163 const JSONRPCRequest &request) -> UniValue {
1164 const NodeContext &node = EnsureAnyNodeContext(request.context);
1167
1168 const BlockHash blockhash(
1169 ParseHashV(request.params[0], "blockhash"));
1170
1171 const CBlockIndex *pprev;
1172 {
1173 LOCK(cs_main);
1174 pprev = chainman.m_blockman.LookupBlockIndex(blockhash);
1175 }
1176
1177 if (!pprev) {
1178 throw JSONRPCError(
1180 strprintf("Block not found: %s\n", blockhash.ToString()));
1181 }
1182
1184 config.GetChainParams().GetConsensus(), pprev)) {
1185 throw JSONRPCError(
1187 strprintf(
1188 "Staking rewards are not activated for block %s\n",
1189 blockhash.ToString()));
1190 }
1191
1192 const std::vector<uint8_t> data =
1193 ParseHex(request.params[1].get_str());
1194 CScript payoutScript(data.begin(), data.end());
1195
1196 std::vector<CScript> payoutScripts;
1197
1198 if (!request.params[2].isNull() && request.params[2].get_bool()) {
1199 // Append mode, initialize our list with the current winners
1200 // and the new one will be added to the back of that list. If
1201 // there is no winner the list will remain empty.
1202 avalanche.getStakingRewardWinners(blockhash, payoutScripts);
1203 }
1204
1205 if (std::find(payoutScripts.begin(), payoutScripts.end(),
1206 payoutScript) != payoutScripts.end()) {
1207 throw JSONRPCError(
1209 strprintf(
1210 "Staking rewards winner is already set for block %s\n",
1211 blockhash.ToString()));
1212 }
1213
1214 payoutScripts.push_back(std::move(payoutScript));
1215
1216 // This will return true upon insertion or false upon replacement.
1217 // We want to convey the success of the RPC, so we always return
1218 // true.
1219 avalanche.setStakingRewardWinners(pprev, payoutScripts);
1220 return true;
1221 },
1222 };
1223}
1224
1226 return RPCHelpMan{
1227 "getremoteproofs",
1228 "Get the list of remote proofs for the given node id.\n",
1229 {
1231 "The node identifier."},
1232 },
1233 RPCResult{
1235 "proofs",
1236 "",
1237 {{
1239 "proof",
1240 "",
1241 {{
1242 {RPCResult::Type::STR_HEX, "proofid",
1243 "The hex encoded proof identifier."},
1244 {RPCResult::Type::BOOL, "present",
1245 "Whether the node has the proof."},
1246 {RPCResult::Type::NUM, "last_update",
1247 "The last time this proof status was updated."},
1248 }},
1249 }},
1250 },
1251 RPCExamples{HelpExampleRpc("getremoteproofs", "<nodeid>")},
1252 [&](const RPCHelpMan &self, const Config &config,
1253 const JSONRPCRequest &request) -> UniValue {
1254 NodeContext &node = EnsureAnyNodeContext(request.context);
1256
1257 const NodeId nodeid = request.params[0].getInt<int64_t>();
1258 auto remoteProofs = avalanche.withPeerManager(
1259 [nodeid](const avalanche::PeerManager &pm) {
1260 return pm.getRemoteProofs(nodeid);
1261 });
1262
1263 UniValue arrOut(UniValue::VARR);
1264
1265 for (const auto &remoteProof : remoteProofs) {
1267 obj.pushKV("proofid", remoteProof.proofid.ToString());
1268 obj.pushKV("present", remoteProof.present);
1269 obj.pushKV("last_update", remoteProof.lastUpdate.count());
1270
1271 arrOut.push_back(obj);
1272 }
1273
1274 return arrOut;
1275 },
1276 };
1277}
1278
1280 return RPCHelpMan{
1281 "getrawavalancheproof",
1282 "Lookup for a known avalanche proof by id.\n",
1283 {
1285 "The hex encoded avalanche proof identifier."},
1286 },
1287 RPCResult{
1289 "",
1290 "",
1291 {{
1292 {RPCResult::Type::STR_HEX, "proof",
1293 "The hex encoded proof matching the identifier."},
1294 {RPCResult::Type::BOOL, "immature",
1295 "Whether the proof has immature utxos."},
1296 {RPCResult::Type::BOOL, "boundToPeer",
1297 "Whether the proof is bound to an avalanche peer."},
1298 {RPCResult::Type::BOOL, "conflicting",
1299 "Whether the proof has a conflicting UTXO with an avalanche "
1300 "peer."},
1301 {RPCResult::Type::BOOL, "finalized",
1302 "Whether the proof is finalized by vote."},
1303 }},
1304 },
1305 RPCExamples{HelpExampleRpc("getrawavalancheproof", "<proofid>")},
1306 [&](const RPCHelpMan &self, const Config &config,
1307 const JSONRPCRequest &request) -> UniValue {
1308 NodeContext &node = EnsureAnyNodeContext(request.context);
1310
1311 const avalanche::ProofId proofid =
1312 avalanche::ProofId::fromHex(request.params[0].get_str());
1313
1314 bool isImmature = false;
1315 bool isBoundToPeer = false;
1316 bool conflicting = false;
1317 bool finalized = false;
1318 auto proof = avalanche.withPeerManager(
1319 [&](const avalanche::PeerManager &pm) {
1320 isImmature = pm.isImmature(proofid);
1321 isBoundToPeer = pm.isBoundToPeer(proofid);
1322 conflicting = pm.isInConflictingPool(proofid);
1323 finalized =
1324 pm.forPeer(proofid, [&](const avalanche::Peer &p) {
1325 return p.hasFinalized;
1326 });
1327 return pm.getProof(proofid);
1328 });
1329
1330 if (!proof) {
1331 throw JSONRPCError(RPC_INVALID_PARAMETER, "Proof not found");
1332 }
1333
1335
1336 DataStream ss{};
1337 ss << *proof;
1338 ret.pushKV("proof", HexStr(ss));
1339 ret.pushKV("immature", isImmature);
1340 ret.pushKV("boundToPeer", isBoundToPeer);
1341 ret.pushKV("conflicting", conflicting);
1342 ret.pushKV("finalized", finalized);
1343
1344 return ret;
1345 },
1346 };
1347}
1348
1350 return RPCHelpMan{
1351 "invalidateavalancheproof",
1352 "Reject a known avalanche proof by id.\n",
1353 {
1355 "The hex encoded avalanche proof identifier."},
1356 },
1357 RPCResult{
1359 "success",
1360 "",
1361 },
1362 RPCExamples{HelpExampleRpc("invalidateavalancheproof", "<proofid>")},
1363 [&](const RPCHelpMan &self, const Config &config,
1364 const JSONRPCRequest &request) -> UniValue {
1365 NodeContext &node = EnsureAnyNodeContext(request.context);
1367
1368 const avalanche::ProofId proofid =
1369 avalanche::ProofId::fromHex(request.params[0].get_str());
1370
1371 avalanche.withPeerManager([&](avalanche::PeerManager &pm) {
1372 if (!pm.exists(proofid) && !pm.isDangling(proofid)) {
1373 throw JSONRPCError(RPC_INVALID_PARAMETER,
1374 "Proof not found");
1375 }
1376
1377 if (!pm.rejectProof(
1378 proofid,
1380 throw JSONRPCError(RPC_INTERNAL_ERROR,
1381 "Failed to reject the proof");
1382 }
1383
1384 pm.setInvalid(proofid);
1385 });
1386
1387 if (avalanche.isRecentlyFinalized(proofid)) {
1388 // If the proof was previously finalized, clear the status.
1389 // Because there is no way to selectively delete an entry from a
1390 // Bloom filter, we have to clear the whole filter which could
1391 // cause extra voting rounds.
1392 avalanche.clearFinalizedItems();
1393 }
1394
1395 return true;
1396 },
1397 };
1398}
1399
1401 return RPCHelpMan{
1402 "isfinalblock",
1403 "Check if a block has been finalized by avalanche votes.\n",
1404 {
1406 "The hash of the block."},
1407 },
1409 "Whether the block has been finalized by avalanche votes."},
1410 RPCExamples{HelpExampleRpc("isfinalblock", "<block hash>") +
1411 HelpExampleCli("isfinalblock", "<block hash>")},
1412 [&](const RPCHelpMan &self, const Config &config,
1413 const JSONRPCRequest &request) -> UniValue {
1414 NodeContext &node = EnsureAnyNodeContext(request.context);
1416
1417 if (!avalanche.isQuorumEstablished()) {
1419 "Avalanche is not ready to poll yet.");
1420 }
1421
1422 ChainstateManager &chainman = EnsureAnyChainman(request.context);
1423 const BlockHash blockhash(
1424 ParseHashV(request.params[0], "blockhash"));
1425 const CBlockIndex *pindex;
1426
1427 {
1428 LOCK(cs_main);
1429 pindex = chainman.m_blockman.LookupBlockIndex(blockhash);
1430
1431 if (!pindex) {
1433 "Block not found");
1434 }
1435 }
1436
1437 return chainman.ActiveChainstate().IsBlockAvalancheFinalized(
1438 pindex);
1439 },
1440 };
1441}
1442
1444 return RPCHelpMan{
1445 "isfinaltransaction",
1446 "Check if a transaction has been finalized by avalanche votes.\n",
1447 {
1449 "The id of the transaction."},
1451 "The block in which to look for the transaction"},
1452 },
1453 RPCResult{
1454 RPCResult::Type::BOOL, "success",
1455 "Whether the transaction has been finalized by avalanche votes."},
1456 RPCExamples{HelpExampleRpc("isfinaltransaction", "<txid> <blockhash>") +
1457 HelpExampleCli("isfinaltransaction", "<txid> <blockhash>")},
1458 [&](const RPCHelpMan &self, const Config &config,
1459 const JSONRPCRequest &request) -> UniValue {
1460 const NodeContext &node = EnsureAnyNodeContext(request.context);
1462 const CTxMemPool &mempool = EnsureMemPool(node);
1464
1465 const TxId txid = TxId(ParseHashV(request.params[0], "txid"));
1466 CBlockIndex *pindex = nullptr;
1467
1468 if (!request.params[1].isNull()) {
1469 const BlockHash blockhash(
1470 ParseHashV(request.params[1], "blockhash"));
1471
1472 LOCK(cs_main);
1473 pindex = chainman.m_blockman.LookupBlockIndex(blockhash);
1474 if (!pindex) {
1476 "Block not found");
1477 }
1478 }
1479
1480 bool f_txindex_ready = false;
1481 if (g_txindex && !pindex) {
1482 f_txindex_ready = g_txindex->BlockUntilSyncedToCurrentChain();
1483 }
1484
1485 BlockHash hash_block;
1487 pindex, &mempool, txid, hash_block, chainman.m_blockman);
1488
1489 if (!avalanche.isQuorumEstablished()) {
1491 "Avalanche is not ready to poll yet.");
1492 }
1493
1494 if (!tx) {
1495 std::string errmsg;
1496 if (pindex) {
1497 if (WITH_LOCK(::cs_main,
1498 return !pindex->nStatus.hasData())) {
1500 "Block data not downloaded yet.");
1501 }
1502 errmsg = "No such transaction found in the provided block.";
1503 } else if (!g_txindex) {
1504 errmsg = "No such transaction. Use -txindex or provide a "
1505 "block hash to enable blockchain transaction "
1506 "queries.";
1507 } else if (!f_txindex_ready) {
1508 errmsg = "No such transaction. Blockchain transactions are "
1509 "still in the process of being indexed.";
1510 } else {
1511 errmsg = "No such mempool or blockchain transaction.";
1512 }
1514 }
1515
1516 if (!pindex) {
1517 LOCK(cs_main);
1518 pindex = chainman.m_blockman.LookupBlockIndex(hash_block);
1519 }
1520
1521 if (!tx) {
1522 // Tx not found, we should have raised an error at this stage
1523 return false;
1524 }
1525
1526 if (WITH_LOCK(
1527 mempool.cs,
1528 return mempool.isAvalancheFinalizedPreConsensus(txid))) {
1529 // The transaction is finalized
1530 return true;
1531 }
1532
1533 // Return true if the tx is in a finalized block
1534 return !node.mempool->exists(txid) &&
1535 chainman.ActiveChainstate().IsBlockAvalancheFinalized(
1536 pindex);
1537 },
1538 };
1539}
1540
1542 return RPCHelpMan{
1543 "reconsideravalancheproof",
1544 "Reconsider a known avalanche proof.\n",
1545 {
1547 "The hex encoded avalanche proof."},
1548 },
1549 RPCResult{
1551 "success",
1552 "Whether the proof has been successfully registered.",
1553 },
1554 RPCExamples{HelpExampleRpc("reconsideravalancheproof", "<proof hex>")},
1555 [&](const RPCHelpMan &self, const Config &config,
1556 const JSONRPCRequest &request) -> UniValue {
1557 auto proof = RCUPtr<avalanche::Proof>::make();
1558
1559 NodeContext &node = EnsureAnyNodeContext(request.context);
1561
1562 // Verify the proof. Note that this is redundant with the
1563 // verification done when adding the proof to the pool, but we get a
1564 // chance to give a better error message.
1565 verifyProofOrThrow(node, *proof, request.params[0].get_str());
1566
1567 // There is no way to selectively clear the invalidation status of
1568 // a single proof, so we clear the whole Bloom filter. This could
1569 // cause extra voting rounds.
1570 avalanche.withPeerManager([&](avalanche::PeerManager &pm) {
1571 if (pm.isInvalid(proof->getId())) {
1572 pm.clearAllInvalid();
1573 }
1574 });
1575
1576 // Add the proof to the pool if we don't have it already. Since the
1577 // proof verification has already been done, a failure likely
1578 // indicates that there already is a proof with conflicting utxos.
1580 if (!registerProofIfNeeded(avalanche, proof, state)) {
1582 strprintf("%s (%s)\n",
1583 state.GetRejectReason(),
1584 state.GetDebugMessage()));
1585 }
1586
1587 return avalanche.withPeerManager(
1588 [&](const avalanche::PeerManager &pm) {
1589 return pm.isBoundToPeer(proof->getId());
1590 });
1591 },
1592 };
1593}
1594
1596 return RPCHelpMan{
1597 "sendavalancheproof",
1598 "Broadcast an avalanche proof.\n",
1599 {
1601 "The avalanche proof to broadcast."},
1602 },
1604 "Whether the proof was sent successfully or not."},
1605 RPCExamples{HelpExampleRpc("sendavalancheproof", "<proof>")},
1606 [&](const RPCHelpMan &self, const Config &config,
1607 const JSONRPCRequest &request) -> UniValue {
1608 auto proof = RCUPtr<avalanche::Proof>::make();
1609
1610 NodeContext &node = EnsureAnyNodeContext(request.context);
1612
1613 // Verify the proof. Note that this is redundant with the
1614 // verification done when adding the proof to the pool, but we get a
1615 // chance to give a better error message.
1616 verifyProofOrThrow(node, *proof, request.params[0].get_str());
1617
1618 // Add the proof to the pool if we don't have it already. Since the
1619 // proof verification has already been done, a failure likely
1620 // indicates that there already is a proof with conflicting utxos.
1621 const avalanche::ProofId &proofid = proof->getId();
1623 if (!registerProofIfNeeded(avalanche, proof, state)) {
1625 strprintf("%s (%s)\n",
1626 state.GetRejectReason(),
1627 state.GetDebugMessage()));
1628 }
1629
1630 avalanche.withPeerManager([&](avalanche::PeerManager &pm) {
1631 pm.addUnbroadcastProof(proofid);
1632 });
1633
1634 if (node.peerman) {
1635 node.peerman->RelayProof(proofid);
1636 }
1637
1638 return true;
1639 },
1640 };
1641}
1642
1644 return RPCHelpMan{
1645 "verifyavalancheproof",
1646 "Verify an avalanche proof is valid and return the error otherwise.\n",
1647 {
1649 "Proof to verify."},
1650 },
1652 "Whether the proof is valid or not."},
1653 RPCExamples{HelpExampleRpc("verifyavalancheproof", "\"<proof>\"")},
1654 [&](const RPCHelpMan &self, const Config &config,
1655 const JSONRPCRequest &request) -> UniValue {
1656 avalanche::Proof proof;
1657 verifyProofOrThrow(EnsureAnyNodeContext(request.context), proof,
1658 request.params[0].get_str());
1659
1660 return true;
1661 },
1662 };
1663}
1664
1666 return RPCHelpMan{
1667 "verifyavalanchedelegation",
1668 "Verify an avalanche delegation is valid and return the error "
1669 "otherwise.\n",
1670 {
1672 "The avalanche proof delegation to verify."},
1673 },
1675 "Whether the delegation is valid or not."},
1676 RPCExamples{HelpExampleRpc("verifyavalanchedelegation", "\"<proof>\"")},
1677 [&](const RPCHelpMan &self, const Config &config,
1678 const JSONRPCRequest &request) -> UniValue {
1679 avalanche::Delegation delegation;
1680 CPubKey dummy;
1681 verifyDelegationOrThrow(delegation, request.params[0].get_str(),
1682 dummy);
1683
1684 return true;
1685 },
1686 };
1687}
1688
1690 return RPCHelpMan{
1691 "setflakyproof",
1692 "Add or remove a proofid from the flaky list. This means that an "
1693 "additional staking reward winner will be accepted if this proof is "
1694 "the selected one.\n",
1695 {
1697 "The avalanche proof id."},
1699 "Whether to add (true) or remove (false) the proof from the flaky "
1700 "list"},
1701 },
1703 "Whether the addition/removal is successful."},
1704 RPCExamples{HelpExampleRpc("setflakyproof", "\"<proofid>\" true")},
1705 [&](const RPCHelpMan &self, const Config &config,
1706 const JSONRPCRequest &request) -> UniValue {
1707 NodeContext &node = EnsureAnyNodeContext(request.context);
1710
1711 const auto proofid =
1712 avalanche::ProofId::fromHex(request.params[0].get_str());
1713 const bool addNotRemove = request.params[1].get_bool();
1714
1715 if (avalanche.withPeerManager(
1716 [&proofid, addNotRemove](avalanche::PeerManager &pm) {
1717 if (addNotRemove) {
1718 return pm.setFlaky(proofid);
1719 }
1720 return pm.unsetFlaky(proofid);
1721 })) {
1722 const CBlockIndex *pprev =
1723 WITH_LOCK(cs_main, return chainman.ActiveTip());
1724 // Force recompute the staking reward winner by first erasing
1725 // the cached entry if any
1726 avalanche.eraseStakingRewardWinner(pprev->GetBlockHash());
1727 return avalanche.computeStakingReward(pprev);
1728 }
1729
1730 return false;
1731 }};
1732}
1733
1735 return RPCHelpMan{
1736 "getflakyproofs",
1737 "List the flaky proofs (set via setflakyproof).\n",
1738 {},
1739 RPCResult{
1741 "flaky_proofs",
1742 "",
1743 {{
1745 "proof",
1746 "",
1747 {{
1748 {RPCResult::Type::STR_HEX, "proofid",
1749 "The hex encoded proof identifier."},
1750 {RPCResult::Type::STR_AMOUNT, "staked_amount",
1751 "The proof stake amount, only present if the proof is "
1752 "known."},
1754 "payout",
1755 "The proof payout script, only present if the proof is "
1756 "known.",
1757 {
1758 {RPCResult::Type::STR, "asm", "Decoded payout script"},
1760 "Raw payout script in hex format"},
1761 {RPCResult::Type::STR, "type",
1762 "The output type (e.g. " + GetAllOutputTypes() + ")"},
1763 {RPCResult::Type::NUM, "reqSigs",
1764 "The required signatures"},
1766 "addresses",
1767 "",
1768 {
1769 {RPCResult::Type::STR, "address",
1770 "eCash address"},
1771 }},
1772 }},
1773 }},
1774 }},
1775 },
1776 RPCExamples{HelpExampleRpc("getflakyproofs", "")},
1777 [&](const RPCHelpMan &self, const Config &config,
1778 const JSONRPCRequest &request) -> UniValue {
1779 NodeContext &node = EnsureAnyNodeContext(request.context);
1781
1782 UniValue flakyProofs(UniValue::VARR);
1783 avalanche.withPeerManager([&flakyProofs](
1785 pm.forEachFlakyProof([&](const avalanche::ProofId &proofid) {
1786 UniValue flakyProof(UniValue::VOBJ);
1787 flakyProof.pushKV("proofid", proofid.GetHex());
1788
1789 const auto proof = pm.getProof(proofid);
1790 if (proof) {
1791 flakyProof.pushKV("staked_amount",
1792 proof->getStakedAmount());
1793 UniValue payout(UniValue::VOBJ);
1794 ScriptPubKeyToUniv(proof->getPayoutScript(), payout,
1795 /*fIncludeHex=*/true);
1796 flakyProof.pushKV("payout", payout);
1797 }
1798
1799 flakyProofs.push_back(flakyProof);
1800 });
1801 });
1802
1803 return flakyProofs;
1804 }};
1805}
1806
1808 return RPCHelpMan{
1809 "getavailabilityscore",
1810 "Return the node availability score.\n",
1811 {
1812 {"nodeid", RPCArg::Type::NUM, RPCArg::Optional::NO, "The node id."},
1813 },
1814 RPCResult{RPCResult::Type::NUM, "availability_score",
1815 "The node availability score (if any)."},
1816 RPCExamples{HelpExampleRpc("getavailabilityscore", "<nodeid>")},
1817 [&](const RPCHelpMan &self, const Config &config,
1818 const JSONRPCRequest &request) -> UniValue {
1819 const NodeContext &node = EnsureAnyNodeContext(request.context);
1820 const CConnman &connman = EnsureConnman(node);
1821
1822 const NodeId nodeid(request.params[0].getInt<int64_t>());
1823
1824 CNodeStats nodeStats;
1825 if (connman.GetNodeStats(nodeid, nodeStats) &&
1826 nodeStats.m_availabilityScore) {
1827 return *nodeStats.m_availabilityScore;
1828 }
1829
1830 return UniValue::VNULL;
1831 },
1832 };
1833}
1834
1836 return RPCHelpMan{
1837 "getstakecontendervote",
1838 "Return the stake contender avalanche vote.\n",
1839 {
1841 "The prevblockhash used to compute the stake contender ID, hex "
1842 "encoded."},
1844 "The proofid used to compute the stake contender ID, hex "
1845 "encoded."},
1846 },
1848 "The vote that would be returned if polled."},
1849 RPCExamples{HelpExampleRpc("getstakecontendervote",
1850 "<prevblockhash> <proofid>")},
1851 [&](const RPCHelpMan &self, const Config &config,
1852 const JSONRPCRequest &request) -> UniValue {
1853 const NodeContext &node = EnsureAnyNodeContext(request.context);
1855
1856 const BlockHash prevblockhash(
1857 ParseHashV(request.params[0], "prevblockhash"));
1858 const avalanche::ProofId proofid(
1859 ParseHashV(request.params[1], "proofid"));
1860 const avalanche::StakeContenderId contenderId(prevblockhash,
1861 proofid);
1862 return avalanche.getStakeContenderStatus(contenderId);
1863 },
1864 };
1865}
1866
1868 return RPCHelpMan{
1869 "finalizetransaction",
1870 "Force finalize a mempool transaction. No attempt is made to poll for "
1871 "this transaction and this could cause the node to disagree with the "
1872 "network. This can fail if the transaction to be finalized would "
1873 "overflow the block size. Upon success it will be included in the "
1874 "block template.\n",
1875 {
1877 "The id of the transaction to be finalized."},
1878 },
1880 "finalized_txids",
1881 "The list of the successfully finalized txids if any (it can "
1882 "include ancestors of the target txid).",
1883 {{
1885 "txid",
1886 "The finalized transaction id.",
1887 }}},
1888 RPCExamples{HelpExampleRpc("finalizetransaction", "<txid>")},
1889 [&](const RPCHelpMan &self, const Config &config,
1890 const JSONRPCRequest &request) -> UniValue {
1891 const NodeContext &node = EnsureAnyNodeContext(request.context);
1892 CTxMemPool &mempool = EnsureAnyMemPool(request.context);
1893 const ChainstateManager &chainman = EnsureChainman(node);
1894
1895 const TxId txid(ParseHashV(request.params[0], "txid"));
1896
1897 LOCK2(cs_main, mempool.cs);
1898 auto entry = mempool.GetIter(txid);
1899 if (!entry) {
1901 "The transaction is not in the mempool.");
1902 }
1903
1904 const CBlockIndex *tip = chainman.ActiveTip();
1905 if (!tip) {
1907 "There is no active chain tip.");
1908 }
1909
1911
1912 std::vector<TxId> finalizedTxids;
1913 if (!mempool.setAvalancheFinalized(**entry, chainman.GetConsensus(),
1914 *tip, finalizedTxids)) {
1915 // If the function returned false, the finalizedTxids vector
1916 // should not be relied upon
1917 return ret;
1918 }
1919
1920 for (TxId &finalizedTxid : finalizedTxids) {
1921 ret.push_back(finalizedTxid.ToString());
1922
1923 // FIXME we might want to remove from the recent rejects as well
1924 // if it exists so we don't vote against this tx anymore. For
1925 // now this is a private data from the PeerManager and can only
1926 // be cleared entirely. Also a rejected transaction is not
1927 // expected to be in the mempool in the first place so this is
1928 // probably safe.
1929 }
1930
1931 return ret;
1932 },
1933 };
1934}
1935
1937 return RPCHelpMan{
1938 "removetransaction",
1939 "Remove a transaction and all its descendants from the mempool. If the "
1940 "transaction is final it is removed anyway. No attempt is made to poll "
1941 "for this transaction and this could cause the node to disagree with "
1942 "the network.\n",
1943 {
1945 "The id of the transaction to be removed."},
1946 },
1948 "removed_txids",
1949 "The list of the removed txids if any (it can include "
1950 "descendants of the target txid).",
1951 {{
1953 "txid",
1954 "The removed transaction id.",
1955 }}},
1956 RPCExamples{HelpExampleRpc("removetransaction", "<txid>")},
1957 [&](const RPCHelpMan &self, const Config &config,
1958 const JSONRPCRequest &request) -> UniValue {
1959 CTxMemPool &mempool = EnsureAnyMemPool(request.context);
1960
1961 const TxId txid(ParseHashV(request.params[0], "txid"));
1962
1963 LOCK(mempool.cs);
1964 auto iter = mempool.GetIter(txid);
1965 if (!iter) {
1967 "The transaction is not in the mempool.");
1968 }
1969
1970 // This mostly mimics the CTxMemPool::removeRecursive function so we
1971 // can return the list of removed txids
1972 CTxMemPool::setEntries setDescendants;
1973 mempool.CalculateDescendants(*iter, setDescendants);
1974
1976 for (auto &it : setDescendants) {
1977 ret.push_back((*it)->GetSharedTx()->GetId().ToString());
1978 }
1979
1980 mempool.RemoveStaged(setDescendants, MemPoolRemovalReason::MANUAL);
1981
1982 return ret;
1983 },
1984 };
1985}
1986
1988 return RPCHelpMan{
1989 "getfinaltransactions",
1990 "Returns all finalized transactions that have not been included in a "
1991 "finalized block yet.",
1992 {
1993 {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false},
1994 "True for a json object, false for an array of transaction ids"},
1995 },
1996 {
1997 RPCResult{"for verbose = false",
1999 "",
2000 "",
2001 {
2002 {RPCResult::Type::STR_HEX, "", "The transaction id"},
2003 }},
2004 RPCResult{"for verbose = true",
2006 "",
2007 "",
2008 {{
2010 "",
2011 "",
2012 DecodeTxDoc(/*txid_field_doc=*/"The transaction id",
2013 /*wallet=*/false),
2014 }}},
2015 },
2016 RPCExamples{HelpExampleCli("getfinaltransactions", "true") +
2017 HelpExampleRpc("getfinaltransactions", "true")},
2018 [&](const RPCHelpMan &self, const Config &config,
2019 const JSONRPCRequest &request) -> UniValue {
2020 const bool fVerbose =
2021 !request.params[0].isNull() && request.params[0].get_bool();
2022
2023 const CTxMemPool &mempool = EnsureAnyMemPool(request.context);
2024
2025 UniValue finalTxs(UniValue::VARR);
2026 {
2027 LOCK(mempool.cs);
2028 mempool.finalizedTxs.forEachLeaf(
2029 [fVerbose, &finalTxs](const CTxMemPoolEntryRef &entryRef) {
2030 if (!fVerbose) {
2031 finalTxs.push_back(
2032 entryRef->GetTx().GetId().GetHex());
2033 } else {
2035 TxToUniv(entryRef->GetTx(), BlockHash(), tx,
2036 /*include_hex=*/true);
2037 finalTxs.push_back(std::move(tx));
2038 }
2039 return true;
2040 });
2041 }
2042
2043 return finalTxs;
2044 },
2045 };
2046}
2047
2049 // clang-format off
2050 static const CRPCCommand commands[] = {
2051 // category actor (function)
2052 // ----------------- --------------------
2053 { "avalanche", getavalanchekey, },
2054 { "avalanche", addavalanchenode, },
2055 { "avalanche", buildavalancheproof, },
2056 { "avalanche", decodeavalancheproof, },
2057 { "avalanche", delegateavalancheproof, },
2058 { "avalanche", decodeavalanchedelegation, },
2059 { "avalanche", getavalancheinfo, },
2060 { "avalanche", getavalanchepeerinfo, },
2061 { "avalanche", getavalancheproofs, },
2062 { "avalanche", getstakingreward, },
2063 { "hidden", hasstakingreward, },
2064 { "avalanche", setstakingreward, },
2065 { "avalanche", getremoteproofs, },
2066 { "avalanche", getrawavalancheproof, },
2067 { "avalanche", invalidateavalancheproof, },
2068 { "avalanche", isfinalblock, },
2069 { "avalanche", isfinaltransaction, },
2070 { "avalanche", reconsideravalancheproof, },
2071 { "avalanche", sendavalancheproof, },
2072 { "avalanche", verifyavalancheproof, },
2073 { "avalanche", verifyavalanchedelegation, },
2074 { "avalanche", setflakyproof, },
2075 { "avalanche", getflakyproofs, },
2076 { "avalanche", finalizetransaction, },
2077 { "avalanche", removetransaction, },
2078 { "avalanche", getfinaltransactions, },
2079 { "hidden", getavailabilityscore, },
2080 { "hidden", getstakecontendervote, },
2081 };
2082 // clang-format on
2083
2084 for (const auto &c : commands) {
2085 t.appendCommand(c.name, &c);
2086 }
2087}
static RPCHelpMan buildavalancheproof()
Definition: avalanche.cpp:207
static RPCHelpMan invalidateavalancheproof()
Definition: avalanche.cpp:1349
static RPCHelpMan delegateavalancheproof()
Definition: avalanche.cpp:463
static RPCHelpMan getremoteproofs()
Definition: avalanche.cpp:1225
static RPCHelpMan decodeavalanchedelegation()
Definition: avalanche.cpp:535
static RPCHelpMan sendavalancheproof()
Definition: avalanche.cpp:1595
static RPCHelpMan getavalancheproofs()
Definition: avalanche.cpp:925
static void verifyDelegationOrThrow(avalanche::Delegation &dg, const std::string &dgHex, CPubKey &auth)
Definition: avalanche.cpp:82
static RPCHelpMan getrawavalancheproof()
Definition: avalanche.cpp:1279
static void verifyProofOrThrow(const NodeContext &node, avalanche::Proof &proof, const std::string &proofHex)
Definition: avalanche.cpp:96
void RegisterAvalancheRPCCommands(CRPCTable &t)
Definition: avalanche.cpp:2048
static RPCHelpMan getavalanchekey()
Definition: avalanche.cpp:35
static RPCHelpMan hasstakingreward()
Definition: avalanche.cpp:1094
static RPCHelpMan addavalanchenode()
Definition: avalanche.cpp:122
static CPubKey ParsePubKey(const UniValue &param)
Definition: avalanche.cpp:51
static RPCHelpMan finalizetransaction()
Definition: avalanche.cpp:1867
static RPCHelpMan getavailabilityscore()
Definition: avalanche.cpp:1807
static RPCHelpMan getstakecontendervote()
Definition: avalanche.cpp:1835
static RPCHelpMan verifyavalanchedelegation()
Definition: avalanche.cpp:1665
static RPCHelpMan setflakyproof()
Definition: avalanche.cpp:1689
static RPCHelpMan getfinaltransactions()
Definition: avalanche.cpp:1987
static RPCHelpMan removetransaction()
Definition: avalanche.cpp:1936
static RPCHelpMan setstakingreward()
Definition: avalanche.cpp:1146
static RPCHelpMan getflakyproofs()
Definition: avalanche.cpp:1734
static RPCHelpMan isfinalblock()
Definition: avalanche.cpp:1400
static RPCHelpMan reconsideravalancheproof()
Definition: avalanche.cpp:1541
static RPCHelpMan isfinaltransaction()
Definition: avalanche.cpp:1443
static RPCHelpMan getstakingreward()
Definition: avalanche.cpp:987
static bool registerProofIfNeeded(const avalanche::Processor &avalanche, avalanche::ProofRef proof, avalanche::ProofRegistrationState &state)
Definition: avalanche.cpp:63
static RPCHelpMan getavalanchepeerinfo()
Definition: avalanche.cpp:829
static RPCHelpMan verifyavalancheproof()
Definition: avalanche.cpp:1643
static RPCHelpMan getavalancheinfo()
Definition: avalanche.cpp:618
static RPCHelpMan decodeavalancheproof()
Definition: avalanche.cpp:338
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:53
#define Assert(val)
Identity function.
Definition: check.h:84
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
BlockHash GetBlockHash() const
Definition: blockindex.h:130
Definition: net.h:815
void GetNodeStats(std::vector< CNodeStats > &vstats) const
Definition: net.cpp:2780
An encapsulated secp256k1 private key.
Definition: key.h:28
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:97
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:209
Information about a peer.
Definition: net.h:386
An encapsulated public key.
Definition: pubkey.h:31
static constexpr unsigned int COMPRESSED_SIZE
Definition: pubkey.h:37
static constexpr unsigned int SIZE
secp256k1:
Definition: pubkey.h:36
RPC command dispatcher.
Definition: server.h:194
void appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:328
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:221
std::set< txiter, CompareIteratorById > setEntries
Definition: txmempool.h:321
RecursiveMutex cs
This mutex needs to be locked when accessing mapTx or other members that are guarded by it.
Definition: txmempool.h:317
bool setAvalancheFinalized(const CTxMemPoolEntryRef &tx, const Consensus::Params &params, const CBlockIndex &active_chain_tip, std::vector< TxId > &finalizedTxIds) EXCLUSIVE_LOCKS_REQUIRED(bool isAvalancheFinalizedPreConsensus(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Definition: txmempool.h:541
RadixTree< CTxMemPoolEntry, MemPoolEntryRadixTreeAdapter > finalizedTxs
Definition: txmempool.h:324
void CalculateDescendants(txiter it, setEntries &setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Populate setDescendants with all in-mempool descendants of hash.
Definition: txmempool.cpp:242
void RemoveStaged(const setEntries &stage, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs)
Remove a set of transactions from the mempool.
Definition: txmempool.cpp:836
std::optional< txiter > GetIter(const TxId &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Returns an iterator to the given txid, if found.
Definition: txmempool.cpp:744
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1185
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:1436
CBlockIndex * ActiveTip() const EXCLUSIVE_LOCKS_REQUIRED(GetMutex())
Definition: validation.h:1443
const Consensus::Params & GetConsensus() const
Definition: validation.h:1281
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1326
Definition: config.h:19
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:118
static RCUPtr make(Args &&...args)
Construct a new object that is owned by the pointer.
Definition: rcu.h:112
void push_back(UniValue val)
Definition: univalue.cpp:96
const std::string & get_str() const
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:229
@ VNULL
Definition: univalue.h:30
@ VOBJ
Definition: univalue.h:31
@ VSTR
Definition: univalue.h:33
@ VARR
Definition: univalue.h:32
@ VNUM
Definition: univalue.h:34
bool isNull() const
Definition: univalue.h:104
size_t size() const
Definition: univalue.h:92
Int getInt() const
Definition: univalue.h:157
const UniValue & get_array() const
bool exists(const std::string &key) const
Definition: univalue.h:99
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:115
bool get_bool() const
bool IsValid() const
Definition: validation.h:119
std::string GetRejectReason() const
Definition: validation.h:123
std::string GetDebugMessage() const
Definition: validation.h:124
std::string ToString() const
Definition: validation.h:125
ProofId getProofId() const
Definition: delegation.cpp:56
const std::vector< Level > & getLevels() const
Definition: delegation.h:64
static bool FromHex(Delegation &dg, const std::string &dgHex, bilingual_str &errorOut)
Definition: delegation.cpp:16
bool verify(DelegationState &state, CPubKey &auth) const
Definition: delegation.cpp:73
const CPubKey & getProofMaster() const
Definition: delegation.h:62
const DelegationId & getId() const
Definition: delegation.h:60
const CPubKey & getDelegatedPubkey() const
Definition: delegation.cpp:60
const LimitedProofId & getLimitedProofId() const
Definition: delegation.h:61
std::vector< RemoteProof > getRemoteProofs(const NodeId nodeid) const
bool isDangling(const ProofId &proofid) const
bool unsetFlaky(const ProofId &proofid)
bool exists(const ProofId &proofid) const
Return true if the (valid) proof exists, but only for non-dangling proofs.
Definition: peermanager.h:411
const ProofPool & getValidProofPool() const
Definition: peermanager.h:510
bool forPeer(const ProofId &proofid, Callable &&func) const
Definition: peermanager.h:419
bool addNode(NodeId nodeid, const ProofId &proofid)
Node API.
Definition: peermanager.cpp:33
void addUnbroadcastProof(const ProofId &proofid)
Proof broadcast API.
bool isBoundToPeer(const ProofId &proofid) const
size_t getPendingNodeCount() const
Definition: peermanager.h:319
const ProofPool & getImmatureProofPool() const
Definition: peermanager.h:514
void forEachPeer(Callable &&func) const
Definition: peermanager.h:425
void setInvalid(const ProofId &proofid)
void forEachNode(const Peer &peer, Callable &&func) const
Definition: peermanager.h:345
const Amount & getStakeUtxoDustThreshold() const
Definition: peermanager.h:530
void forEachFlakyProof(Callable &&func) const
Definition: peermanager.h:457
bool isInvalid(const ProofId &proofid) const
bool isImmature(const ProofId &proofid) const
bool rejectProof(const ProofId &proofid, RejectionMode mode=RejectionMode::DEFAULT)
const ProofPool & getConflictingProofPool() const
Definition: peermanager.h:511
bool isInConflictingPool(const ProofId &proofid) const
ProofRef getProof(const ProofId &proofid) const
bool registerProof(const ProofRef &proof, ProofRegistrationState &registrationState, RegistrationMode mode=RegistrationMode::DEFAULT)
bool addUTXO(COutPoint utxo, Amount amount, uint32_t height, bool is_coinbase, CKey key)
int64_t getExpirationTime() const
Definition: proof.h:164
static bool FromHex(Proof &proof, const std::string &hexProof, bilingual_str &errorOut)
Definition: proof.cpp:52
bool verify(const Amount &stakeUtxoDustThreshold, ProofValidationState &state) const
Definition: proof.cpp:120
Amount getStakedAmount() const
Definition: proof.cpp:105
const CPubKey & getMaster() const
Definition: proof.h:165
uint64_t getSequence() const
Definition: proof.h:163
const LimitedProofId & getLimitedId() const
Definition: proof.h:171
const SchnorrSig & getSignature() const
Definition: proof.h:168
const CScript & getPayoutScript() const
Definition: proof.h:167
uint32_t getScore() const
Definition: proof.h:175
const ProofId & getId() const
Definition: proof.h:170
const std::vector< SignedStake > & getStakes() const
Definition: proof.h:166
Map a proof to each utxo.
Definition: proofpool.h:57
size_t countProofs() const
Definition: proofpool.cpp:129
void forEachProof(Callable &&func) const
Definition: proofpool.h:118
ProofIdSet getProofIds() const
Definition: proofpool.cpp:101
std::string ToString() const
Definition: uint256.h:80
std::string GetHex() const
Definition: uint256.cpp:16
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:194
void TxToUniv(const CTransaction &tx, const BlockHash &hashBlock, UniValue &entry, bool include_hex=true, const CTxUndo *txundo=nullptr, TxVerbosity verbosity=TxVerbosity::SHOW_DETAILS, std::function< bool(const CTxOut &)> is_change_func={})
Definition: core_write.cpp:221
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
int64_t NodeId
Definition: eviction.h:16
std::string EncodeDestination(const CTxDestination &dest, const Config &config)
Definition: key_io.cpp:167
CTxDestination DecodeDestination(const std::string &addr, const CChainParams &params)
Definition: key_io.cpp:174
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:77
static constexpr Amount PROOF_DUST_THRESHOLD
Minimum amount per utxo.
Definition: proof.h:41
Definition: init.h:31
CTransactionRef GetTransaction(const CBlockIndex *const block_index, const CTxMemPool *const mempool, const TxId &txid, BlockHash &hashBlock, const BlockManager &blockman)
Return transaction with a given txid.
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:315
std::vector< RPCResult > DecodeTxDoc(const std::string &txid_field_doc, bool wallet)
Explain the UniValue "decoded" transaction object, may include extra fields if processed by wallet.
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:58
@ RPC_MISC_ERROR
General application defined errors std::exception thrown in command handling.
Definition: protocol.h:38
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:46
@ RPC_INTERNAL_ERROR
Definition: protocol.h:33
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:50
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:42
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:153
Amount AmountFromValue(const UniValue &value)
Definition: util.cpp:58
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:170
std::string GetAllOutputTypes()
Definition: util.cpp:308
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:194
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:93
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded values (throws error if not hex).
Definition: util.cpp:76
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Check for expected keys/value types in an Object.
Definition: util.cpp:29
ChainstateManager & EnsureAnyChainman(const std::any &context)
Definition: server_util.cpp:59
NodeContext & EnsureAnyNodeContext(const std::any &context)
Definition: server_util.cpp:21
CTxMemPool & EnsureMemPool(const NodeContext &node)
Definition: server_util.cpp:29
ChainstateManager & EnsureChainman(const NodeContext &node)
Definition: server_util.cpp:52
CTxMemPool & EnsureAnyMemPool(const std::any &context)
Definition: server_util.cpp:37
avalanche::Processor & EnsureAvalanche(const NodeContext &node)
Definition: server_util.cpp:81
CConnman & EnsureConnman(const NodeContext &node)
Definition: server_util.cpp:63
bool IsStakingRewardsActivated(const Consensus::Params &params, const CBlockIndex *pprev)
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:158
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:260
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:240
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:85
Definition: amount.h:21
static constexpr Amount zero() noexcept
Definition: amount.h:34
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
POD that contains various stats about a node.
Definition: net.h:214
std::optional< double > m_availabilityScore
Definition: net.h:249
static const Currency & get()
Definition: amount.cpp:18
std::string ticker
Definition: amount.h:155
@ STR_HEX
Special type that is a STR with only hex chars.
@ AMOUNT
Special type representing a floating point amount (can be either NUM or STR)
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
@ NO
Required arg.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
bool forEachLeaf(Callable &&func) const
Definition: radix.h:144
A TxId is the identifier of a transaction.
Definition: txid.h:14
NodeId nodeid
Definition: node.h:21
uint32_t node_count
Definition: peermanager.h:89
ProofRef proof
Definition: peermanager.h:91
static ProofId fromHex(const std::string &str)
Definition: proofid.h:21
StakeContenderIds are unique for each block to ensure that the peer polling for their acceptance has ...
Bilingual messages:
Definition: translation.h:17
std::string original
Definition: translation.h:18
NodeContext struct containing references to chain state and connection state.
Definition: context.h:48
#define LOCK2(cs1, cs2)
Definition: sync.h:309
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:17
@ MANUAL
Manual removal via RPC.
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string EncodeBase64(Span< const uint8_t > input)
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.