Skip to content

sgns

More...

Namespaces

Name
sgns::account
sgns::api
sgns::base
sgns::crdt
sgns::crypto
sgns::evmwatcher
sgns::face
sgns::input_validator_constants
sgns::ipfs_bitswap
sgns::ipfs_lite
sgns::ipfs_pubsub
sgns::multisig
sgns::networkregistry
sgns::peerregistry
sgns::processing
sgns::securecrdt
sgns::sgprocessing
Artifact and manifest binary serialization.
sgns::sgprocmanager
sgns::sgprocmanagerdiff
sgns::sgprocmanagerquant
sgns::sgprocmanagersha
sgns::storage
sgns::subscription
sgns::trustedpeer
sgns::utxo_address
sgns::utxo_merkle
Utilities for building deterministic Merkle roots over ordered UTXO payloads.
sgns::version
sgns::watcher

Classes

Name
class sgns::AccountMessenger
class sgns::AndroidSecureStorage
class sgns::AppleSecureStorage
class sgns::Blockchain
Manages genesis/account-creation blocks and consensus integration.
struct sgns::BlockGateResult
Structured verdict of the multi-element block gate (PRUNE-03).
class sgns::BridgeRelayer
Registers both BridgeSourceBurned (v1) and BridgeOutInitiated (v2) watches on a shared EthWatchService across multiple chains and calls MintFunds when burns are detected. OnWatchEvent dispatches on the variant type of values[5] to handle both event formats (D-06).
struct sgns::BurnEventParams
Parsed burn event parameters shared between real-time watch (OnWatchEvent) and startup catch-up scan (PerformStartupCatchupScan).
struct sgns::ChainContractPair
Represents a chain name and its GNUS bridge contract address.
class sgns::ChainRpcEndpointProvider
Encapsulates ChainList RPC endpoint loading and validator wiring.
class sgns::ConsensusManager
Implements Consensus with weighted voting.
class sgns::DevMintInputValidator
class sgns::EscrowTransaction
Transaction that reserves funds for a job escrow while tracking peer payout metadata.
struct sgns::FromMnemonic
Restore from a BIP39 mnemonic.
struct sgns::FromPrivateKey
Restore from an Ethereum hex private key.
struct sgns::FromPublicKey
Load from storage by public address (read-only).
class sgns::GeniusAccount
class sgns::GeniusAssigner
class sgns::GeniusInputValidator
Validator for native Genius-chain transactions.
class sgns::GeniusNode
High-level facade that initializes and coordinates account, networking, transaction, blockchain, and processing subsystems.
class sgns::GeniusProver
Prover class of SuperGenius.
class sgns::GeniusSigner
Owns a Genius keypair without imposing account persistence or lifecycle concerns.
class sgns::GeniusTransaction
Base class of the GeniusTransaction.
class sgns::GeniusUTXO
Immutable-style UTXO value object containing ownership, token, amount, and outpoint metadata.
class sgns::IBasicProof
Base proof class header file.
class sgns::IBridgeInitObserver
Observer interface notified when RPC endpoints have been loaded and wired.
class sgns::IInputValidator
Strategy interface for validating transaction inputs and their witness data.
class sgns::IMigrationStep
Interface for a migration step between two schema versions.
struct sgns::InputUTXOInfo
Raw UTXO input data included in a spend request.
class sgns::IpfsDHT
class sgns::IPriceSource
One price-fetch tier behind the LocalPriceManager (D-13).
class sgns::ISecureStorage
class sgns::JSONBackend
class sgns::JSONSecureStorage
struct sgns::lambda_visitor
struct sgns::lambda_visitor< Lambda >
struct sgns::lambda_visitor< Lambda, Lambdas... >
class sgns::LinuxSecureStorage
class sgns::LocalPriceManager
class sgns::MemorySecureStorage
In-memory JSON backend for tests. Stores data in a map — no OS keychain access, no password prompts, no cleanup needed.
class sgns::Migration0_2_0To1_0_0
Migration step for version 0.2.0 to 1.0.0.
class sgns::Migration1_0_0To3_4_0
Migration step for version 1.0.0 to 3.4.0. Changes the full node topic from CRDT heads.
class sgns::Migration3_4_0To3_5_0
Migration step for version 3.4.0 to 3.5.0. Updates persisted data required by the 3.5.0 node layout.
class sgns::Migration3_5_0To3_6_0
Executes the storage migration from database version 3.5.1 to 3.6.0.
class sgns::Migration3_6_0To3_7_0
Executes the 3.6.0 to 3.7.0 migration, including legacy balance recovery.
class sgns::MigrationAllowList
Stores observed legacy balances and validates migration claim eligibility.
class sgns::MigrationInputValidator
Implements the InputValidator for a Migration type.
class sgns::MigrationManager
Executes a sequence of migration steps to update a CRDT store.
class sgns::MigrationTransaction
class sgns::MintTransaction
Transaction that mints tokens after proving a corresponding source-chain event.
class sgns::MintTransactionV2
Implements a Mint Version 2 transaction.
struct sgns::NewAccount
Account-creation source for GeniusNode::New(dev_config, AccountSource).Generate a new identity.
class sgns::NilFileHelper
struct sgns::OutPoint
Unique identifier for a transaction output.
struct sgns::OutPointHash
Hash functor for using OutPoint keys in unordered containers.
struct sgns::OutputDestInfo
Single UTXO output destination entry.
struct sgns::PriceFetchFailure
Struct error carrier: a code plus the HTTP status that produced it, so tests and logs assert the numeric status without string-matching.
class sgns::PriceHttpClient
Price-fetch facade over the status-aware sgns::HTTPClient transport (02-02): applies the status-before-parse gate (LPM-05), CoinGecko-friendly UA and 5s timeouts (LPM-06, D-08/D-10), the transient-only retry schedule with 429 hold-off (LPM-07, D-11..D-13), and produces PriceQuote objects with fetch-time timestamps (D-14).
class sgns::PriceHttpClientSource
Production tier adapter: a PriceHttpClient wrapped in the IPriceSource seam, closing over the manager's io_context (D-04).
struct sgns::PriceQuote
Provider-independent price quote (QUOTE-01).
class sgns::ProcessingProof
A class for generating and verifying processing proofs.
struct sgns::PruneCandidateResult
Structured verdict for one candidate transaction key.
struct sgns::PruneCycleStats
Counters of ONE prune cycle (RECL-03; counts only).
class sgns::PruneEligibility
Read-only prune-eligibility evaluator (PRUNE-01, GATE-01).
struct sgns::PruneEvaluationResult
Structured result of one evaluation pass (D-03).
struct sgns::PruneStatus
Queryable pruning status (RECL-04).
struct sgns::PruningConfig
Pruning policy configuration (GATE-06 policy half).
class sgns::PublicChainInputValidator
Validator for transactions that reference external public-chain proofs.
class sgns::RateLimitHoldOff
Client-side CoinGecko rate-limit hold-off (D-13): a 429 sets a hold-until timestamp; while held, the CoinGecko tier is skipped entirely (fallback goes straight to the next tier).
class sgns::RecursiveTransferProof
A class for generating a recursive Transfer Proof.
struct sgns::RegistrationDiscoveryEntry
Discovery entry returned by GetRegistrationsForMain.
class sgns::RegistrationTransaction
Transaction for child-wallet registration under a main wallet.
struct sgns::RetryConfig
Fixed retry/backoff schedule (D-12): 1s -> 2s -> (4s, never reached under the default cap of 3 attempts). Tests inject zeros for deterministic zero-backoff runs.
class sgns::RevokeTransaction
Transaction for main-initiated revocation of a registered child wallet.
struct sgns::RpcVerificationEvidence
Structured, claim-bound evidence of which RPC endpoints actually verified a specific bridge claim (issue #364).
class sgns::ScaledInteger
Represents a decimal value using an integer scaled by 10^precision.
class sgns::TokenAmount
Utility for GNUS token fixed-point parsing, formatting and cost calculation.
class sgns::TokenID
Represents a 32-byte token identifier while preserving legacy GNUS semantics.
class sgns::TransactionConsensusHandler
Validates and finalizes transactions on behalf of consensus.
class sgns::TransactionManager
Coordinates transaction creation, CRDT propagation, verification, and status tracking.
class sgns::TransferProof
A class for generating and verifying transfer proofs.
class sgns::TransferTransaction
Transaction for transferring funds between UTXO inputs and outputs.
class sgns::TxPruner
The real prune-cycle service (PRUNE-04).
struct sgns::Unused
class sgns::UTXOManager
class sgns::ValidatorRegistry
Maintains validator registry state and applies certificate-driven updates.
struct sgns::WeightedRpcEndpoint
Weighted RPC endpoint used for multi-provider consensus verification.
class sgns::WindowsSecureStorage

Types

Name
enum class uint8_t NodeType { Full = 0, Light = 1, Archive = 2}
Deployment node role, read from sgns_config.json ("node_type").
enum class PriceFetchError { EmptyInput = 1, NetworkError, JsonParseError, NoDataFound, RateLimitExceeded, DateTooOld, HttpStatus, Blocked}
Typed price-fetch error taxonomy (D-15).
enum class FreshnessBand { Fresh, StaleButUsable, Unavailable}
Freshness classification for a PriceQuote (FRESH-02).
enum class PriceSource { LocalCache, CoinGecko, GnusPriceService, OnChain}
Where a price quote came from (QUOTE-02).
enum class ResponseFormat { CoinGeckoSimplePrice, GnusEnvelope}
Which wire format a PriceHttpClient instance speaks.
enum class RetryDecision { Retry, GiveUp}
Outcome of a retry decision.
enum class uint8_t PruneReason { UNSPENT_OUTPUT, SPENDER_NOT_RECORDED, SPENDER_UNRESOLVED, SPEND_WITHIN_WINDOW, NO_OUTPUTS, OUT_OF_PREFIX, DESERIALIZE_FAILED, NON_ELIGIBLE_SIBLING, CID_UNRESOLVED, SPENDER_PRUNED_WINDOW_SATISFIED, BLOCK_ALREADY_ERASED}
Why one candidate is (or is not) prune-eligible (D-03 structured result).
enum class uint8_t PrunedLookup { PRUNED, NOT_FOUND, VALUE_PRESENT_INVARIANT_VIOLATION}
Tri-state verdict of the pruned-marker lookup (D-04 contract).
using std::function< std::optional< std::string >()> ChainlistFetcher
Fetches the chainlist dataset (JSON text) used to discover public RPC URLs at startup.
using std::variant< NewAccount, FromPrivateKey, FromMnemonic, FromPublicKey > AccountSource
using std::function< std::unique_ptr< eth::rpc::JsonRpcTransport >(const std::string &url, std::chrono::seconds timeout)> TransportFactory
Factory callable that produces a JsonRpcTransport from a URL and timeout.
using std::pair< std::vector< InputUTXOInfo >, std::vector< OutputDestInfo > > UTXOTxParameters
Pair of signed inputs and destination outputs that make up a UTXO transaction payload.
template <typename T >
using boost::outcome_v2::basic_result< T, PriceFetchFailure, boost::outcome_v2::policy::terminate >
PriceResult
result alias carrying the status-bearing failure type.
using std::pair< std::string, base::Buffer > EscrowDataPair

Functions

Name
base::Logger BridgeRelayerLogger()
Returns a new instance of the BridgeRelayer logger.
base::Logger InputValidatorLogger()
base::Logger GeniusNodeLogger()
std::string generate_uuid_with_ipfs_id(const std::string & ipfs_id)
constexpr bool ReplicatesAllAccounts(NodeType type)
Whether this role replicates network-wide data rather than just its own account.
constexpr bool ParticipatesInConsensus(NodeType type)
Whether this role actively participates in consensus and result handling.
constexpr std::string_view NodeTypeToString(NodeType type)
Canonical lowercase name of a role, as accepted in sgns_config.json.
std::optional< NodeType > NodeTypeFromString(std::string_view s)
Parses a node role name, case-insensitively (Phase-2 D-02).
bool DevMintBurnlessPermitted()
True iff THIS process's own net may certify burn-less dev mints.
template <size_t N,class Stream >
Stream &
operator<<(Stream & s, const Unused< N > & )
template <size_t N,class Stream >
Stream &
operator>>(Stream & s, Unused< N > & )
std::string to_string(const std::vector< unsigned char > & bytes)
Convert a byte array to a hexadecimal string.
bool isLittleEndian()
Checks if the architecture is little endian.
template <typename T >
T
Vector2Num(const std::vector< uint8_t > & bytes)
Converts a little-endian byte vector into a number.
uint128_t Vector2Num(const std::vector< uint8_t > & bytes)
uint256_t Vector2Num(const std::vector< uint8_t > & bytes)
template <typename T >
std::vector< uint8_t >
Num2Vector(const T & num, std::size_t num_bytes_resolution =sizeof(T))
Converts a number into a byte vector (little-endian).
template <typename T >
T
HexASCII2Num(const char * p_char, std::size_t num_nibbles_resolution =sizeof(T) *2)
Converts a hexadecimal ASCII char array into a number.
template <typename T >
std::vector< T >
HexASCII2NumStr(const char * p_char, std::size_t char_ptr_size)
Converts a hexadecimal ASCII char array into a vector of numbers.
template <typename T >
std::enable_if_t< std::is_same_v< typename T::value_type, uint8_t > >
AdjustEndianess(T & data, std::optional< typename T::iterator > start =std::nullopt, std::optional< typename T::iterator > finish =std::nullopt)
Adjust endianess if needed.
std::string Uint256ToString(const uint256_t & value)
template <class... Fs>
constexpr auto
make_visitor(Fs &&... fs)
Creates a compile-time visitor from a set of lambdas.
template <typename TVariant ,typename... TVisitors>
constexpr decltype(auto)
visit_in_place(TVariant && variant, TVisitors &&... visitors)
Applies an in-place visitor to a boost::variant.
template <typename T ,typename Matcher >
constexpr decltype(auto)
match(T && t, Matcher && m)
apply Matcher to optional T
template <typename T ,typename... Fs>
constexpr decltype(auto)
match_in_place(T && t, Fs &&... fs)
construct visitor from Fs and apply it to optional T
base::Logger ConsensusManagerLogger()
outcome::result< std::vector< uint8_t > > ProposalSigningBytes(const ConsensusProposal & proposal)
Builds canonical bytes used to sign a consensus proposal.
outcome::result< std::vector< uint8_t > > VoteSigningBytes(const ConsensusVote & vote)
Builds canonical bytes used to sign a consensus vote.
outcome::result< std::vector< uint8_t > > VoteBundleSigningBytes(const ConsensusVoteBundle & bundle)
Builds canonical bytes used to sign a consensus vote bundle.
outcome::result< std::string > ComputeProposalId(const ConsensusProposal & proposal)
Computes deterministic proposal id from proposal content.
bool ValidateProposal(const ConsensusProposal & proposal)
Validates proposal basic shape, signature, and computed id.
std::string GetPriceBaseUrl(const char * envName, const char * productionDefault)
Resolve a price-tier base URL from the environment.
std::string GetCoinGeckoBaseUrl()
Tier 1 base URL: SGNS_COINGECKO_URL when set and non-empty, otherwise https://api.coingecko.com (LPM-09 CoinGecko defaults).
std::string GetFallbackBaseUrl()
Tier 2 base URL: SGNS_PRICE_FALLBACK_URL when set and non-empty, otherwise https://token.gnus.ai (LPM-09 defaults).
FreshnessBand ClassifyFreshness(std::chrono::system_clock::time_point fetchedAt, std::chrono::system_clock::time_point now)
Classify the freshness of a fetched quote.
PriceResult< std::vector< PriceQuote > > ParseCoinGeckoSimplePrice(const std::string & body, const std::vector< std::string > & tokenIds, const std::string & currency, std::chrono::system_clock::time_point fetchTime)
Parse a CoinGecko /simple/price 200-body into quotes.
PriceResult< std::vector< PriceQuote > > ParseGnusPriceEnvelope(const std::string & body, const std::vector< std::string > & tokenIds, const std::string & currency)
Parse a token.gnus.ai price envelope into quotes.
bool IsTransientTransport(http::ClientError error)
Pre-mapping classifier over the transport's own error enum — true for ClientError::TIMEOUT / CONNECT_FAILED / RESOLVE_FAILED only.
bool IsTransient(const PriceFetchFailure & error)
True only for transport-class failures (D-11): timeouts, connection resets, DNS failures. NEVER true for a status-bearing failure (403/429/any HTTP status), parse errors, or input errors.
RetryDecision ShouldRetry(const PriceFetchFailure & error, int attempt, const RetryConfig & config)
Decide whether to make another attempt after a failure.
void InitGeniusSDKAndroid(JavaVM * vm)
GeniusProver::ProofType GetSnarkFromProto(const SGProof::BaseProofData & proof_proto_data)

Attributes

Name
constexpr std::string_view kBridgeSourceBurnedSig
Canonical Solidity event signatures for bridge events. Single source of truth — shared by watch registration, catch-up scan, and RPC endpoint validation.
constexpr std::string_view kBridgeOutInitiatedSig
constexpr std::array< uint16_t, 2 > kDevMintPermittedNets
constexpr std::string_view NONCE_SUBJECT_TYPE
constexpr std::string_view TASK_RESULT_SUBJECT_TYPE
constexpr std::string_view REGISTRY_BATCH_SUBJECT_TYPE
constexpr const char * kCoinGeckoBaseUrlDefault
Production default base URL for tier 1 (CoinGecko direct). The client appends "/api/v3/simple/price".
constexpr const char * kFallbackBaseUrlDefault
Production default base URL for tier 2 (token.gnus.ai fallback). The client appends "/v1/prices".
constexpr std::chrono::seconds kFreshMaxAge
Shared freshness band constants (D-16) consumed by code and tests.
constexpr std::chrono::seconds kStaleMaxAge
constexpr std::string_view FILE_NAME
constexpr size_t MAX_PUBSUB_TX_BYTES

Detailed Description

Header file for IPriceSource — the pure-virtual tier seam behind the LocalPriceManager (Phase 3, D-13). Production adapters (PriceHttpClientSource) and test fakes (FakePriceSource) both target this one interface.

Source file for LocalPriceManager — executor lifecycle (ioc -> work guard -> strand -> thread), blocking GetQuotes promise/future bridge, band-aware L1 cache with copy-on-serve, single-tier inline dispatch, and the drain-then-join destructor (Phase 3 plan 03-01: LPM-01, D-01..D-06, D-13/D-15).

Header file for LocalPriceManager — the device-side local price manager (Phase 3, D-15): the counterpart of the Worker's server-side PriceCoordinator durable object. Same single-flight idea, two scopes.

A self-contained strand-serialized state machine (D-02/D-03): one io_context + one work guard + one strand + ONE dedicated runner thread. All state (the L1 cache, later the per-currency pending windows) is strand-confined — there is not a single mutex in this class.

Header file for PriceEndpoints — production price-tier base-URL configuration via environment variables (Phase 4, LPM-09, D-01/D-02). Header-only: both accessors are tiny free functions over std::getenv.

Header file for PriceHttpClientSource — the production IPriceSource adapter over PriceHttpClient (Phase 3, D-13/D-04). Header-only: the FetchPrices override is a single forwarding return.

Source file for PriceResponseParsers — the two tier parsers (03-03). ParseCoinGeckoSimplePrice is the parse loop moved behavior-identically from PriceHttpClient.cpp:153-175; ParseGnusPriceEnvelope implements the Phase-1 envelope.ts contract.

Header file for PriceResponseParsers — body→PriceQuote assembly for the two price tiers (Phase 3, 03-03): ParseCoinGeckoSimplePrice (extracted behavior-identically from PriceHttpClient.cpp's parse branch) and ParseGnusPriceEnvelope (the Phase-1 envelope contract, D-16).

Source file for the PriceRetryPolicy — transient-only retry classification, fixed backoff schedule, and the CoinGecko 429 hold-off (D-11/D-12/D-13).

Types Documentation

enum NodeType

Enumerator Value Description
Full 0 Full node: replicates everything and participates in consensus.
Light 1 Light node: own account only. Default on missing/unknown key.
Archive 2 Archive node: replicates everything, participates in nothing.

Deployment node role, read from sgns_config.json ("node_type").

  • Full participates in everything: replicates all accounts, proposes, votes, mirrors results.
  • Light replicates only its own account's data.
  • Archive replicates everything like Full, but performs no consensus or result work. It is a passive replica: it stores, it does not act.

enum PriceFetchError

Enumerator Value Description
EmptyInput 1
NetworkError
JsonParseError
NoDataFound
RateLimitExceeded
DateTooOld
HttpStatus
Blocked

Typed price-fetch error taxonomy (D-15).

The first six values keep the legacy price-error names and ordering so log/test vocabulary stayed stable across the Phase 4 cutover (the legacy carrier class was deleted in its entirety per Phase 4 D-09); HttpStatus and Blocked are new.

enum FreshnessBand

Enumerator Value Description
Fresh
StaleButUsable
Unavailable

Freshness classification for a PriceQuote (FRESH-02).

enum PriceSource

Enumerator Value Description
LocalCache
CoinGecko
GnusPriceService
OnChain

Where a price quote came from (QUOTE-02).

Note: OnChain is reserved for the SRC-01 deferred on-chain fallback tier and has no implementation in this phase.

enum ResponseFormat

Enumerator Value Description
CoinGeckoSimplePrice tier 1 — CoinGecko direct: {"id":{"usd":0.19}}
GnusEnvelope tier 2 — token.gnus.ai:

Which wire format a PriceHttpClient instance speaks.

enum RetryDecision

Enumerator Value Description
Retry
GiveUp

Outcome of a retry decision.

enum PruneReason

Enumerator Value Description
UNSPENT_OUTPUT An output is not genuinely consumed (D-C2); synthesized zero-amount tombstones land here — they are not spend evidence.
SPENDER_NOT_RECORDED The output is genuinely consumed but no spending transaction identity was recorded (spent_by_txid unset).
SPENDER_UNRESOLVED The recorded spender's tx->CID map entry was not found, or its priority could not be read (fail closed; the pruned-marker refinement below narrows this). Existence MUST be established BEFORE any priority read: GetKeyPriority reports 0 for a missing key, which would satisfy the window vacuously.
SPEND_WITHIN_WINDOW The most-recent spend is not beyond the finality window (maxHeight − spend_height < N).
NO_OUTPUTS The transaction produces no UTXOs (GetProducedUTXOs nullopt) — no spend evidence can exist (fail closed).
OUT_OF_PREFIX The candidate key is outside the /bc-/tx/ allowlist (defensive; the enumeration prefix already excludes such keys — reported, never dropped).
DESERIALIZE_FAILED The stored value could not be deserialized into a transaction (fail closed; the scan continues).
NON_ELIGIBLE_SIBLING PRUNE-03 block gate: a key the delta block carries (element OR tombstone) is allowlist-conformant but not in the eligible set — the block holds a sibling that is not itself prunable, so the BLOCK is not erasable (the tx can still be eligible on its own).
CID_UNRESOLVED PRUNE-03 block gate: an ELIGIBLE candidate's tx->CID map entry could not be resolved, so no delta-block verdict can be computed — reported as an explicit not-erasable block report (fail closed), never silently dropped from the report (WR-05).
SPENDER_PRUNED_WINDOW_SATISFIED EVIDENCE code (non-failure reason): the spender's own entries are gone because the spender was pruned (marker present, value absent). A pruned spender's own window elapsed by construction, so this spend is older still — the output's window counts as SATISFIED, explicitly (D-02/B spec point 5, never silent).
BLOCK_ALREADY_ERASED EVIDENCE code (non-failure reason): the delta block's BYTES are absent while an otherwise-eligible candidate still names it — the sibling group was already erased through the sanctioned path, so this verdict COMPLETES the stranded candidate's erase (value + map entry + marker; block staging is an idempotent no-op on the absent key). The SPENDER_PRUNED_WINDOW_SATISFIED discipline: explicit affirmative evidence, never a silent pass and never a fail-closed stranding.

Why one candidate is (or is not) prune-eligible (D-03 structured result).

Every ineligible candidate carries at least one of these codes — nothing is silently dropped (repudiability). Codes are fail-closed: each one names a check whose failure must block erasure, EXCEPT the two affirmative-EVIDENCE codes, SPENDER_PRUNED_WINDOW_SATISFIED and BLOCK_ALREADY_ERASED (they appear on ELIGIBLE/erasable verdicts so the evidence behind the verdict is explicit, never silent).

enum PrunedLookup

Enumerator Value Description
PRUNED Marker present AND value absent: the transaction's history was physically pruned on this node.
NOT_FOUND No marker AND no value: the transaction is simply unknown here.
VALUE_PRESENT_INVARIANT_VIOLATION Marker AND value both present: violates the value-XOR-marker invariant (Phase 18 writes both sides in ONE batch, so this state signals corruption — report, never guess which side is right).

Tri-state verdict of the pruned-marker lookup (D-04 contract).

The PRUNED-vs-NOT_FOUND distinction is Phase 19 SURV-02's answer source: "history pruned on this node" is a distinct, reportable state — never conflated with plain not-found. The invariant violation (marker AND value both present) is a state bug and is reported loudly — never guessed away.

using ChainlistFetcher

using sgns::ChainlistFetcher = typedef std::function<std::optional<std::string>()>;

Fetches the chainlist dataset (JSON text) used to discover public RPC URLs at startup.

Return: The chainlist JSON text, or std::nullopt on fetch failure.

Production default: HTTPS GET of https://chainid.network/chains.json. Tests inject a callable returning canned JSON (no network).

using AccountSource

using sgns::AccountSource = typedef std::variant<NewAccount, FromPrivateKey, FromMnemonic, FromPublicKey>;

using TransportFactory

using sgns::TransportFactory = typedef std::function<std::unique_ptr<eth::rpc::JsonRpcTransport>( const std::string &url, std::chrono::seconds timeout )>;

Factory callable that produces a JsonRpcTransport from a URL and timeout.

Parameters:

  • url RPC endpoint URL.
  • timeout Transport operation timeout.

Return: Unique ownership of a transport implementing JsonRpcTransport.

Injected via SetTransportFactory(). When not set, the default factory creates real RpcHttpTransport instances (production path per D-16). Tests inject a factory that returns MockRpcTransport instances (D-07, D-14).

using UTXOTxParameters

using sgns::UTXOTxParameters = typedef std::pair<std::vector<InputUTXOInfo>, std::vector<OutputDestInfo> >;

Pair of signed inputs and destination outputs that make up a UTXO transaction payload.

using PriceResult

template <typename T >
using sgns::PriceResult = typedef boost::outcome_v2::basic_result<T, PriceFetchFailure, boost::outcome_v2::policy::terminate>;

result alias carrying the status-bearing failure type.

The terminate policy is required for a non-error_code error type (boost::outcome's default_policy assumes std::error_code and drags in exception_ptr machinery that cannot convert). Observers used here (bool/operator*/error) are policy-safe.

using EscrowDataPair

using sgns::EscrowDataPair = typedef std::pair<std::string, base::Buffer>;

Functions Documentation

function BridgeRelayerLogger

base::Logger BridgeRelayerLogger()

Returns a new instance of the BridgeRelayer logger.

Return: Logger instance for BridgeRelayer.

Note: This is used for 2 reasons: (1) to enable logging on static methods, and (2) to avoid static initialization order issues when its created before the one with the same name on GeniusNode, which can have the output configured to file. If we initialize this logger statically it could end up outputing to console instead.

function InputValidatorLogger

base::Logger InputValidatorLogger()

function GeniusNodeLogger

base::Logger GeniusNodeLogger()

function generate_uuid_with_ipfs_id

std::string generate_uuid_with_ipfs_id(
    const std::string & ipfs_id
)

function ReplicatesAllAccounts

constexpr bool ReplicatesAllAccounts(
    NodeType type
)

Whether this role replicates network-wide data rather than just its own account.

Return: True for Full and Archive, false for Light.

Gates the full-node topic subscription, network-wide UTXO roots, and full-node blockchain mode — i.e. everything on the "store it" side of the split.

function ParticipatesInConsensus

constexpr bool ParticipatesInConsensus(
    NodeType type
)

Whether this role actively participates in consensus and result handling.

Return: True for Full and Light, false for Archive.

Archive is a passive replica, so it declines the work-generating side of full-node behavior (proposals, certificate authorship, result mirroring) while keeping replication.

function NodeTypeToString

constexpr std::string_view NodeTypeToString(
    NodeType type
)

Canonical lowercase name of a role, as accepted in sgns_config.json.

function NodeTypeFromString

inline std::optional< NodeType > NodeTypeFromString(
    std::string_view s
)

Parses a node role name, case-insensitively (Phase-2 D-02).

Return: The matching role, or std::nullopt if the string is not a known role.

function DevMintBurnlessPermitted

inline bool DevMintBurnlessPermitted()

True iff THIS process's own net may certify burn-less dev mints.

Return: Membership of version::GetNetworkID() in kDevMintPermittedNets.

function operator<<

template <size_t N,
class Stream >
Stream & operator<<(
    Stream & s,
    const Unused< N > & 
)

function operator>>

template <size_t N,
class Stream >
Stream & operator>>(
    Stream & s,
    Unused< N > & 
)

function to_string

static std::string to_string(
    const std::vector< unsigned char > & bytes
)

Convert a byte array to a hexadecimal string.

Parameters:

  • bytes A vector of bytes to be converted.

Return: A hexadecimal string representation of the bytes.

function isLittleEndian

static bool isLittleEndian()

Checks if the architecture is little endian.

Return: true if little endian, false otherwise

function Vector2Num

template <typename T >
static T Vector2Num(
    const std::vector< uint8_t > & bytes
)

Converts a little-endian byte vector into a number.

Parameters:

  • bytes Byte vector to convert.

Template Parameters:

  • T uint8_t, uint16_t, uint32_t, uint64_t, or supported multiprecision integer types.

Return: The converted number.

function Vector2Num

uint128_t Vector2Num(
    const std::vector< uint8_t > & bytes
)

function Vector2Num

uint256_t Vector2Num(
    const std::vector< uint8_t > & bytes
)

function Num2Vector

template <typename T >
static std::vector< uint8_t > Num2Vector(
    const T & num,
    std::size_t num_bytes_resolution =sizeof(T)
)

Converts a number into a byte vector (little-endian).

Parameters:

  • num Number to convert.
  • num_bytes_resolution Optional byte resolution (defaults to sizeof(T)).

Template Parameters:

  • T uint8_t, uint16_t, uint32_t or uint64_t

Return: The converted byte vector.

function HexASCII2Num

template <typename T >
static T HexASCII2Num(
    const char * p_char,
    std::size_t num_nibbles_resolution =sizeof(T) *2
)

Converts a hexadecimal ASCII char array into a number.

Parameters:

  • p_char Hexadecimal ASCII char array
  • num_nibbles_resolution How many nibbles will constitute a number

Template Parameters:

  • T uint8_t, uint16_t, uint32_t or uint64_t

Return: The converted number (8-64 bit variable)

function HexASCII2NumStr

template <typename T >
static std::vector< T > HexASCII2NumStr(
    const char * p_char,
    std::size_t char_ptr_size
)

Converts a hexadecimal ASCII char array into a vector of numbers.

Parameters:

  • p_char Hexadecimal ASCII char array
  • char_ptr_size Size of the char array

Template Parameters:

  • T uint8_t, uint16_t, uint32_t or uint64_t

Return: The vector of converted numbers

function AdjustEndianess

template <typename T >
static std::enable_if_t< std::is_same_v< typename T::value_type, uint8_t > > AdjustEndianess(
    T & data,
    std::optional< typename T::iterator > start =std::nullopt,
    std::optional< typename T::iterator > finish =std::nullopt
)

Adjust endianess if needed.

Parameters:

  • data The container of data (vector/array)
  • start Optional beginning of the valid data
  • finish Optional ending of the valid data

Template Parameters:

  • T std::vector or std::array

function Uint256ToString

static std::string Uint256ToString(
    const uint256_t & value
)

function make_visitor

template <class... Fs>
constexpr auto make_visitor(
    Fs &&... fs
)

Creates a compile-time visitor from a set of lambdas.

Return: Visitor instance that dispatches to the provided lambdas.

Example: ```cpp

make_visitor(, { return 2; });

This is essentially the same as: ```cpp

struct visitor : public boost::static_visitor<int> {
  int operator()(int a) { return 1; }
  int operator()(std::string b) { return 2; }
};

function visit_in_place

template <typename TVariant ,
typename... TVisitors>
constexpr decltype(auto) visit_in_place(
    TVariant && variant,
    TVisitors &&... visitors
)

Applies an in-place visitor to a boost::variant.

Example: ```cpp

boost::variant value = "1234";

visit_in_place(value, { std::cout << "(int)" << v; }, { std::cout << "(string)" << v; });

### function match

```cpp
template <typename T ,
typename Matcher >
constexpr decltype(auto) match(
    T && t,
    Matcher && m
)

apply Matcher to optional T

function match_in_place

template <typename T ,
typename... Fs>
constexpr decltype(auto) match_in_place(
    T && t,
    Fs &&... fs
)

construct visitor from Fs and apply it to optional T

function ConsensusManagerLogger

base::Logger ConsensusManagerLogger()

function ProposalSigningBytes

inline outcome::result< std::vector< uint8_t > > ProposalSigningBytes(
    const ConsensusProposal & proposal
)

Builds canonical bytes used to sign a consensus proposal.

Parameters:

  • proposal Proposal object to serialize for signing.

Return: Serialized signing bytes on success, or std::errc::invalid_argument when protobuf serialization fails.

The signature field is cleared before serialization so signatures are never part of their own signing payload.

function VoteSigningBytes

inline outcome::result< std::vector< uint8_t > > VoteSigningBytes(
    const ConsensusVote & vote
)

Builds canonical bytes used to sign a consensus vote.

Parameters:

  • vote Vote object to serialize for signing.

Return: Serialized signing bytes on success, or std::errc::invalid_argument when protobuf serialization fails.

The signature field is cleared before serialization so signatures are never part of their own signing payload.

function VoteBundleSigningBytes

inline outcome::result< std::vector< uint8_t > > VoteBundleSigningBytes(
    const ConsensusVoteBundle & bundle
)

Builds canonical bytes used to sign a consensus vote bundle.

Parameters:

  • bundle Vote bundle object to serialize for signing.

Return: Serialized signing bytes on success, or std::errc::invalid_argument when protobuf serialization fails.

The signature field is cleared before serialization so signatures are never part of their own signing payload.

function ComputeProposalId

inline outcome::result< std::string > ComputeProposalId(
    const ConsensusProposal & proposal
)

Computes deterministic proposal id from proposal content.

Parameters:

  • proposal Proposal used to derive the identifier.

Return: Lowercase hex SHA-256 proposal id on success, or propagated error when signing bytes cannot be produced.

The proposal id field is cleared before hashing to guarantee stable id derivation from the signed payload content only.

function ValidateProposal

inline bool ValidateProposal(
    const ConsensusProposal & proposal
)

Validates proposal basic shape, signature, and computed id.

Parameters:

  • proposal Proposal to validate.

Return: true when proposer id/signature/id are present, signature is valid, and computed proposal id matches; otherwise false.

function GetPriceBaseUrl

inline std::string GetPriceBaseUrl(
    const char * envName,
    const char * productionDefault
)

Resolve a price-tier base URL from the environment.

Parameters:

  • envName Environment variable name to read
  • productionDefault Base URL used when the variable is unset or empty

Return: The env value when non-null AND non-empty, otherwise the production default

Note: The read is intentionally NOT cached in a function-local static: D-03 requires a fresh read at every LocalPriceManager construction so per-test stub-port redirection takes effect; a static would freeze the first value process-wide.

function GetCoinGeckoBaseUrl

inline std::string GetCoinGeckoBaseUrl()

Tier 1 base URL: SGNS_COINGECKO_URL when set and non-empty, otherwise https://api.coingecko.com (LPM-09 CoinGecko defaults).

Return: The resolved tier 1 base URL

function GetFallbackBaseUrl

inline std::string GetFallbackBaseUrl()

Tier 2 base URL: SGNS_PRICE_FALLBACK_URL when set and non-empty, otherwise https://token.gnus.ai (LPM-09 defaults).

Return: The resolved tier 2 base URL

function ClassifyFreshness

inline FreshnessBand ClassifyFreshness(
    std::chrono::system_clock::time_point fetchedAt,
    std::chrono::system_clock::time_point now
)

Classify the freshness of a fetched quote.

Parameters:

  • fetchedAt D-14 fetch time of the quote
  • now Current time to classify against

Return: The freshness band for age = now - fetchedAt

Note:

  • Boundary rule (D-16): bands are closed on the fresh side. An age of exactly kFreshMaxAge (60s) classifies Fresh, and an age of exactly kStaleMaxAge (300s) classifies StaleButUsable.
  • The age is compared at the clock's native precision (no truncation to whole seconds) so sub-second boundary cases classify exactly.

function ParseCoinGeckoSimplePrice

PriceResult< std::vector< PriceQuote > > ParseCoinGeckoSimplePrice(
    const std::string & body,
    const std::vector< std::string > & tokenIds,
    const std::string & currency,
    std::chrono::system_clock::time_point fetchTime
)

Parse a CoinGecko /simple/price 200-body into quotes.

Parameters:

  • body The 200 response body
  • tokenIds Requested ids — quotes are emitted for requested ids present in the body; unknown ids stay absent, not errors (D-09)
  • currency Target currency
  • fetchTime D-14 fetch time stamped on every quote

Return: One PriceQuote per requested id found in the body, or NoDataFound when none matched, or JsonParseError on malformed JSON (status 0 — the HTTP status belongs to the facade layer)

function ParseGnusPriceEnvelope

PriceResult< std::vector< PriceQuote > > ParseGnusPriceEnvelope(
    const std::string & body,
    const std::vector< std::string > & tokenIds,
    const std::string & currency
)

Parse a token.gnus.ai price envelope into quotes.

Parameters:

  • body The 200 response body (Phase-1 envelope.ts contract)
  • tokenIds Requested ids — quotes are emitted for requested ids present in prices; absent ids stay absent, not errors (D-09)
  • currency Expected target currency (envelope currency)

Return: One PriceQuote per requested id found in prices, or NoDataFound when none matched, or JsonParseError on malformed JSON / an unknown source string (status 0 — the HTTP status belongs to the facade layer)

Note:

  • LANDMINE: envelope fetchedAt is epoch SECONDS (never ms) and is the max across the returned ids, SHARED by all quotes — do not invent per-id timestamps (Phase-1 D-11).
  • LANDMINE: the envelope source names the upstream that PRODUCED the price, not the serving tier — "coingecko" maps to PriceSource::CoinGecko and "coingecko-cache" to PriceSource::GnusPriceService (Phase-1 D-06). Counterintuitive but contractual; do NOT "fix" this.

function IsTransientTransport

bool IsTransientTransport(
    http::ClientError error
)

Pre-mapping classifier over the transport's own error enum — true for ClientError::TIMEOUT / CONNECT_FAILED / RESOLVE_FAILED only.

function IsTransient

bool IsTransient(
    const PriceFetchFailure & error
)

True only for transport-class failures (D-11): timeouts, connection resets, DNS failures. NEVER true for a status-bearing failure (403/429/any HTTP status), parse errors, or input errors.

function ShouldRetry

RetryDecision ShouldRetry(
    const PriceFetchFailure & error,
    int attempt,
    const RetryConfig & config
)

Decide whether to make another attempt after a failure.

Parameters:

  • error The failure from the just-finished attempt
  • attempt 1-based index of the attempt that just failed
  • config The retry schedule in force

Return: Retry iff the error is transient AND attempt < maxAttempts; GiveUp otherwise (403/429 fall through immediately by construction)

function InitGeniusSDKAndroid

void InitGeniusSDKAndroid(
    JavaVM * vm
)

function GetSnarkFromProto

static GeniusProver::ProofType GetSnarkFromProto(
    const SGProof::BaseProofData & proof_proto_data
)

Attributes Documentation

variable kBridgeSourceBurnedSig

constexpr std::string_view kBridgeSourceBurnedSig =
        "BridgeSourceBurned(address,uint256,uint256,uint256,uint256,bytes)";

Canonical Solidity event signatures for bridge events. Single source of truth — shared by watch registration, catch-up scan, and RPC endpoint validation.

Note: The old signature with 5 parameters it not supported as it was wrong.

variable kBridgeOutInitiatedSig

constexpr std::string_view kBridgeOutInitiatedSig =
        "BridgeOutInitiated(address,uint256,uint256,uint256,uint256,bytes32,bool)";

variable kDevMintPermittedNets

constexpr std::array< uint16_t, 2 > kDevMintPermittedNets { version::STAGING_NET_ID, version::DEV_NET_ID };

Nets where burn-less dev mints may certify through full consensus (D-03). Built from the named net-id constants — the only net literals.

variable NONCE_SUBJECT_TYPE

static constexpr std::string_view NONCE_SUBJECT_TYPE = "sgns.nonce.v1";

variable TASK_RESULT_SUBJECT_TYPE

static constexpr std::string_view TASK_RESULT_SUBJECT_TYPE = "sgns.task_result.v1";

variable REGISTRY_BATCH_SUBJECT_TYPE

static constexpr std::string_view REGISTRY_BATCH_SUBJECT_TYPE = "sgns.registry_batch.v1";

variable kCoinGeckoBaseUrlDefault

constexpr const char * kCoinGeckoBaseUrlDefault = "https://api.coingecko.com";

Production default base URL for tier 1 (CoinGecko direct). The client appends "/api/v3/simple/price".

variable kFallbackBaseUrlDefault

constexpr const char * kFallbackBaseUrlDefault = "https://token.gnus.ai";

Production default base URL for tier 2 (token.gnus.ai fallback). The client appends "/v1/prices".

variable kFreshMaxAge

constexpr std::chrono::seconds kFreshMaxAge { 60 };

Shared freshness band constants (D-16) consumed by code and tests.

variable kStaleMaxAge

constexpr std::chrono::seconds kStaleMaxAge { 300 };

variable FILE_NAME

constexpr std::string_view FILE_NAME = "secure_storage.json";

variable MAX_PUBSUB_TX_BYTES

static constexpr size_t MAX_PUBSUB_TX_BYTES = 64 * 1024;

Updated on 2026-10-23 at 16:46:17 +0000