sebak: Index | Files | Directories

package common

import ""

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


Package Files

amount.go checker.go config.go constant.go exec.go hash.go http2_client.go inflation.go init.go log.go message.go net.go prefix.go router.go test.go time.go url.go util.go


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
const (
    ConnectMessage     MessageType = "connect"
    DiscoveryMessage   MessageType = "discovery"
    TransactionMessage MessageType = "transaction"
    BallotMessage      MessageType = "ballot"

    TransactionVersionV1 = "1"
    BallotVersionV1      = "1"
    DiscoveryVersionV1   = "1"
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
const MaxUintEncodeByte = 8
const (
    TIMEFORMAT_ISO8601 string = "2006-01-02T15:04:05.000000000Z07:00"


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 = "" // 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
var (
    DefaultLogLevel   logging.Lvl     = logging.LvlInfo
    DefaultLogHandler logging.Handler = logging.StreamHandler(os.Stdout, logging.TerminalFormat())
var (
    TrueQueryStringValue  []string = []string{"true", "yes", "1"}
    FalseQueryStringValue []string = []string{"false", "no", "0"}
var BytesToHash = ethcommon.BytesToHash

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

var DefaultEndpoint int = 12345
var Encode = rlp.Encode

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

var EncodeToBytes = rlp.EncodeToBytes


var EncodeToReader = rlp.EncodeToReader


func CheckBindString Uses

func CheckBindString(b string) error

func CheckPortInUse Uses

func CheckPortInUse(port int) error

func CheckRoundTripRLP Uses

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

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


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

func EncodeUint64ToByteSlice Uses

func EncodeUint64ToByteSlice(i uint64) [MaxUintEncodeByte]byte

func ExecExternalCommand Uses

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

func FormatISO8601 Uses

func FormatISO8601(t time.Time) string

func GenerateUUID Uses

func GenerateUUID() string

func GetENVValue Uses

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

func GetFreePort Uses

func GetFreePort(excludes (port int)

func GetUniqueIDFromDate Uses

func GetUniqueIDFromDate() string

func GetUniqueIDFromUUID Uses

func GetUniqueIDFromUUID() string

func GetUrlQuery Uses

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

func InStringArray Uses

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

func InStringMap Uses

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

func InflationRatio2String Uses

func InflationRatio2String(ratio float64) string

func IsEmpty Uses

func IsEmpty(path string) (bool, error)

func IsExists Uses

func IsExists(path string) bool

func IsLocalhost Uses

func IsLocalhost(s string) bool

func IsNotExists Uses

func IsNotExists(path string) bool

func IsStringArrayEqual Uses

func IsStringArrayEqual(a, b []string) bool

func IsStringMapEqual Uses

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

func IsStringMapEqualWithHash Uses

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

func JSONMarshalIndent Uses

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

func JsonFormatEx Uses

func JsonFormatEx(pretty, lineSeparated bool) logging.Format

func MakeHash Uses

func MakeHash(b []byte) []byte

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

func MakeObjectHash Uses

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 Uses

func MustMakeObjectHash(i interface{}) []byte

Pedestrian version of `MakeObjectHash`

func MustMakeObjectHashString Uses

func MustMakeObjectHashString(i interface{}) string

Returns the hash of the object, base58 encoded

func MustMarshalJSON Uses

func MustMarshalJSON(o interface{}) []byte

func MustUnmarshalJSON Uses

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 Uses

func NopLogger() logging.Logger

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

func NormalizeURLPath Uses

func NormalizeURLPath(s string) string

func NowISO8601 Uses

func NowISO8601() string

func ParseBoolQueryString Uses

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 Uses

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

func PostAndJSONMatcher Uses

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

func PutInt Uses

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

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

func PutListLength Uses

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

Write the length of a list to the writer according to RLP specs See:

func RequestURLFromRequest Uses

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

func ReverseStringSlice Uses

func ReverseStringSlice(a []string) []string

func RunChecker Uses

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

func SetLogging Uses

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

func SizeofSize Uses

func SizeofSize(i uint64) (size byte)

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

func SortDecByValue Uses

func SortDecByValue(slice []KV)

func StrictURLParse Uses

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

func String2InflationRatio Uses

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

type Amount Uses

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 Uses

func AmountFromString(str string) (Amount, error)

Parse an `Amount` from a string input


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


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

func CalculateInflation Uses

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

CalculateInflation returns the amount of inflation in every block.

func MustAmountFromString Uses

func MustAmountFromString(str string) Amount

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

func (Amount) Add Uses

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 Uses

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

Implement `common.Decoder`

func (Amount) EncodeRLP Uses

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 Uses

func (this Amount) Invariant()

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

func (Amount) MarshalJSON Uses

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

Implement JSON's Marshaler interface

func (Amount) MultInt Uses

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 Uses

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

/ Ditto

func (Amount) MultUint Uses

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

/ Ditto

func (Amount) MultUint64 Uses

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

/ Ditto

func (Amount) MustAdd Uses

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 Uses

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 Uses

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 Uses

func (a Amount) String() string

Stringer interface implementation

func (Amount) Sub Uses

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 Uses

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

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

type BackoffStrategy Uses

type BackoffStrategy = pester.BackoffStrategy

type Checker Uses

type Checker interface {
    GetFuncs() []CheckerFunc

type CheckerDeferFunc Uses

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

type CheckerErrorStop Uses

type CheckerErrorStop struct {
    // contains filtered or unexported fields

func NewCheckerErrorStop Uses

func NewCheckerErrorStop(checker Checker, message string) CheckerErrorStop

func (CheckerErrorStop) Checker Uses

func (c CheckerErrorStop) Checker() Checker

func (CheckerErrorStop) Error Uses

func (c CheckerErrorStop) Error() string

type CheckerFunc Uses

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

type CheckerStop Uses

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

type Config Uses

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 Uses

func NewTestConfig() Config

Initialize a new config object for unittests

type Decoder Uses

type Decoder = rlp.Decoder

Interface recognized by RLP decoder

type DefaultChecker Uses

type DefaultChecker struct {
    Funcs []CheckerFunc

func (*DefaultChecker) GetFuncs Uses

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

type Encoder Uses

type Encoder = rlp.Encoder

Interface recognized by RLP encoder

type Endpoint Uses

type Endpoint url.URL

func MustParseEndpoint Uses

func MustParseEndpoint(endpoint string) *Endpoint

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

func NewEndpointFromURL Uses

func NewEndpointFromURL(u *url.URL) *Endpoint

func ParseEndpoint Uses

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

func (*Endpoint) EncodeRLP Uses

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

func (*Endpoint) Equal Uses

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

func (*Endpoint) MarshalJSON Uses

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

func (*Endpoint) Port Uses

func (e *Endpoint) Port() string

func (*Endpoint) Query Uses

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

func (*Endpoint) String Uses

func (e *Endpoint) String() string

func (*Endpoint) UnmarshalJSON Uses

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

type HTTP2Client Uses

type HTTP2Client struct {
    // contains filtered or unexported fields

func NewHTTP2Client Uses

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

func NewPersistentHTTP2Client Uses

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

func (*HTTP2Client) Close Uses

func (c *HTTP2Client) Close()

func (*HTTP2Client) Do Uses

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

It's same interface as

func (*HTTP2Client) Get Uses

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

func (*HTTP2Client) Post Uses

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

type HTTP2StreamWriter Uses

type HTTP2StreamWriter struct {
    DataChannel chan []byte
    Error       error

    DataChannelClosed bool

func GetHTTP2Stream Uses

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

func NewHTTP2StreamWriter Uses

func NewHTTP2StreamWriter() *HTTP2StreamWriter

func (*HTTP2StreamWriter) Close Uses

func (r *HTTP2StreamWriter) Close() error

func (*HTTP2StreamWriter) Write Uses

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

type Hash Uses

type Hash = ethcommon.Hash

32 bytes / 256 bits hash type

type HttpDoer Uses

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

type KV Uses

type KV struct {
    Key   string
    Value uint64

type Message Uses

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

type MessageType Uses

type MessageType string

func (MessageType) String Uses

func (t MessageType) String() string

type NetworkMessage Uses

type NetworkMessage struct {
    Type MessageType
    Data []byte

func NewNetworkMessage Uses

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

func (NetworkMessage) Head Uses

func (t NetworkMessage) Head(n int) NetworkMessage

func (NetworkMessage) IsEmpty Uses

func (t NetworkMessage) IsEmpty() bool

func (NetworkMessage) Serialize Uses

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

type RLPStream Uses

type RLPStream = rlp.Stream

Argument to the `Decoder.Decode` method

type RateLimitRule Uses

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

func NewRateLimitRule Uses

func NewRateLimitRule(rate limiter.Rate) RateLimitRule

type RetrySetting Uses

type RetrySetting struct {
    MaxRetries  int
    Concurrency int
    Backoff     BackoffStrategy

type TimeSync Uses

type TimeSync struct {
    // contains filtered or unexported fields

func NewTimeSync Uses

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

func (*TimeSync) Query Uses

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

func (*TimeSync) Start Uses

func (ts *TimeSync) Start()

func (*TimeSync) Sync Uses

func (ts *TimeSync) Sync() error


keypairEncapsulate Stellar's keypair package

Package common imports 32 packages (graph) and is imported by 49 packages. Updated 2019-03-12. Refresh now. Tools for package owners.