lurkcoin

package
v3.0.9+incompatible Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2021 License: AGPL-3.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const COPYRIGHT = "Copyright © 2020 by luk3yx"

Copyrights should be separated by newlines

View Source
const DefaultTargetBalance int64 = 500000

Make a new server The default target balance is currently ¤500,000.

View Source
const REPORT_SECURITY = "https://gitlab.com/luk3yx/lurkcoin-core/-/issues/new"
View Source
const SOURCE_URL = "https://github.com/luk3yx/lurkcoin-core"

Note that public source code is required by the AGPL

View Source
const SYMBOL = "¤"
View Source
const VERSION = "3.0.9"

Variables

View Source
var MaxTargetBalance = CurrencyFromInt64(500000000)

Functions

func AuthenticateRequest

func AuthenticateRequest(db Database, username, token string,
	otherServers []string) (bool, *DatabaseTransaction, *Server)

func BackupDatabase

func BackupDatabase(db Database, writer io.Writer) error

Backup a database.

func ConstantTimeCompare

func ConstantTimeCompare(a, b string) bool

Returns true if a == b in a constant time. Note that this will however leak string lengths.

func ForEach

func ForEach(db Database, f func(*Server) error, saveChanges bool) error

func GenerateToken

func GenerateToken() string

Generate a secure random API token. This will probably be around 171 characters long.

func GenerateTransactionID

func GenerateTransactionID() (string, int64)

func GetV2History

func GetV2History(summary Summary, appendID bool) (h []string)

A helper used by both lurkcoin/api and lurkcoin/databases.

func HomogeniseUsername

func HomogeniseUsername(username string) string

func LookupError

func LookupError(code string) (string, string, int)

func PasteuriseUsername

func PasteuriseUsername(username string) (res string, runeCount int)

Remove control characters and leading+trailing whitespace from a username. HomogeniseUsername(PasteuriseUsername(username)) should always equal HomogeniseUsername(username).

func PrintASCIIArt

func PrintASCIIArt()

func RestoreDatabase

func RestoreDatabase(db Database, reader io.Reader) error

Restore a database. This is not atomic and may result in a partially restored database. TODO: Delete servers that exist in the database but do not exist in the backup.

func SeedPRNG

func SeedPRNG()

Gets a random uint64 with crypto/rand, casts it to an int64 and feeds it to rand.Seed().

func ValidateWebhookURL

func ValidateWebhookURL(rawURL string) (string, bool)

Validate a webhook URL, returns the actual URL that should be used and a boolean indicating success.

Types

type Currency

type Currency struct {
	// contains filtered or unexported fields
}

Create a custom Currency type that stores read-only currency values.

func CurrencyFromFloat

func CurrencyFromFloat(num *big.Float) Currency

Create new currency values

func CurrencyFromFloat64

func CurrencyFromFloat64(num float64) Currency

func CurrencyFromInt

func CurrencyFromInt(num *big.Int) Currency

func CurrencyFromInt64

func CurrencyFromInt64(num int64) Currency

func CurrencyFromString

func CurrencyFromString(num string) Currency

func GetExchangeRate

func GetExchangeRate(db Database, source, target string, amount Currency) (Currency, error)

Get an exchange rate between two servers

func ParseCurrency

func ParseCurrency(num string) (Currency, error)

func (Currency) Add

func (self Currency) Add(num Currency) Currency

Addition/division

func (Currency) Cmp

func (self Currency) Cmp(num Currency) int

Comparisons

func (Currency) DeltaString

func (self Currency) DeltaString() string

Returns the currency as a human-readable string. Positive numbers are prefixed with +.

func (Currency) Div

func (self Currency) Div(num Currency) *big.Float

func (Currency) Eq

func (self Currency) Eq(num Currency) bool

func (Currency) Float

func (self Currency) Float() *big.Float

func (*Currency) GobDecode

func (self *Currency) GobDecode(data []byte) error

func (*Currency) GobEncode

func (self *Currency) GobEncode() ([]byte, error)

func (Currency) Gt

func (self Currency) Gt(num Currency) bool

func (Currency) GtZero

func (self Currency) GtZero() bool

func (Currency) Int

func (self Currency) Int() *big.Int

func (Currency) IsNil

func (self Currency) IsNil() bool

func (Currency) IsZero

func (self Currency) IsZero() bool

func (Currency) Lt

func (self Currency) Lt(num Currency) bool

func (Currency) LtZero

func (self Currency) LtZero() bool

func (Currency) MarshalJSON

func (self Currency) MarshalJSON() ([]byte, error)

JSON

func (Currency) Neg

func (self Currency) Neg() Currency

func (Currency) RawString

func (self Currency) RawString() string

A method to convert currency to a string.

func (Currency) String

func (self Currency) String() string

Returns the currency as a human-readable string.

func (Currency) Sub

func (self Currency) Sub(num Currency) Currency

func (*Currency) UnmarshalJSON

func (self *Currency) UnmarshalJSON(data []byte) error

type Database

type Database interface {
	// GetServers(serverNames) (servers, ok, badServer)
	// This must atomically get all servers specified, and if one fails free
	// the previous ones and return nil, false, <failed server UID>.
	// NOTE THAT THIS WILL DEADLOCK IF DUPLICATE SERVERs ARE PROVIDED! Use
	// a DatabaseTransaction object to mitigate this issue.
	GetServers([]string) ([]*Server, bool, string)

	// FreeServers(servers, saveChanges)
	// This must atomically free all servers in servers, and if saveChanges is
	// true write any changes to the database.
	FreeServers([]*Server, bool)

	CreateServer(string) (*Server, bool)
	ListServers() []string
	DeleteServer(string) bool
}

type DatabaseTransaction

type DatabaseTransaction struct {
	// contains filtered or unexported fields
}

An atomic database transaction.

func BeginDbTransaction

func BeginDbTransaction(db Database) *DatabaseTransaction

Creates a new DatabaseTransaction object for a database.

func (*DatabaseTransaction) Abort

func (self *DatabaseTransaction) Abort()

Aborts the transaction and discards any changes made. This is a no-op if Finish() or Abort() have already been called.

func (*DatabaseTransaction) CreateServer

func (self *DatabaseTransaction) CreateServer(name string) (*Server, bool)

Creates a server. This may or may not be able to be reverted with Abort().

func (*DatabaseTransaction) Finish

func (self *DatabaseTransaction) Finish()

Commits the changes made to the database.

func (*DatabaseTransaction) ForEach

func (self *DatabaseTransaction) ForEach(f func(*Server) error, saveChanges bool) error

Iterate over the database. Server objects are freed after f() returns.

func (*DatabaseTransaction) GetCachedServer

func (self *DatabaseTransaction) GetCachedServer(name string) (server *Server, ok bool)

Get a server already in the cache

func (*DatabaseTransaction) GetOneServer

func (self *DatabaseTransaction) GetOneServer(name string) (server *Server, ok bool)

func (*DatabaseTransaction) GetOrCreateServer

func (self *DatabaseTransaction) GetOrCreateServer(name string) (*Server, bool)

Gets a server or creates one if it doesn't exist.

func (*DatabaseTransaction) GetRawDatabase

func (self *DatabaseTransaction) GetRawDatabase() Database

func (*DatabaseTransaction) GetServers

func (self *DatabaseTransaction) GetServers(names ...string) ([]*Server, bool, string)

Get a server. The server will be freed once Finish() or Abort() is called.

func (*DatabaseTransaction) ListServers

func (self *DatabaseTransaction) ListServers() []string

Calls the underlying database's ListServers().

type EncodedServer

type EncodedServer struct {
	// A version number for breaking changes, because of the way gob works this
	// can be upgraded to a uint16/uint32 at a later time.
	Version uint8 `json:"version"`

	// The server name (not passed through HomogeniseUsername)
	Name string `json:"name"`

	// The balance in integer form where 1234 is ¤12.34.
	Balance *big.Int `json:"balance"`

	// The target balance in the same format as the above balance.
	TargetBalance *big.Int `json:"target_balance"`

	// Other values
	History             []Transaction `json:"history"`
	PendingTransactions []Transaction `json:"pending_transactions"`
	Token               string        `json:"token"`
	WebhookURL          string        `json:"webhook_url"`
}

"Encoded" servers that have all their values public

func (*EncodedServer) Decode

func (self *EncodedServer) Decode() *Server

type Server

type Server struct {
	UID  string
	Name string

	WebhookURL string
	// contains filtered or unexported fields
}

Most mutable fields in Server are private to prevent race conditions. Note that pendingTransactions has to be ordered to retain lurkcoinV2 compatibility. If compatibiltiy is ever dropped, it could possibly become a map[string]Transaction to improve the efficiency of delete operations.

func NewServer

func NewServer(name string) *Server

func (*Server) AddToHistory

func (self *Server) AddToHistory(transaction Transaction)

func (*Server) ChangeBal

func (self *Server) ChangeBal(num Currency) bool

Changes the user's balance, returns false if the user does not have enough money. This is an atomic operation, changing the balance manually is not recommended.

func (*Server) CheckToken

func (self *Server) CheckToken(token string) bool

Check an API token. WARNING: This may leak the length of the stored token, however that is probably already deducible by inspecting GenerateToken().

func (*Server) Encode

func (self *Server) Encode() EncodedServer

func (*Server) GetBalance

func (self *Server) GetBalance() Currency

func (*Server) GetExchangeRate

func (self *Server) GetExchangeRate(amount Currency, toLurkcoin bool) (Currency,
	*big.Float)

Exchange rate calculations are horrible at the moment, however they work (at least I think they work).

func (*Server) GetHistory

func (self *Server) GetHistory() []Transaction

Gets the server's history. The slice returned can be modified, however the transaction objects should not be.

func (*Server) GetPendingTransactions

func (self *Server) GetPendingTransactions() []Transaction

Get a list of pending transactions, similar to GetHistory().

func (*Server) GetSummary

func (self *Server) GetSummary() Summary

func (*Server) GetTargetBalance

func (self *Server) GetTargetBalance() Currency

func (*Server) HasPendingTransactions

func (self *Server) HasPendingTransactions() bool

Returns true if the server has pending transactions.

func (*Server) IsModified

func (self *Server) IsModified() bool

func (*Server) Pay

func (sourceServer *Server) Pay(source, target string,
	targetServer *Server, sentAmount Currency, localCurrency bool,
	revertable bool) (*Transaction, error)

Sends a payment.

func (*Server) RegenerateToken

func (self *Server) RegenerateToken() string

Regenerates the token and returns the new one.

func (*Server) RejectPendingTransaction

func (self *Server) RejectPendingTransaction(id string,
	tr *DatabaseTransaction)

Reject (and possibly revert) a pending transaction.

func (*Server) RemoveFirstPendingTransactions

func (self *Server) RemoveFirstPendingTransactions(amount int)

Remove the first <amount> pending transactions. This is here to support lurkcoinV2 and probably shouldn't be used outside of that.

func (*Server) RemovePendingTransaction

func (self *Server) RemovePendingTransaction(id string)

Remove a pending transaction given its ID.

func (*Server) SetModified

func (self *Server) SetModified()

func (*Server) SetTargetBalance

func (self *Server) SetTargetBalance(targetBalance Currency) bool

Sets the target balance.

func (*Server) SetWebhookURL

func (self *Server) SetWebhookURL(webhookURL string) (ok bool)

Validates and sets a webhook URL.

type ServerCollection

type ServerCollection interface {
	GetServer(name string) *Server
}

type Summary

type Summary struct {
	UID           string        `json:"uid"`
	Name          string        `json:"name"`
	Bal           Currency      `json:"bal"`
	Balance       string        `json:"balance"`
	History       []Transaction `json:"history"`
	InterestRate  float64       `json:"interest_rate"`
	TargetBalance Currency      `json:"target_balance"`
}

Summaries

type Transaction

type Transaction struct {
	ID             string   `json:"id"`
	Source         string   `json:"source"`
	SourceServer   string   `json:"source_server"`
	Target         string   `json:"target"`
	TargetServer   string   `json:"target_server"`
	Amount         Currency `json:"amount"`
	SentAmount     Currency `json:"sent_amount"`
	ReceivedAmount Currency `json:"received_amount"`
	Time           int64    `json:"time"`

	// If true lurkcoin will attempt to revert the transaction if it is
	// rejected. The transaction can still be rejected if this is false.
	Revertable bool `json:"revertable"`
}

func MakeTransaction

func MakeTransaction(source, sourceServer, target, targetServer string,
	amount, sentAmount, receivedAmount Currency) Transaction

func (*Transaction) GetLegacyID

func (self *Transaction) GetLegacyID() int32

func (Transaction) GetTime

func (self Transaction) GetTime() time.Time

Get a time.Time object from the transaction's Time attribute.

func (Transaction) String

func (self Transaction) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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