explorer

package
v3.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 28, 2019 License: ISC Imports: 40 Imported by: 0

Documentation

Overview

package explorer handles the block explorer subsystem for generating the explorer pages.

Index

Constants

View Source
const (
	MaxAddressRows         int64 = 1000
	MaxUnconfirmedPossible int64 = 1000
)
View Source
const (
	ErrorStatusType          statusType = "Error"
	NotFoundStatusType       statusType = "Not Found"
	NotSupportedStatusType   statusType = "Not Supported"
	NotImplementedStatusType statusType = "Not Implemented"
	WrongNetworkStatusType   statusType = "Wrong Network"
	DeprecatedStatusType     statusType = "Deprecated"
	BlockchainSyncingType    statusType = "Blocks Syncing"
	P2PKAddresStatusType     statusType = "P2PK Address Type"
)
View Source
const NumLatestMempoolTxns = 5

NumLatestMempoolTxns is the maximum number of mempool transactions that will be stored in MempoolData.LatestTransactions.

Variables

View Source
var ErrWsClosed = "use of closed network connection"

ErrWsClosed is the error message text used websocket Conn.Close tries to close an already closed connection.

Functions

func AddressPathCtx

func AddressPathCtx(next http.Handler) http.Handler

AddressPathCtx embeds "address" into the request context

func AgendaPathCtx

func AgendaPathCtx(next http.Handler) http.Handler

AgendaPathCtx embeds "agendaid" into the request context

func ChartTypeData added in v3.1.0

func ChartTypeData(chartType string) (data *dbtypes.ChartsData, ok bool)

ChartTypeData is a thread-safe way to access chart data of the given type.

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.

func GetAgendaInfo

func GetAgendaInfo(agendaId string) (*agendadb.AgendaTagged, error)

GetAgendaInfo gets the all info for the specified agenda ID.

func New

func New(dataSource explorerDataSourceLite, primaryDataSource explorerDataSource,
	useRealIP bool, appVersion string, devPrefetch bool) *explorerUI

New returns an initialized instance of explorerUI

func SetSyncExplorerUpdateStatus added in v3.1.0

func SetSyncExplorerUpdateStatus(status bool)

SetSyncExplorerUpdateStatus is a thread-safe way to set when the explorer should be updated with the latest blocks synced.

func SyncExplorerUpdateStatus added in v3.1.0

func SyncExplorerUpdateStatus() bool

SyncExplorerUpdateStatus is thread-safe to check the current set explorer update status.

func TicketStatusText

func TicketStatusText(s dbtypes.TicketSpendType, p dbtypes.TicketPoolStatus) string

TicketStatusText generates the text to display on the explorer's transaction page for the "POOL STATUS" field.

func TransactionHashCtx

func TransactionHashCtx(next http.Handler) http.Handler

TransactionHashCtx embeds "txid" into the request context

func TransactionIoIndexCtx added in v3.1.0

func TransactionIoIndexCtx(next http.Handler) http.Handler

TransactionIoIndexCtx embeds "inout" and "inoutid" into the request context

func UseLogger

func UseLogger(logger slog.Logger)

UseLogger uses a specified Logger to output package logging info.

Types

type AddrPrefix

type AddrPrefix struct {
	Name        string
	Prefix      string
	Description string
}

AddrPrefix represent the address name it's prefix and description

func AddressPrefixes

func AddressPrefixes(params *chaincfg.Params) []AddrPrefix

AddressPrefixes generates an array AddrPrefix by using chaincfg.Params

type AddressBalance

type AddressBalance struct {
	Address        string `json:"address"`
	NumSpent       int64  `json:"num_stxos"`
	NumUnspent     int64  `json:"num_utxos"`
	TotalSpent     int64  `json:"amount_spent"`
	TotalUnspent   int64  `json:"amount_unspent"`
	NumMergedSpent int64  `json:"num_merged_spent,omitempty"`
}

AddressBalance represents the number and value of spent and unspent outputs for an address.

type AddressInfo

type AddressInfo struct {
	// Address is the decred address on the current page
	Address string

	// IsDummyAddress is true when the address is the dummy address typically
	// used for unspendable ticket change outputs. See
	// https://github.com/decred/dcrdata/v3/issues/358 for details.
	IsDummyAddress bool

	// Page parameters
	Fullmode      bool
	MaxTxLimit    int64
	Path          string
	Limit, Offset int64  // ?n=Limit&start=Offset
	TxnType       string // ?txntype=TxnType

	// NumUnconfirmed is the number of unconfirmed txns for the address
	NumUnconfirmed  int64
	UnconfirmedTxns *AddressTransactions

	// Transactions on the current page
	Transactions    []*AddressTx
	TxnsFunding     []*AddressTx
	TxnsSpending    []*AddressTx
	NumTransactions int64 // The number of transactions in the address
	NumFundingTxns  int64 // number paying to the address
	NumSpendingTxns int64 // number spending outpoints associated with the address
	AmountReceived  dcrutil.Amount
	AmountSent      dcrutil.Amount
	AmountUnspent   dcrutil.Amount

	// Balance is used in full mode, describing all known transactions
	Balance *AddressBalance

	// KnownTransactions refers to the total transaction count in the DB when in
	// full mode, the sum of funding (crediting) and spending (debiting) txns.
	KnownTransactions int64
	KnownFundingTxns  int64
	KnownSpendingTxns int64

	// KnownMergedSpendingTxns refers to the total count of unique debit transactions
	// that appear in the merged debit view.
	KnownMergedSpendingTxns int64
}

AddressInfo models data for display on the address page

func ReduceAddressHistory

func ReduceAddressHistory(addrHist []*dbtypes.AddressRow) *AddressInfo

ReduceAddressHistory generates a template AddressInfo from a slice of dbtypes.AddressRow. All fields except NumUnconfirmed and Transactions are set completely. Transactions is partially set, with each transaction having only the TxID and ReceivedTotal set. The rest of the data should be filled in by other means, such as RPC calls or database queries.

func (*AddressInfo) TxnCount

func (a *AddressInfo) TxnCount() int64

TxnCount returns the number of transaction "rows" available.

type AddressTransactions

type AddressTransactions struct {
	Transactions []*AddressTx
	TxnsFunding  []*AddressTx
	TxnsSpending []*AddressTx
}

AddressTransactions collects the transactions for an address as AddressTx slices.

type AddressTx

type AddressTx struct {
	TxID           string
	TxType         string
	InOutID        uint32
	Size           uint32
	FormattedSize  string
	Total          float64
	Confirmations  uint64
	Time           int64
	FormattedTime  string
	ReceivedTotal  float64
	SentTotal      float64
	IsFunding      bool
	MatchedTx      string
	MatchedTxIndex uint32
	BlockTime      uint64
	MergedTxnCount uint64 `json:",omitempty"`
}

AddressTx models data for transactions on the address page

func (*AddressTx) IOID

func (a *AddressTx) IOID(txType ...string) string

IOID formats an identification string for the transaction input (or output) represented by the AddressTx.

type BlockBasic

type BlockBasic struct {
	Height         int64  `json:"height"`
	Hash           string `json:"hash"`
	Size           int32  `json:"size"`
	Valid          bool   `json:"valid"`
	MainChain      bool   `json:"mainchain"`
	Voters         uint16 `json:"votes"`
	Transactions   int    `json:"tx"`
	WindowIndx     int64  `json:"windowIndex"`
	FreshStake     uint8  `json:"tickets"`
	Revocations    uint32 `json:"revocations"`
	BlockTime      int64  `json:"time"`
	FormattedTime  string `json:"formatted_time"`
	FormattedBytes string `json:"formatted_bytes"`
}

BlockBasic models data for the explorer's explorer page

type BlockInfo

type BlockInfo struct {
	*BlockBasic
	Version               int32
	Confirmations         int64
	StakeRoot             string
	MerkleRoot            string
	TxAvailable           bool
	Tx                    []*TrimmedTxInfo
	Tickets               []*TrimmedTxInfo
	Revs                  []*TrimmedTxInfo
	Votes                 []*TrimmedTxInfo
	Misses                []string
	Nonce                 uint32
	VoteBits              uint16
	FinalState            string
	PoolSize              uint32
	Bits                  string
	SBits                 float64
	Difficulty            float64
	ExtraData             string
	StakeVersion          uint32
	PreviousHash          string
	NextHash              string
	TotalSent             float64
	MiningFee             float64
	StakeValidationHeight int64
	AllTxs                uint32
	Subsidy               *dcrjson.GetBlockSubsidyResult
}

BlockInfo models data for display on the block page

type BlockSubsidy

type BlockSubsidy struct {
	Total int64 `json:"total"`
	PoW   int64 `json:"pow"`
	PoS   int64 `json:"pos"`
	Dev   int64 `json:"dev"`
}

BlockSubsidy is an implementation of dcrjson.GetBlockSubsidyResult

type BlockValidation

type BlockValidation struct {
	Hash     string `json:"hash"`
	Height   int64  `json:"height"`
	Validity bool   `json:"validity"`
}

BlockValidation models data about a vote's decision on a block

func (*BlockValidation) ForBlock

func (v *BlockValidation) ForBlock(blockHash string) bool

ForBlock indicates if the validation choice is for the specified block.

type BlockValidatorIndex

type BlockValidatorIndex map[string]TicketIndex

BlockValidatorIndex keeps a list of arbitrary indexes for unique combinations of block hash and the ticket being spent to validate the block, i.e. map[validatedBlockHash]map[ticketHash]index.

type ChainParams

type ChainParams struct {
	WindowSize       int64 `json:"window_size"`
	RewardWindowSize int64 `json:"reward_window_size"`
	TargetPoolSize   int64 `json:"target_pool_size"`
	BlockTime        int64 `json:"target_block_time"`
	MeanVotingBlocks int64
}

ChainParams models simple data about the chain server's parameters used for some info on the front page.

type ExtendedChainParams

type ExtendedChainParams struct {
	Params               *chaincfg.Params
	MaximumBlockSize     int
	ActualTicketPoolSize int64
	AddressPrefix        []AddrPrefix
}

ExtendedChainParams represents the data of ChainParams

type HomeInfo

type HomeInfo struct {
	CoinSupply            int64          `json:"coin_supply"`
	StakeDiff             float64        `json:"sdiff"`
	NextExpectedStakeDiff float64        `json:"next_expected_sdiff"`
	NextExpectedBoundsMin float64        `json:"next_expected_min"`
	NextExpectedBoundsMax float64        `json:"next_expected_max"`
	IdxBlockInWindow      int            `json:"window_idx"`
	IdxInRewardWindow     int            `json:"reward_idx"`
	Difficulty            float64        `json:"difficulty"`
	DevFund               int64          `json:"dev_fund"`
	DevAddress            string         `json:"dev_address"`
	TicketReward          float64        `json:"reward"`
	RewardPeriod          string         `json:"reward_period"`
	ASR                   float64        `json:"ASR"`
	NBlockSubsidy         BlockSubsidy   `json:"subsidy"`
	Params                ChainParams    `json:"params"`
	PoolInfo              TicketPoolInfo `json:"pool_info"`
	TotalLockedDCR        float64        `json:"total_locked_dcr"`
	HashRate              float64        `json:"hash_rate"`
	// HashRateChange defines the hashrate change in 24hrs
	HashRateChange float64 `json:"hash_rate_change"`
}

HomeInfo represents data used for the home page

type MempoolInfo

type MempoolInfo struct {
	sync.RWMutex
	MempoolShort
	Transactions []MempoolTx `json:"tx"`
	Tickets      []MempoolTx `json:"tickets"`
	Votes        []MempoolTx `json:"votes"`
	Revocations  []MempoolTx `json:"revs"`
}

MempoolInfo models data to update mempool info on the home page

type MempoolShort

type MempoolShort struct {
	LastBlockHeight    int64               `json:"block_height"`
	LastBlockHash      string              `json:"block_hash"`
	LastBlockTime      int64               `json:"block_time"`
	TotalOut           float64             `json:"total"`
	TotalSize          int32               `json:"size"`
	NumTickets         int                 `json:"num_tickets"`
	NumVotes           int                 `json:"num_votes"`
	NumRegular         int                 `json:"num_regular"`
	NumRevokes         int                 `json:"num_revokes"`
	NumAll             int                 `json:"num_all"`
	LatestTransactions []MempoolTx         `json:"latest"`
	FormattedTotalSize string              `json:"formatted_size"`
	TicketIndexes      BlockValidatorIndex `json:"-"`
	VotingInfo         VotingInfo          `json:"voting_info"`
	InvRegular         map[string]struct{} `json:"-"`
	InvStake           map[string]struct{} `json:"-"`
}

MempoolShort represents the mempool data sent as the mempool update

type MempoolTx

type MempoolTx struct {
	TxID      string    `json:"txid"`
	Fees      float64   `json:"fees"`
	VinCount  int       `json:"vin_count"`
	VoutCount int       `json:"vout_count"`
	Coinbase  bool      `json:"coinbase"`
	Hash      string    `json:"hash"`
	Time      int64     `json:"time"`
	Size      int32     `json:"size"`
	TotalOut  float64   `json:"total"`
	Type      string    `json:"Type"`
	VoteInfo  *VoteInfo `json:"vote_info,omitempty"`
}

MempoolTx models the tx basic data for the mempool page

type NewMempoolTx

type NewMempoolTx struct {
	Time int64
	Hex  string
}

NewMempoolTx models data sent from the notification handler

type SyncStatusInfo added in v3.1.0

type SyncStatusInfo struct {
	// PercentComplete is the percentage of sync complete for a given progress bar.
	PercentComplete float64 `json:"percentage_complete"`
	// BarMsg holds the main bar message about the currect sync.
	BarMsg string `json:"bar_msg"`
	// BarSubtitle holds any other information about the current main sync. This
	// value may include but not limited to; db indexing, deleting duplicates etc.
	BarSubtitle string `json:"subtitle"`
	// Time is the estimated time in seconds to the sync should be complete.
	Time int64 `json:"seconds_to_complete"`
	// ProgressBarID is the given entry progress bar id needed on the UI page.
	ProgressBarID string `json:"progress_bar_id"`
}

SyncStatusInfo defines information for a single progress bar.

func SyncStatus added in v3.1.0

func SyncStatus() []SyncStatusInfo

SyncStatus defines a thread-safe way to read the sync status updates

type TicketIndex

type TicketIndex map[string]int

TicketIndex is used to assign an index to a ticket hash.

type TicketInfo

type TicketInfo struct {
	TicketMaturity       int64
	TimeTillMaturity     float64 // Time before a particular ticket reaches maturity, in hours
	PoolStatus           string
	SpendStatus          string
	TicketPoolSize       int64   // Total number of ticket in the pool
	TicketExpiry         int64   // Total number of blocks before a ticket expires
	TicketExpiryDaysLeft float64 // Approximate days left before the given ticket expires
	TicketLiveBlocks     int64   // Total number of confirms after maturity and up until the point the ticket votes or expires
	BestLuck             int64   // Best possible Luck for voting
	AvgLuck              int64   // Average Luck for voting
	VoteLuck             float64 // Actual Luck for voting on a ticket
	LuckStatus           string  // Short discription based on the VoteLuck
	Probability          float64 // Probability of success before ticket expires
}

TicketInfo is used to represent data shown for a sstx transaction.

type TicketPoolInfo

type TicketPoolInfo struct {
	Size          uint32  `json:"size"`
	Value         float64 `json:"value"`
	ValAvg        float64 `json:"valavg"`
	Percentage    float64 `json:"percent"`
	Target        uint16  `json:"target"`
	PercentTarget float64 `json:"percent_target"`
}

TicketPoolInfo describes the live ticket pool

type TrimmedBlockInfo added in v3.1.0

type TrimmedBlockInfo struct {
	Time         int64
	Height       int64
	Total        float64
	Fees         float64
	Subsidy      *dcrjson.GetBlockSubsidyResult
	Votes        []*TrimmedTxInfo
	Tickets      []*TrimmedTxInfo
	Revocations  []*TrimmedTxInfo
	Transactions []*TrimmedTxInfo
}

TrimmedBlockInfo models data needed to display block info on the new home page

type TrimmedMempoolInfo added in v3.1.0

type TrimmedMempoolInfo struct {
	Transactions []*TrimmedTxInfo
	Tickets      []*TrimmedTxInfo
	Votes        []*TrimmedTxInfo
	Revocations  []*TrimmedTxInfo
	Subsidy      BlockSubsidy
	Total        float64
	Time         int64
	Fees         float64
}

TrimmedMempoolInfo models data needed to display mempool info on the new home page

type TrimmedTxInfo added in v3.1.0

type TrimmedTxInfo struct {
	*TxBasic
	Fees      float64
	VinCount  int
	VoutCount int
	VoteValid bool
}

TrimmedTxInfo for use with /nexthome

type TxBasic

type TxBasic struct {
	TxID          string
	FormattedSize string
	Total         float64
	Fee           dcrutil.Amount
	FeeRate       dcrutil.Amount
	VoteInfo      *VoteInfo
	Coinbase      bool
}

TxBasic models data for transactions on the block page

type TxInID

type TxInID struct {
	Hash  string
	Index uint32
}

TxInID models the identity of a spending transaction input

type TxInfo

type TxInfo struct {
	*TxBasic
	SpendingTxns     []TxInID
	Type             string
	Vin              []Vin
	Vout             []Vout
	BlockHeight      int64
	BlockIndex       uint32
	BlockHash        string
	BlockMiningFee   int64
	Confirmations    int64
	Time             int64
	FormattedTime    string
	Mature           string
	VoteFundsLocked  string
	Maturity         int64   // Total number of blocks before mature
	MaturityTimeTill float64 // Time in hours until mature
	TicketInfo
}

TxInfo models data needed for display on the tx page

func (*TxInfo) IsTicket

func (t *TxInfo) IsTicket() bool

func (*TxInfo) IsVote

func (t *TxInfo) IsVote() bool

type Vin

type Vin struct {
	*dcrjson.Vin
	Addresses       []string
	FormattedAmount string
	Index           uint32
}

Vin models basic data about a tx input for display

type VoteInfo

type VoteInfo struct {
	Validation         BlockValidation         `json:"block_validation"`
	Version            uint32                  `json:"vote_version"`
	Bits               uint16                  `json:"vote_bits"`
	Choices            []*txhelpers.VoteChoice `json:"vote_choices"`
	TicketSpent        string                  `json:"ticket_spent"`
	MempoolTicketIndex int                     `json:"mempool_ticket_index"`
	ForLastBlock       bool                    `json:"last_block"`
}

VoteInfo models data about a SSGen transaction (vote)

func (*VoteInfo) VotesOnBlock

func (v *VoteInfo) VotesOnBlock(blockHash string) bool

VotesOnBlock indicates if the vote is voting on the validity of block specified by the given hash.

type VotingInfo

type VotingInfo struct {
	TicketsVoted     uint16 `json:"tickets_voted"`
	MaxVotesPerBlock uint16 `json:"max_votes_per_block"`
	// contains filtered or unexported fields
}

VotingInfo models data about the validity of the next block from mempool.

type Vout

type Vout struct {
	Addresses       []string
	Amount          float64
	FormattedAmount string
	Type            string
	Spent           bool
	OP_RETURN       string
	Index           uint32
}

Vout models basic data about a tx output for display

type WebSocketMessage

type WebSocketMessage struct {
	EventId string `json:"event"`
	Message string `json:"message"`
}

WebSocketMessage represents the JSON object used to send and received typed messages to the web client.

type WebsocketBlock

type WebsocketBlock struct {
	Block *BlockInfo `json:"block"`
	Extra *HomeInfo  `json:"extra"`
}

WebsocketBlock wraps the new block info for use in the websocket

type WebsocketHub

type WebsocketHub struct {
	Register   chan *clientHubSpoke
	Unregister chan *hubSpoke
	HubRelay   chan hubSignal
	NewTxChan  chan *MempoolTx
	// contains filtered or unexported fields
}

WebsocketHub and its event loop manage all websocket client connections. WebsocketHub is responsible for closing all connections registered with it. If the event loop is running, calling (*WebsocketHub).Stop() will handle it.

func NewWebsocketHub

func NewWebsocketHub() *WebsocketHub

NewWebsocketHub creates a new WebsocketHub

func (*WebsocketHub) MaybeSendTxns

func (wsh *WebsocketHub) MaybeSendTxns(tx *MempoolTx)

MaybeSendTxns adds a mempool transaction to the client broadcast buffer. If the buffer is at capacity, a goroutine is launched to signal for the transactions to be sent to the clients.

func (*WebsocketHub) NumClients

func (wsh *WebsocketHub) NumClients() int

NumClients returns the number of clients connected to the websocket hub

func (*WebsocketHub) RegisterClient

func (wsh *WebsocketHub) RegisterClient(c *hubSpoke) *client

RegisterClient registers a websocket connection with the hub, and returns a pointer to the new client data object.

func (*WebsocketHub) Stop

func (wsh *WebsocketHub) Stop()

Stop kills the run() loop and unregisteres all clients (connections).

func (*WebsocketHub) UnregisterClient

func (wsh *WebsocketHub) UnregisterClient(c *hubSpoke)

UnregisterClient unregisters the input websocket connection via the main run() loop. This call will block if the run() loop is not running.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL