pegnet

package
v0.0.0-...-4a3476f Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2020 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// BankBaseAmount is the minimum the bank size will ever be.
	// Any bank growth will be ontop of this value.
	BankBaseAmount = conversions.PerBlock
)
View Source
const (
	DefaultPad = 1
)
View Source
const (
	// Prefix for pAsset prices on exchanges reported by miners
	PAssetExchangePrefix = "exch_"
)
View Source
const QueryLimit = 50

QueryLimit is the amount of transactions to return in one query

View Source
const (
	// SnapshotRate is how often snapshots are taken and paid out on a block basis
	SnapshotRate = 144 // Default is 144, once a day
)

Variables

View Source
var (
	InsufficientBalanceErr          = errors.New("insufficient balance")
	InsufficientBalanceErrInt int64 = -1

	PFCTOneWayError          = errors.New("pFCT conversions are one way only at this height, they cannot be a conversion destination")
	PFCTOneWayErrorInt int64 = -3
	ZeroRatesError           = errors.New("an asset in the conversion has a rate of 0, and not allowed to be used for conversions")
	ZeroRatesErrorInt  int64 = -4
)
View Source
var (
	Hardforks = []ForkEvent{

		{0, -1},

		{ActivationHeight: 231620, MinimumVersion: 1},

		{ActivationHeight: 258796, MinimumVersion: 2},
	}
)
View Source
var (
	// PegnetdSyncVersion is an indicator of the version of pegnetd
	// at each height synced. This version number can differ from the tagged
	// version, and is likely only to be updated at hard forks. It is used to
	// detect if a pegnetd was updated late, and therefore has an invalid state.
	//
	// Each fork should increment this number by at least 1
	PegnetdSyncVersion = 2
)

Functions

func FormatTxID

func FormatTxID(index int, hash string) string

FormatTxID constructs a txid from an entryhash and its index

func FormatTxIDWithPad

func FormatTxIDWithPad(pad, index int, hash string) string

FormatTxIDWithPad constructs a txid from an entryhash and its index. It will pad the index such that it is of at least 'pad' characters in lenght. pad = 2 -> 01-entryhash pad = 3 -> 001-entryhash

func IsRejectedTx

func IsRejectedTx(err error) (int64, error)

IsRejectedTx takes an error, and returns the integer form of that error if it is a rejected tx. If the error is unknown, the original error is returned.

func SplitTxID

func SplitTxID(txid string) (index int, batchHash string, err error)

SplitTxID splits a TxID into it's parts. TxID format : [TxIndex]-[BatchHash]

1-c99dedea0e4e0c40118fe7e4d515b23cc0489269c8cef187b4f15a4ccbd880be

func VerifyTransactionHash

func VerifyTransactionHash(hash string) (index int, batchHash string, err error)

VerifyTransactionHash checks if a given hash or txid is valid. There are 2 types of transaction hashes:

  • batches, 64 hex characters indicates a batch of transactions. All burns and coinbases are considered batches of length 1.
  • txid, [TxIndex]-[BatchHash] indicates a single transaction in a batch.

All hashes in pure hash format (64 hex characters) will return an index of -1, meaning the hash indicates a batch of transactions.

All hashes in txid format, [TxIndex]-[BatchHash] will return an index number >= 0.

Types

type BalancePair

type BalancePair struct {
	Address *factom.FAAddress
	Balance uint64
}

type BalancesPair

type BalancesPair struct {
	Address  *factom.FAAddress
	Balances []uint64
}

type BankEntry

type BankEntry struct {
	// Each height will have a bank entry.
	Height int32
	// BankAmount is the total amount of PEG allowed to be converted into
	// for the given height.
	BankAmount int64 // units are PEGtoshi
	// BankUsed is some additional information to detail how much of the bank
	// was consumed.
	BankUsed int64 // units are PEGtoshi
	// PEGRequested is the total amount of PEG requested
	PEGRequested int64 // units are PEGtoshi
}

BankEntry is for managing the PEG Bank. The bank is the amount of PEG allowed to be converted into every block. This table should be used for bank management purposes.

The bank has the following data structure at each height. It can be used to control the amount of PEG allowed to be converted into at each pegnet block.

There is extra information provided for informational purposes. The only true value needed here is likely the BankAmount and possible the BankUsed. The PEGRequested shows the demand for PEG at a high level.

type BlockSync

type BlockSync struct {
	Synced uint32
}

type ForkEvent

type ForkEvent struct {
	ActivationHeight uint32
	MinimumVersion   int
}

type Graded

type Graded struct {
	EntryHash  string `json:"entryhash"`
	Payout     uint64 `json:"payout"`
	Nonce      string `json:"nonce"`
	Difficulty uint64 `json:"difficulty"`
	Position   uint8  `json:"position"`
	MinerID    string `json:"minerid"`
	Address    string `json:"address"`
}

type GradedResult

type GradedResult struct {
	Height int32    `json:"height"`
	Graded []Graded `json:"graded"`
}

type HistoryAction

type HistoryAction int32

HistoryAction are the different types of actions inside the history

const (
	// Invalid is used for debugging
	Invalid HistoryAction = iota
	// Transfer is a 1:n transfer of pegged assets from one address to another
	Transfer
	// Conversion is a conversion of pegged assets
	Conversion
	// Coinbase is a miner reward payout
	Coinbase
	// FCTBurn is a pFCT payout for burning FCT on factom
	FCTBurn
)

type HistoryQueryOptions

type HistoryQueryOptions struct {
	Offset     int
	Desc       bool
	Transfer   bool
	Conversion bool
	Coinbase   bool
	FCTBurn    bool
	Asset      string

	// UseTxIndex is set if specifying a specific tx in the batch.
	// Because 0 is a valid tx index, we want the uninitialized value
	// to be "off"
	UseTxIndex bool
	TxIndex    int
}

HistoryQueryOptions contains the data of what to query for the query builder

type HistoryTransaction

type HistoryTransaction struct {
	Hash      *factom.Bytes32 `json:"hash"`
	TxID      string          `json:"txid"` // [TxIndex]-[BatchHash]
	Height    int64           `json:"height"`
	Timestamp time.Time       `json:"timestamp"`
	Executed  int32           `json:"executed"`
	TxIndex   int             `json:"txindex"`
	TxAction  HistoryAction   `json:"txaction"`

	FromAddress *factom.FAAddress          `json:"fromaddress"`
	FromAsset   string                     `json:"fromasset"`
	FromAmount  int64                      `json:"fromamount"`
	ToAsset     string                     `json:"toasset,omitempty"`
	ToAmount    int64                      `json:"toamount,omitempty"`
	Outputs     []HistoryTransactionOutput `json:"outputs,omitempty"`
}

HistoryTransaction is a flattened entry of the history table structure. It contains several actions: transfers, conversions, coinbases, and fct burns

type HistoryTransactionOutput

type HistoryTransactionOutput struct {
	Address factom.FAAddress `json:"address"`
	Amount  int64            `json:"amount"`
}

HistoryTransactionOutput is an entry of a transfer's outputs

type MinerDominance

type MinerDominance struct {
	Identities       []string `json:"identities"`
	TotalWins        int32    `json:"totalwins"`
	TotalGraded      int32    `json:"totalgraded"`
	WinPercentage    float64  `json:"winpercent"`
	GradedPercentage float64  `json:"gradedpercent"`
}

type MinerDominanceResult

type MinerDominanceResult struct {
	Start       int `json:"startheight"`
	Stop        int `json:"stopheight"`
	Miners      map[string]MinerDominance
	TotalWins   int32 `json:"totalwins"`
	TotalGraded int32 `json:"totalgraded"`
}

type PEGPricingPhase

type PEGPricingPhase int
const (
	PEGPriceIsZero     PEGPricingPhase // PEG == 0
	PEGPriceIsEquation                 // PEG == MarketCap / Peg Supply
	PEGPriceIsFloating                 // PEG == ExchRate
)

type Pegnet

type Pegnet struct {
	Config *viper.Viper

	// This is the sqlite db to store state
	DB *sql.DB
}

func New

func New(conf *viper.Viper) *Pegnet

func (*Pegnet) AddToBalance

func (p *Pegnet) AddToBalance(tx *sql.Tx, adr *factom.FAAddress, ticker fat2.PTicker, value uint64) (int64, error)

AddToBalance adds value to the typed balance of adr, creating a new row in "pn_addresses" if it does not exist. If successful, the row id is returned.

func (Pegnet) CheckHardForks

func (p Pegnet) CheckHardForks(tx QueryAble) error

CheckHardForks will iterate over all the hardforks post the version_lock update, and verify the version that was used to sync was appropriate.

func (*Pegnet) CreateTableAddresses

func (p *Pegnet) CreateTableAddresses() error

func (*Pegnet) CreateTableBank

func (p *Pegnet) CreateTableBank() error

CreateTableBank is used to expose this table for unit tests

func (*Pegnet) CreateTableSyncVersion

func (p *Pegnet) CreateTableSyncVersion() error

CreateTableSyncVersion is used to expose this table for unit tests

func (*Pegnet) DoesTransactionExist

func (p *Pegnet) DoesTransactionExist(entryhash factom.Bytes32) (bool, error)

func (Pegnet) FetchMaxSyncedVersion

func (Pegnet) FetchMaxSyncedVersion(tx QueryAble, height uint32) (int, error)

FetchMaxSyncedVersion returns -1, nil if the height was not found

func (Pegnet) FetchMinSyncedVersion

func (Pegnet) FetchMinSyncedVersion(tx QueryAble, height uint32) (int, error)

FetchMinSyncedVersion returns -1, nil if the height was not found

func (Pegnet) HighestSynced

func (p Pegnet) HighestSynced(tx QueryAble) (uint32, error)

func (*Pegnet) Init

func (p *Pegnet) Init() error

func (Pegnet) InsertBankAmount

func (p Pegnet) InsertBankAmount(q QueryAble, height int32, bankAmount int64) error

InsertBankAmount does not fill in the bank_used and total_requested with legit values. It leaves a -1 to indicate that needs to be filled.

func (*Pegnet) InsertCoinbase

func (p *Pegnet) InsertCoinbase(tx *sql.Tx, winner *grader.GradingOPR, addr []byte, timestamp time.Time) error

InsertCoinbase inserts the payouts from mining into the history system. There is one transaction per winning OPR, with the entry hash pointing to that specific opr

func (*Pegnet) InsertDeveloperRewardCoinbase

func (p *Pegnet) InsertDeveloperRewardCoinbase(tx *sql.Tx, txid string, addTxid string, height uint32, heightTimestamp time.Time, payout uint64, faAdd factom.FAAddress) error

func (*Pegnet) InsertFCTBurn

func (p *Pegnet) InsertFCTBurn(tx *sql.Tx, fBlockHash *factom.Bytes32, burn factom.FactoidTransaction, height uint32) error

InsertFCTBurn inserts a payout for an FCT burn into the system. Note that from_asset and to_asset are hardcoded

func (*Pegnet) InsertGradeBlock

func (p *Pegnet) InsertGradeBlock(tx *sql.Tx, eblock *factom.EBlock, graded grader.GradedBlock) error

func (*Pegnet) InsertRates

func (p *Pegnet) InsertRates(tx *sql.Tx, height uint32, rates []opr.AssetUint, phase PEGPricingPhase) error

InsertRates adds all asset rates as rows, computing the rate for PEG if necessary

func (*Pegnet) InsertStaking100Coinbase

func (p *Pegnet) InsertStaking100Coinbase(tx *sql.Tx, winner *graderStake.GradingSPR, addr []byte, timestamp time.Time) error

InsertCoinbase inserts the payouts from staking into the history system. There is one transaction per winning SPR, with the entry hash pointing to that specific spr

func (*Pegnet) InsertStakingCoinbase

func (p *Pegnet) InsertStakingCoinbase(tx *sql.Tx, txid string, height uint32, heightTimestamp time.Time, payouts map[string]uint64, addressMap map[string]factom.FAAddress) error

InsertStakingCoinbase inserts the payouts from mining into the history system. There is one transaction per winning OPR, with the entry hash pointing to that specific opr

func (*Pegnet) InsertStats

func (p *Pegnet) InsertStats(tx *sql.Tx, stats *Stats) error

func (*Pegnet) InsertSynced

func (p *Pegnet) InsertSynced(tx *sql.Tx, bs *BlockSync) error

func (*Pegnet) InsertTransactionBatchHolding

func (p *Pegnet) InsertTransactionBatchHolding(tx *sql.Tx, txBatch *fat2.TransactionBatch, height uint64, eblockKeyMR *factom.Bytes32) (int64, error)

InsertTransactionBatchHolding inserts a row into "pn_transaction_batch_holding" that stores the entry data at its entry hash, along with the contextual information of the block height and eblock_keymr. If successful, the row id for the new row in "pn_transaction_batch_holding" is returned.

Note: It is assumed that the entry stored has already been validated as a fat2 transaction batch that contains at least one conversion. It is only put into holding to be executed against future asset exchange rates.

func (*Pegnet) InsertTransactionHistoryTxBatch

func (p *Pegnet) InsertTransactionHistoryTxBatch(tx *sql.Tx, blockorder int, txbatch *fat2.TransactionBatch, height uint32) error

InsertTransactionHistoryTxBatch inserts a transaction from the transaction chain into the history system

func (*Pegnet) InsertTransactionRelation

func (p *Pegnet) InsertTransactionRelation(tx *sql.Tx, adr factom.FAAddress, entryHash *factom.Bytes32, txIndex uint64, to bool, isConversion bool) (int64, error)

InsertTransactionRelation inserts a row into "pnaddress_transactions" relating the adrID with the entryHash with the given transaction direction, to. If successful, the row id for the new row in "pn_address_transactions" is returned.

If isConversion is true, the to field will automatically be set to true.

func (*Pegnet) InsertZeroingCoinbase

func (p *Pegnet) InsertZeroingCoinbase(tx *sql.Tx, txid string, addTxid string, height uint32, heightTimestamp time.Time, payout uint64, asset string, faAdd factom.FAAddress) error

Special construction to nullify burn address

func (*Pegnet) IsIncludedTopPEGAddress

func (p *Pegnet) IsIncludedTopPEGAddress(address []byte) bool

func (*Pegnet) IsReplayTransaction

func (p *Pegnet) IsReplayTransaction(tx *sql.Tx, entryHash *factom.Bytes32) (bool, error)

IsReplayTransaction returns true if there exist any transaction relations in the "pn_address_transactions" table.

func (Pegnet) LowestSynced

func (p Pegnet) LowestSynced(tx QueryAble) (uint32, error)

func (Pegnet) MarkHeightSynced

func (p Pegnet) MarkHeightSynced(tx QueryAble, height uint32) error

func (*Pegnet) SelectAllBalances

func (p *Pegnet) SelectAllBalances() ([]BalancesPair, error)

SelectPendingBalances returns a map of all valid PTickers and their associated balances for the given address. If the address is not in the database, the map will contain 0 for all valid PTickers. This works on the pending tx

func (*Pegnet) SelectBalance

func (p *Pegnet) SelectBalance(adr *factom.FAAddress, ticker fat2.PTicker) (uint64, error)

SelectBalance returns the balance of an individual token type for the given address. If the address is not in the database, 0 will be returned.

func (*Pegnet) SelectBalances

func (p *Pegnet) SelectBalances(adr *factom.FAAddress) (map[fat2.PTicker]uint64, error)

SelectBalances returns a map of all valid PTickers and their associated balances for the given address. If the address is not in the database, the map will contain 0 for all valid PTickers.

func (Pegnet) SelectBankEntry

func (p Pegnet) SelectBankEntry(q QueryAble, height int32) (entry BankEntry, err error)

func (*Pegnet) SelectGraded

func (p *Pegnet) SelectGraded(ctx context.Context, height int32) (GradedResult, error)

func (*Pegnet) SelectIssuances

func (p *Pegnet) SelectIssuances() (map[fat2.PTicker]uint64, error)

func (*Pegnet) SelectMinerDominance

func (p *Pegnet) SelectMinerDominance(ctx context.Context, start, stop int) (MinerDominanceResult, error)

SelectMinerDominance returns information around which miners are winning PEG and being graded in a block range Params are the start and stop block height. The stop height is inclusive.

func (*Pegnet) SelectMostRecentRatesBeforeHeight

func (p *Pegnet) SelectMostRecentRatesBeforeHeight(ctx context.Context, tx QueryAble, height uint32) (map[fat2.PTicker]uint64, uint32, error)

func (*Pegnet) SelectPendingBalance

func (p *Pegnet) SelectPendingBalance(tx *sql.Tx, adr *factom.FAAddress, ticker fat2.PTicker) (uint64, error)

SelectPendingBalance returns the balance of an individual token type for the given address, in the context of a given sql transaction. If the address is not in the database or will not be in the database after the tx is committed, 0 will be returned.

func (*Pegnet) SelectPendingBalances

func (p *Pegnet) SelectPendingBalances(tx *sql.Tx, adr *factom.FAAddress) (map[fat2.PTicker]uint64, error)

SelectPendingBalances returns a map of all valid PTickers and their associated balances for the given address. If the address is not in the database, the map will contain 0 for all valid PTickers. This works on the pending tx

func (*Pegnet) SelectPendingRates

func (p *Pegnet) SelectPendingRates(ctx context.Context, tx *sql.Tx, height uint32) (map[fat2.PTicker]uint64, error)

func (*Pegnet) SelectPrevStats

func (p *Pegnet) SelectPrevStats(tx *sql.Tx, height uint32) (*Stats, error)

func (*Pegnet) SelectPreviousWinners

func (p *Pegnet) SelectPreviousWinners(ctx context.Context, height uint32) ([]string, error)

func (*Pegnet) SelectRates

func (p *Pegnet) SelectRates(ctx context.Context, height uint32) (map[fat2.PTicker]uint64, error)

func (*Pegnet) SelectRatesByKeyMR

func (p *Pegnet) SelectRatesByKeyMR(ctx context.Context, keymr *factom.Bytes32) (map[fat2.PTicker]uint64, error)

func (*Pegnet) SelectRecentRates

func (p *Pegnet) SelectRecentRates(ctx context.Context, height uint32) (map[string]uint64, error)

func (*Pegnet) SelectReferenceRates

func (p *Pegnet) SelectReferenceRates(ctx context.Context, tx QueryAble, height uint32) (map[fat2.PTicker]uint64, error)

SelectReferenceRates returns the pAsset rates on the external market that are reported by the miners.

So pUSD == $1, but the Reference token (pUSD) can be trading at $0.90 This rate call will return $0.90

func (*Pegnet) SelectRichList

func (p *Pegnet) SelectRichList(ticker fat2.PTicker, count int) ([]BalancePair, error)

SelectRichList returns the balance of all addresses for a given ticker

func (Pegnet) SelectSnapshotBalances

func (Pegnet) SelectSnapshotBalances(tx QueryAble) ([]BalancesPair, error)

SelectSnapshotBalances returns a map of all valid PTickers and their associated snapshot balances for the given address. The snapshot balance is the minimum of the past, and current snapshot. You must provide the table to query on

func (*Pegnet) SelectStats

func (p *Pegnet) SelectStats(ctx context.Context, height uint32) (*Stats, error)

func (Pegnet) SelectSynced

func (Pegnet) SelectSynced(ctx context.Context, tx QueryAble) (*BlockSync, error)

func (*Pegnet) SelectTransactionBatchesInHoldingAtHeight

func (p *Pegnet) SelectTransactionBatchesInHoldingAtHeight(height uint64) ([]*fat2.TransactionBatch, error)

SelectTransactionBatchesInHoldingAtHeight selects all fat2.TransactionBatch entries that are in holding at the given height. It should be assumed that a TransactionBatch in the database has already returned nil for TransactionBatch.Validate() and also that TransactionBatch.HasConversions() returns true.

func (*Pegnet) SelectTransactionHistoryActionsByAddress

func (p *Pegnet) SelectTransactionHistoryActionsByAddress(addr *factom.FAAddress, options HistoryQueryOptions) ([]HistoryTransaction, int, error)

SelectTransactionHistoryActionsByAddress uses the lookup table to retrieve all transactions that have the specified address in either inputs or outputs

func (*Pegnet) SelectTransactionHistoryActionsByHash

func (p *Pegnet) SelectTransactionHistoryActionsByHash(hash *factom.Bytes32, options HistoryQueryOptions) ([]HistoryTransaction, int, error)

SelectTransactionHistoryActionsByHash returns the specified amount of transactions based on the hash. Hash can be an entry hash from the opr and transaction chains, or a transaction hash from an fblock.

func (*Pegnet) SelectTransactionHistoryActionsByHeight

func (p *Pegnet) SelectTransactionHistoryActionsByHeight(height uint32, options HistoryQueryOptions) ([]HistoryTransaction, int, error)

SelectTransactionHistoryActionsByHeight returns all transactions that were **entered** at the specified height.

func (*Pegnet) SelectTransactionHistoryActionsByTxID

func (p *Pegnet) SelectTransactionHistoryActionsByTxID(hash *factom.Bytes32, options HistoryQueryOptions) ([]HistoryTransaction, int, error)

SelectTransactionHistoryActionsByTxID uses the lookup table to retrieve all transactions that have the specified txid. A TxID is an entryhash + a transaction index

func (*Pegnet) SelectTransactionHistoryStatus

func (p *Pegnet) SelectTransactionHistoryStatus(hash *factom.Bytes32) (uint32, int32, error)

SelectTransactionHistoryStatus returns the status of a transaction: `-1` for a failed transaction, `0` for a pending transactions, `height` for the block in which it was applied otherwise

func (*Pegnet) SetTransactionHistoryConvertedAmount

func (p *Pegnet) SetTransactionHistoryConvertedAmount(tx *sql.Tx, txbatch *fat2.TransactionBatch, index int, amount int64) error

SetTransactionHistoryConvertedAmount updates a conversion with the actual conversion value. This is done in the same SQL Transaction as updating its executed status

func (*Pegnet) SetTransactionHistoryExecuted

func (p *Pegnet) SetTransactionHistoryExecuted(tx *sql.Tx, txbatch *fat2.TransactionBatch, executed int64) error

SetTransactionHistoryExecuted updates a transaction's executed status

func (*Pegnet) SetTransactionHistoryPEGConvertedRequestAmount

func (p *Pegnet) SetTransactionHistoryPEGConvertedRequestAmount(tx *sql.Tx, txbatch *fat2.TransactionBatch, index int, pegAmount, refundAmount int64) error

SetTransactionHistoryPEGConvertedRequestAmount updates a peg conversion request with the actual amount of PEG received and the refund amount. The refund amount will appear as an output. This is done in the same SQL Transaction as updating its executed status

func (*Pegnet) SnapshotCurrent

func (p *Pegnet) SnapshotCurrent(tx QueryAble) error

SnapshotCurrent moves the current snapshot to the past, and updates the current snapshot. 1. Clear snapshot_past 2. Save snapshot_current to past 3. Delete snapshot_current 4. Save current balances to snapshot_current

func (*Pegnet) SubFromBalance

func (p *Pegnet) SubFromBalance(tx *sql.Tx, adr *factom.FAAddress, ticker fat2.PTicker, value uint64) (id int64, txError, err error)

SubFromBalance subtracts value from the typed balance of adr, creating a new row in "pn_addresses" if it does not exist and value is 0. If successful, the row id is returned, otherwise 0. If subtracting sub would result in a negative balance, txErr is not nil and starts with "insufficient balance".

func (Pegnet) UpdateBankEntry

func (p Pegnet) UpdateBankEntry(q QueryAble, height int32, bankUsed, pegRequested int64) error

UpdateBankEntry updates the bank_used and total_requested values

type QueryAble

type QueryAble interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
	Prepare(query string) (*sql.Stmt, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
	QueryRow(query string, args ...interface{}) *sql.Row
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
}

QueryAble is so we can swap db and tx interactions

type Stats

type Stats struct {
	Height          uint32
	Burns           uint64
	ConversionTotal uint64
	Supply          map[string]int64
	Volume          map[string]uint64
	VolumeIn        map[string]uint64
	VolumeOut       map[string]uint64
	VolumeTx        map[string]uint64
}

func NewStats

func NewStats(height uint32) *Stats

Jump to

Keyboard shortcuts

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