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
- Variables
- func CheckBindString(b string) error
- func CheckPortInUse(port int) error
- func CheckRoundTripRLP(t *testing.T, record interface{})
- func EncodeUint64ToByteSlice(i uint64) [MaxUintEncodeByte]byte
- func ExecExternalCommand(cmd string) ([]byte, error)
- func FormatISO8601(t time.Time) string
- func GenerateUUID() string
- func GetENVValue(key, defaultValue string) (v string)
- func GetFreePort(excludes ...int) (port int)
- func GetUniqueIDFromDate() string
- func GetUniqueIDFromUUID() string
- func GetUrlQuery(query url.Values, key, defaultValue string) string
- func InStringArray(a []string, s string) (index int, found bool)
- func InStringMap(a map[string]bool, s string) (found bool)
- func InflationRatio2String(ratio float64) string
- func IsEmpty(path string) (bool, error)
- func IsExists(path string) bool
- func IsLocalhost(s string) bool
- func IsNotExists(path string) bool
- func IsStringArrayEqual(a, b []string) bool
- func IsStringMapEqual(a, b map[string]bool) bool
- func IsStringMapEqualWithHash(a, b map[string]bool) bool
- func JSONMarshalIndent(o interface{}) ([]byte, error)
- func JsonFormatEx(pretty, lineSeparated bool) logging.Format
- func MakeHash(b []byte) []byte
- func MakeObjectHash(i interface{}) (b []byte, err error)
- func MustMakeObjectHash(i interface{}) []byte
- func MustMakeObjectHashString(i interface{}) string
- func MustMarshalJSON(o interface{}) []byte
- func MustUnmarshalJSON(data []byte, v interface{})
- func NopLogger() logging.Logger
- func NormalizeURLPath(s string) string
- func NowISO8601() string
- func ParseBoolQueryString(v string) (yesno bool, err error)
- func ParseISO8601(s string) (time.Time, error)
- func PostAndJSONMatcher(r *http.Request, rm *mux.RouteMatch) bool
- func PutInt(w io.Writer, i uint64) error
- func PutListLength(w io.Writer, length uint64) error
- func RequestURLFromRequest(r *http.Request) *url.URL
- func ReverseStringSlice(a []string) []string
- func RunChecker(checker Checker, deferFunc CheckerDeferFunc, args ...interface{}) error
- func SetLogging(level logging.Lvl, handler logging.Handler)
- func SizeofSize(i uint64) (size byte)
- func SortDecByValue(slice []KV)
- func StrictURLParse(s string) (u *url.URL, err error)
- func String2InflationRatio(s string) (ratio float64, err error)
- type Amount
- func (a Amount) Add(added Amount) (n Amount, err error)
- func (a *Amount) DecodeRLP(s *RLPStream) error
- func (a Amount) EncodeRLP(w io.Writer) error
- func (this Amount) Invariant()
- func (a Amount) MarshalJSON() ([]byte, error)
- func (a Amount) MultInt(n int) (Amount, error)
- func (a Amount) MultInt64(n int64) (Amount, error)
- func (a Amount) MultUint(n uint) (Amount, error)
- func (a Amount) MultUint64(n uint64) (Amount, error)
- func (a Amount) MustAdd(added Amount) Amount
- func (a Amount) MustMult(n int) Amount
- func (a Amount) MustSub(sub Amount) Amount
- func (a Amount) String() string
- func (a Amount) Sub(sub Amount) (Amount, error)
- func (a *Amount) UnmarshalJSON(b []byte) (err error)
- type BackoffStrategy
- type Checker
- type CheckerDeferFunc
- type CheckerErrorStop
- type CheckerFunc
- type CheckerStop
- type Config
- type Decoder
- type DefaultChecker
- type Encoder
- type Endpoint
- type HTTP2Client
- func (c *HTTP2Client) Close()
- func (c *HTTP2Client) Do(req *http.Request) (*http.Response, error)
- func (c *HTTP2Client) Get(url string, headers http.Header) (response *http.Response, err error)
- func (c *HTTP2Client) Post(url string, b []byte, headers http.Header) (response *http.Response, err error)
- type HTTP2StreamWriter
- type Hash
- type HttpDoer
- type KV
- type Message
- type MessageType
- type NetworkMessage
- type RLPStream
- type RateLimitRule
- type RetrySetting
- type TimeSync
Constants ¶
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"
)
Variables ¶
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 )
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
Ditto
var EncodeToReader = rlp.EncodeToReader
Ditto
Functions ¶
func CheckBindString ¶
func CheckPortInUse ¶
func CheckRoundTripRLP ¶
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 FormatISO8601 ¶
func GenerateUUID ¶
func GenerateUUID() string
func GetENVValue ¶
func GetFreePort ¶
func GetUniqueIDFromDate ¶
func GetUniqueIDFromDate() string
func GetUniqueIDFromUUID ¶
func GetUniqueIDFromUUID() string
func InflationRatio2String ¶
func IsLocalhost ¶
func IsNotExists ¶
func IsStringArrayEqual ¶
func IsStringMapEqual ¶
func JSONMarshalIndent ¶
func JsonFormatEx ¶
func MakeObjectHash ¶
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 NormalizeURLPath ¶
func NowISO8601 ¶
func NowISO8601() string
func ParseBoolQueryString ¶
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 PostAndJSONMatcher ¶
func PostAndJSONMatcher(r *http.Request, rm *mux.RouteMatch) bool
func PutListLength ¶
Write the length of a list to the writer according to RLP specs See: https://github.com/ethereum/wiki/wiki/RLP
func ReverseStringSlice ¶
func RunChecker ¶
func RunChecker(checker Checker, deferFunc CheckerDeferFunc, args ...interface{}) error
func SizeofSize ¶
Computes the minimum number of bytes required to store `i` in RLP encoding.
func SortDecByValue ¶
func SortDecByValue(slice []KV)
func String2InflationRatio ¶
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 ¶
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 ¶
CalculateInflation returns the amount of inflation in every block.
func MustAmountFromString ¶
Same as AmountFromString, except it `panic`s if an error happens
func (Amount) Add ¶
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) EncodeRLP ¶
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 ¶
Implement JSON's Marshaler interface
func (Amount) MultInt ¶
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) MustAdd ¶
Counterpart of `Add` which panic instead of returning an error Useful for debugging and testing, should be avoided in regular code
func (Amount) MustMult ¶
Counterpart of `Mult` which panic instead of returning an error Useful for debugging and testing, should be avoided in regular code
func (Amount) MustSub ¶
Counterpart of `Sub` which panic instead of returning an error Useful for debugging and testing, should be avoided in regular code
func (Amount) Sub ¶
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 ¶
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 ¶
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 CheckerStop ¶
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.
type DefaultChecker ¶
type DefaultChecker struct {
Funcs []CheckerFunc
}
func (*DefaultChecker) GetFuncs ¶
func (c *DefaultChecker) GetFuncs() []CheckerFunc
type Endpoint ¶
func MustParseEndpoint ¶
Utility to get a new `common.Endpoint` from a string
func NewEndpointFromURL ¶
func ParseEndpoint ¶
func (*Endpoint) MarshalJSON ¶
func (*Endpoint) UnmarshalJSON ¶
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 ¶
It's same interface as https://golang.org/pkg/net/http/#Client.Do
type HTTP2StreamWriter ¶
func GetHTTP2Stream ¶
func GetHTTP2Stream(response *http.Response) (cw *HTTP2StreamWriter, err error)
func NewHTTP2StreamWriter ¶
func NewHTTP2StreamWriter() *HTTP2StreamWriter
func (*HTTP2StreamWriter) Close ¶
func (r *HTTP2StreamWriter) Close() error
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 RateLimitRule ¶
func NewRateLimitRule ¶
func NewRateLimitRule(rate limiter.Rate) RateLimitRule
type RetrySetting ¶
type RetrySetting struct { MaxRetries int Concurrency int Backoff BackoffStrategy }
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Encapsulate Stellar's keypair package Provides additional wrapper and convenience functions, suited for usage within Sebak Provides utilities to use in test code
|
Encapsulate Stellar's keypair package Provides additional wrapper and convenience functions, suited for usage within Sebak Provides utilities to use in test code |