Documentation

Overview

Define the `Amount` type, which is the monetary type used accross the code base

One BOSCoin accounts for 10 million currency units. In addition to the `Amount` type, some member functions are defined: - `Add` / `Sub` do an addition / substraction and return an error object - `MustAdd` / `MustSub` call `Add` / `Sub` and turn any `error` into a `panic`.

Those are provided for testing / quick prototyping and should not be in production code.

- Invariant `panic`s if the instance it's called on violates its invariant (see Contract programming)

This package defines hash-related functions used in Sebak The primary hash function used in Sebak is a double sha256, like Bitcoin.

Provide test utilities for the common package

Index

Constants

View Source
const (
	// BaseFee is the default transaction fee, if fee is lower than BaseFee, the
	// transaction will fail validation.
	BaseFee Amount = 10000

	// BaseReserve is minimum amount of balance for new account. By default, it
	// is `0.1` BOS.
	BaseReserve Amount = 1000000

	// FrozenFee is a special transaction fee about freezing, and unfreezing.
	FrozenFee Amount = 0

	// GenesisBlockHeight set the block height of genesis block
	GenesisBlockHeight uint64 = 1

	// FirstProposedBlockHeight is used for calculating block time
	FirstProposedBlockHeight uint64 = 2

	// GenesisBlockConfirmedTime is the time for the confirmed time of genesis
	// block. This time is of the first commit of SEBAK.
	GenesisBlockConfirmedTime string = "2018-04-17T5:07:31.000000000Z"

	// InflationRatio is the inflation ratio. If the decimal points is over 17,
	// the inflation amount will be 0, considering with `MaximumBalance`. The
	// current value, `0.0000001` will increase `50BOS` in every block(current
	// genesis balance is `5000000000000000`).
	InflationRatio float64 = 0.0000001

	// BlockHeightEndOfInflation sets the block height of inflation end.
	BlockHeightEndOfInflation uint64 = 36000000

	HTTPCacheMemoryAdapterName = "mem"
	HTTPCacheRedisAdapterName  = "redis"
	HTTPCachePoolSize          = 10000

	// DefaultTxPoolLimit is the default tx pool limit.
	DefaultTxPoolLimit int = 1000000

	// DefaultOperationsInTransactionLimit is the default maximum number of
	// operations in one transaction.
	DefaultOperationsInTransactionLimit int = 1000

	// DefaultTransactionsInBallotLimit is the default maximum number of
	// transactions in one ballot.
	DefaultTransactionsInBallotLimit int = 1000

	// DefaultOperationsInBallotLimit is the default maximum number of
	// operations in one ballot. This does not count the operations of
	// `ProposerTransaction`.
	DefaultOperationsInBallotLimit int = 10000

	DefaultTimeoutINIT       = 2 * time.Second
	DefaultTimeoutSIGN       = 2 * time.Second
	DefaultTimeoutACCEPT     = 2 * time.Second
	DefaultTimeoutALLCONFIRM = 30 * time.Second
	DefaultBlockTime         = 5 * time.Second
	DefaultBlockTimeDelta    = 1 * time.Second

	// DiscoveryMessageCreatedAllowDuration limit the `DiscoveryMessage.Created`
	// is allowed or not.
	DiscoveryMessageCreatedAllowDuration time.Duration = time.Second * 10
)
View Source
const (
	ConnectMessage     MessageType = "connect"
	DiscoveryMessage   MessageType = "discovery"
	TransactionMessage MessageType = "transaction"
	BallotMessage      MessageType = "ballot"

	TransactionVersionV1 = "1"
	BallotVersionV1      = "1"
	DiscoveryVersionV1   = "1"
)
View Source
const (
	BlockPrefixHash                       = string(0x00)
	BlockPrefixConfirmed                  = string(0x01)
	BlockPrefixHeight                     = string(0x02)
	BlockTransactionPrefixHash            = string(0x10)
	BlockTransactionPrefixSource          = string(0x11)
	BlockTransactionPrefixConfirmed       = string(0x12)
	BlockTransactionPrefixAccount         = string(0x13)
	BlockTransactionPrefixBlock           = string(0x14)
	BlockOperationPrefixHash              = string(0x20)
	BlockOperationPrefixTxHash            = string(0x21)
	BlockOperationPrefixSource            = string(0x22)
	BlockOperationPrefixTarget            = string(0x23)
	BlockOperationPrefixPeers             = string(0x24)
	BlockOperationPrefixTypeSource        = string(0x25)
	BlockOperationPrefixTypeTarget        = string(0x26)
	BlockOperationPrefixTypePeers         = string(0x27)
	BlockOperationPrefixCreateFrozen      = string(0x28)
	BlockOperationPrefixFrozenLinked      = string(0x29)
	BlockOperationPrefixBlockHeight       = string(0x2A)
	BlockAccountPrefixAddress             = string(0x30)
	BlockAccountPrefixCreated             = string(0x31)
	BlockAccountSequenceIDPrefix          = string(0x32)
	BlockAccountSequenceIDByAddressPrefix = string(0x33)
	TransactionPoolPrefix                 = string(0x40)
	InternalPrefix                        = string(0x50) // internal data
)
View Source
const MaxUintEncodeByte = 8
View Source
const (
	TIMEFORMAT_ISO8601 string = "2006-01-02T15:04:05.000000000Z07:00"
)

Variables

View Source
var (
	// UnfreezingPeriod is the number of blocks required for unfreezing to take effect.
	// When frozen funds are unfreezed, the transaction is record in the blockchain,
	// and after `UnfreezingPeriod`, it takes effect on the account.
	// The default value, 241920, is equal to:
	// 14 (days) * 24 (hours) * 60 (minutes) * 12 (60 seconds / 5 seconds per block on average)
	UnfreezingPeriod uint64 = 241920

	// BallotConfirmedTimeAllowDuration is the duration time for ballot from
	// other nodes. If confirmed time of ballot has too late or ahead by
	// BallotConfirmedTimeAllowDuration, it will be considered not-wellformed.
	// For details, `Ballot.IsWellFormed()`
	BallotConfirmedTimeAllowDuration time.Duration = time.Minute * time.Duration(1)

	InflationRatioString string = InflationRatio2String(InflationRatio)

	// RateLimitAPI set the rate limit for API interface, the default value
	// allows 100 requests per minute.
	RateLimitAPI, _ = limiter.NewRateFromFormatted("100-M")

	// RateLimitNode set the rate limit for node interface, the default value
	// allows 100 requests per seconds.
	RateLimitNode, _ = limiter.NewRateFromFormatted("100-S")

	HTTPCacheAdapterNames = map[string]bool{
		HTTPCacheMemoryAdapterName: true,
		HTTPCacheRedisAdapterName:  true,
		"":                         true,
	}
	DefaultJSONRPCBindURL string = "http://127.0.0.1:54321/jsonrpc" // JSONRPC only can be accessed from localhost

	// MaxTimeDiffAllow is the allowed difference of node time. The default
	// value, 4 seconds is from BlockTime.
	MaxTimeDiffAllow time.Duration = time.Second * 4
)
View Source
var (
	TrueQueryStringValue  []string = []string{"true", "yes", "1"}
	FalseQueryStringValue []string = []string{"false", "no", "0"}
)
View Source
var BytesToHash = ethcommon.BytesToHash

Set the content of the hash to be the provided binary data

View Source
var DefaultEndpoint int = 12345
View Source
var Encode = rlp.Encode

Encode the provided value It is exposed here as it is useful for recursive calls by types implementing `Encoder`

View Source
var EncodeToBytes = rlp.EncodeToBytes

Ditto

View Source
var EncodeToReader = rlp.EncodeToReader

Ditto

Functions

func CheckBindString

func CheckBindString(b string) error

func CheckPortInUse

func CheckPortInUse(port int) error

func CheckRoundTripRLP

func CheckRoundTripRLP(t *testing.T, record interface{})

Test that a record that gets serialized to RLP deserialize to the same data

Params:

t = The testing object
record = A pointer to the record to serialize

func EncodeUint64ToByteSlice

func EncodeUint64ToByteSlice(i uint64) [MaxUintEncodeByte]byte

func ExecExternalCommand

func ExecExternalCommand(cmd string) ([]byte, error)

func FormatISO8601

func FormatISO8601(t time.Time) string

func GenerateUUID

func GenerateUUID() string

func GetENVValue

func GetENVValue(key, defaultValue string) (v string)

func GetFreePort

func GetFreePort(excludes ...int) (port int)

func GetUniqueIDFromDate

func GetUniqueIDFromDate() string

func GetUniqueIDFromUUID

func GetUniqueIDFromUUID() string

func GetUrlQuery

func GetUrlQuery(query url.Values, key, defaultValue string) string

func InStringArray

func InStringArray(a []string, s string) (index int, found bool)

func InStringMap

func InStringMap(a map[string]bool, s string) (found bool)

func InflationRatio2String

func InflationRatio2String(ratio float64) string

func IsEmpty

func IsEmpty(path string) (bool, error)

func IsExists

func IsExists(path string) bool

func IsLocalhost

func IsLocalhost(s string) bool

func IsNotExists

func IsNotExists(path string) bool

func IsStringArrayEqual

func IsStringArrayEqual(a, b []string) bool

func IsStringMapEqual

func IsStringMapEqual(a, b map[string]bool) bool

func IsStringMapEqualWithHash

func IsStringMapEqualWithHash(a, b map[string]bool) bool

func JSONMarshalIndent

func JSONMarshalIndent(o interface{}) ([]byte, error)

func JsonFormatEx

func JsonFormatEx(pretty, lineSeparated bool) logging.Format

func MakeHash

func MakeHash(b []byte) []byte

Generate a double SHA-256 hash out of the supplied binary data

func MakeObjectHash

func MakeObjectHash(i interface{}) (b []byte, err error)

Generate a double SHA-256 hash from the interface's RLP encoding

Types wishing to implement custom encoding should implement the `Encoder.EncodeRLP` interface

func MustMakeObjectHash

func MustMakeObjectHash(i interface{}) []byte

Pedestrian version of `MakeObjectHash`

func MustMakeObjectHashString

func MustMakeObjectHashString(i interface{}) string

Returns the hash of the object, base58 encoded

func MustMarshalJSON

func MustMarshalJSON(o interface{}) []byte

func MustUnmarshalJSON

func MustUnmarshalJSON(data []byte, v interface{})

Function to wrap calls to `json.Unmarshall` that cannot fail

This function should only be used when doing calls that cannot fails, e.g. reading the content of the on-disk storage which was serialized by sebak. It ensures no silent corruption of data can happen

func NopLogger

func NopLogger() logging.Logger

NopLogger returns a Logger with a no-op (nil) Logger

func NormalizeURLPath

func NormalizeURLPath(s string) string

func NowISO8601

func NowISO8601() string

func ParseBoolQueryString

func ParseBoolQueryString(v string) (yesno bool, err error)

ParseBoolQueryString will parse boolean value from url.Value. By default, `Reverse` is `false`. If 'true', '1', 'yes', it will be `true` If 'false', '0', 'no', it will be `false` If not `true` nor `false, `errors.InvalidQueryString` will be occurred.

func ParseISO8601

func ParseISO8601(s string) (time.Time, error)

func PostAndJSONMatcher

func PostAndJSONMatcher(r *http.Request, rm *mux.RouteMatch) bool

func PutInt

func PutInt(w io.Writer, i uint64) error

Writes i to the `io.Writer` in big endian

func PutListLength

func PutListLength(w io.Writer, length uint64) error

Write the length of a list to the writer according to RLP specs See: https://github.com/ethereum/wiki/wiki/RLP

func RequestURLFromRequest

func RequestURLFromRequest(r *http.Request) *url.URL

func ReverseStringSlice

func ReverseStringSlice(a []string) []string

func RunChecker

func RunChecker(checker Checker, deferFunc CheckerDeferFunc, args ...interface{}) error

func SetLogging

func SetLogging(level logging.Lvl, handler logging.Handler)

func SizeofSize

func SizeofSize(i uint64) (size byte)

Computes the minimum number of bytes required to store `i` in RLP encoding.

func SortDecByValue

func SortDecByValue(slice []KV)

func StrictURLParse

func StrictURLParse(s string) (u *url.URL, err error)

func String2InflationRatio

func String2InflationRatio(s string) (ratio float64, err error)

Types

type Amount

type Amount uint64

Main monetary type used accross sebak

const (
	// 10,000,000 units == 1 BOSCoin
	AmountPerCoin Amount = 10000000
	// The maximum possible supply of coins within any network
	// It is 10 trillions BOSCoin, or 100,000,000,000,000,000,000 in `Amount`
	MaximumBalance Amount = 1000000000000 * AmountPerCoin

	// Amount that can be frozen, currently 10,000 BOS
	// Freezing happens by steps, as one can freeze 10k, 20k, 30k, etc... but not 15k.
	Unit = Amount(10000 * AmountPerCoin)
)

func AmountFromString

func AmountFromString(str string) (Amount, error)

Parse an `Amount` from a string input

Params:

str = a string consisting only of numbers, expressing an amount in GON

Returns:

A valid `Amount` and a `nil` error, or an invalid amount and an `error`

func CalculateInflation

func CalculateInflation(initialBalance Amount) (a Amount, err error)

CalculateInflation returns the amount of inflation in every block.

func MustAmountFromString

func MustAmountFromString(str string) Amount

Same as AmountFromString, except it `panic`s if an error happens

func (Amount) Add

func (a Amount) Add(added Amount) (n Amount, err error)

Add an `Amount` to this `Amount`

If the resulting value would overflow maximumAmount, an error is returned, along with the value (which would trigger a `panic` if used).

func (*Amount) DecodeRLP

func (a *Amount) DecodeRLP(s *RLPStream) error

Implement `common.Decoder`

func (Amount) EncodeRLP

func (a Amount) EncodeRLP(w io.Writer) error

Implement `common.Encoder` TODO: Change this to binary encoding RLP cannot encode integer, so this was historically encoded as string, which is of course very efficient

func (Amount) Invariant

func (this Amount) Invariant()

Check this type's invariant, that is, its value is <= MaximumBalance

func (Amount) MarshalJSON

func (a Amount) MarshalJSON() ([]byte, error)

Implement JSON's Marshaler interface

func (Amount) MultInt

func (a Amount) MultInt(n int) (Amount, error)

Add this `Amount` to itself, `n` times

If the resulting value would overflow maximumAmount, an error is returned, along with the value (which would trigger a `panic` if used).

func (Amount) MultInt64

func (a Amount) MultInt64(n int64) (Amount, error)

/ Ditto

func (Amount) MultUint

func (a Amount) MultUint(n uint) (Amount, error)

/ Ditto

func (Amount) MultUint64

func (a Amount) MultUint64(n uint64) (Amount, error)

/ Ditto

func (Amount) MustAdd

func (a Amount) MustAdd(added Amount) Amount

Counterpart of `Add` which panic instead of returning an error Useful for debugging and testing, should be avoided in regular code

func (Amount) MustMult

func (a Amount) MustMult(n int) Amount

Counterpart of `Mult` which panic instead of returning an error Useful for debugging and testing, should be avoided in regular code

func (Amount) MustSub

func (a Amount) MustSub(sub Amount) Amount

Counterpart of `Sub` which panic instead of returning an error Useful for debugging and testing, should be avoided in regular code

func (Amount) String

func (a Amount) String() string

Stringer interface implementation

func (Amount) Sub

func (a Amount) Sub(sub Amount) (Amount, error)

Substract an `Amount` to this `Amount`

If the resulting value would underflow, an error is returned, along with an invalid value (which would trigger a `panic` if used).

func (*Amount) UnmarshalJSON

func (a *Amount) UnmarshalJSON(b []byte) (err error)

Implement JSON's Unmarshaler interface If Unmarshalling errors, `a` will have an `invalidValue`

type BackoffStrategy

type BackoffStrategy = pester.BackoffStrategy

type Checker

type Checker interface {
	GetFuncs() []CheckerFunc
}

type CheckerDeferFunc

type CheckerDeferFunc func(int, Checker, error)
var DefaultDeferFunc CheckerDeferFunc = func(int, Checker, error) {}

type CheckerErrorStop

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

func NewCheckerErrorStop

func NewCheckerErrorStop(checker Checker, message string) CheckerErrorStop

func (CheckerErrorStop) Checker

func (c CheckerErrorStop) Checker() Checker

func (CheckerErrorStop) Error

func (c CheckerErrorStop) Error() string

type CheckerFunc

type CheckerFunc func(Checker, ...interface{}) error

type CheckerStop

type CheckerStop interface {
	Error() string
	Checker() Checker
}

type Config

type Config struct {
	TimeoutINIT       time.Duration
	TimeoutSIGN       time.Duration
	TimeoutACCEPT     time.Duration
	TimeoutALLCONFIRM time.Duration
	BlockTime         time.Duration
	BlockTimeDelta    time.Duration

	TxsLimit          int
	OpsLimit          int
	OpsInBallotLimit  int
	TxPoolClientLimit int
	TxPoolNodeLimit   int

	NetworkID      []byte
	InitialBalance Amount

	// Those fields are not consensus-related
	RateLimitRuleAPI  RateLimitRule
	RateLimitRuleNode RateLimitRule

	HTTPCacheAdapter    string
	HTTPCachePoolSize   int
	HTTPCacheRedisAddrs map[string]string

	CongressAccountAddress string
	CommonAccountAddress   string

	JSONRPCEndpoint *Endpoint

	WatcherMode bool

	DiscoveryEndpoints []*Endpoint
	StopConsensus      bool
}

Config has timeout features and transaction limit. The Config is included in ISAACStateManager and these timeout features are used in ISAAC consensus.

func NewTestConfig

func NewTestConfig() Config

Initialize a new config object for unittests

type Decoder

type Decoder = rlp.Decoder

Interface recognized by RLP decoder

type DefaultChecker

type DefaultChecker struct {
	Funcs []CheckerFunc
}

func (*DefaultChecker) GetFuncs

func (c *DefaultChecker) GetFuncs() []CheckerFunc

type Encoder

type Encoder = rlp.Encoder

Interface recognized by RLP encoder

type Endpoint

type Endpoint url.URL

func MustParseEndpoint

func MustParseEndpoint(endpoint string) *Endpoint

Utility to get a new `common.Endpoint` from a string

func NewEndpointFromURL

func NewEndpointFromURL(u *url.URL) *Endpoint

func ParseEndpoint

func ParseEndpoint(endpoint string) (u *Endpoint, err error)

func (*Endpoint) EncodeRLP

func (e *Endpoint) EncodeRLP(w io.Writer) error

func (*Endpoint) Equal

func (e *Endpoint) Equal(n *Endpoint) bool

func (*Endpoint) MarshalJSON

func (e *Endpoint) MarshalJSON() ([]byte, error)

func (*Endpoint) Port

func (e *Endpoint) Port() string

func (*Endpoint) Query

func (e *Endpoint) Query() url.Values

func (*Endpoint) String

func (e *Endpoint) String() string

func (*Endpoint) UnmarshalJSON

func (e *Endpoint) UnmarshalJSON(b []byte) error

type HTTP2Client

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

func NewHTTP2Client

func NewHTTP2Client(timeout, idleTimeout time.Duration, keepAlive bool) (client *HTTP2Client, err error)

func NewPersistentHTTP2Client

func NewPersistentHTTP2Client(timeout, idleTimeout time.Duration, keepAlive bool, retrySetting *RetrySetting) (client *HTTP2Client, err error)

func (*HTTP2Client) Close

func (c *HTTP2Client) Close()

func (*HTTP2Client) Do

func (c *HTTP2Client) Do(req *http.Request) (*http.Response, error)

It's same interface as https://golang.org/pkg/net/http/#Client.Do

func (*HTTP2Client) Get

func (c *HTTP2Client) Get(url string, headers http.Header) (response *http.Response, err error)

func (*HTTP2Client) Post

func (c *HTTP2Client) Post(url string, b []byte, headers http.Header) (response *http.Response, err error)

type HTTP2StreamWriter

type HTTP2StreamWriter struct {
	DataChannel chan []byte
	Error       error

	DataChannelClosed bool
}

func GetHTTP2Stream

func GetHTTP2Stream(response *http.Response) (cw *HTTP2StreamWriter, err error)

func NewHTTP2StreamWriter

func NewHTTP2StreamWriter() *HTTP2StreamWriter

func (*HTTP2StreamWriter) Close

func (r *HTTP2StreamWriter) Close() error

func (*HTTP2StreamWriter) Write

func (r *HTTP2StreamWriter) Write(b []byte) (int, error)

type Hash

type Hash = ethcommon.Hash

32 bytes / 256 bits hash type

type HttpDoer

type HttpDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

type KV

type KV struct {
	Key   string
	Value uint64
}

type Message

type Message interface {
	GetType() MessageType
	GetHash() string
	Serialize() ([]byte, error)
	IsWellFormed(Config) error
	Equal(Message) bool
	Source() string
	Version() string
}

type MessageType

type MessageType string

func (MessageType) String

func (t MessageType) String() string

type NetworkMessage

type NetworkMessage struct {
	Type MessageType
	Data []byte
}

func NewNetworkMessage

func NewNetworkMessage(mt MessageType, data []byte) NetworkMessage

func (NetworkMessage) Head

func (t NetworkMessage) Head(n int) NetworkMessage

func (NetworkMessage) IsEmpty

func (t NetworkMessage) IsEmpty() bool

func (NetworkMessage) Serialize

func (t NetworkMessage) Serialize() ([]byte, error)

type RLPStream

type RLPStream = rlp.Stream

Argument to the `Decoder.Decode` method

type RateLimitRule

type RateLimitRule struct {
	Default     limiter.Rate
	ByIPAddress map[string]limiter.Rate
}

func NewRateLimitRule

func NewRateLimitRule(rate limiter.Rate) RateLimitRule

type RetrySetting

type RetrySetting struct {
	MaxRetries  int
	Concurrency int
	Backoff     BackoffStrategy
}

type TimeSync

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

func NewTimeSync

func NewTimeSync(ntpServer string, syncCmd string) (*TimeSync, error)

func (*TimeSync) Query

func (ts *TimeSync) Query() (*ntp.Response, error)

func (*TimeSync) Start

func (ts *TimeSync) Start()

func (*TimeSync) Sync

func (ts *TimeSync) Sync() error

Directories

Path Synopsis
keypair Encapsulate Stellar's keypair package Provides additional wrapper and convenience functions, suited for usage within Sebak Provides utilities to use in test code
observer
test