tomox_state

package
v2.0.1-beta+incompatible Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2019 License: GPL-3.0 Imports: 21 Imported by: 0

Documentation

Overview

Package state provides a caching layer atop the Ethereum state trie.

Index

Constants

This section is empty.

Variables

View Source
var (
	EmptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
	Ask       = "SELL"
	Bid       = "BUY"
	Market    = "MO"
	Limit     = "LO"
	Cancel    = "CANCELLED"
)
View Source
var (
	ErrWrongHash             = errors.New("verify order: wrong hash")
	ErrInvalidSignature      = errors.New("verify order: invalid signature")
	ErrInvalidPrice          = errors.New("verify order: invalid price")
	ErrInvalidQuantity       = errors.New("verify order: invalid quantity")
	ErrInvalidRelayer        = errors.New("verify order: invalid relayer")
	ErrInvalidOrderType      = errors.New("verify order: unsupported order type")
	ErrInvalidOrderSide      = errors.New("verify order: invalid order side")
	ErrOrderBookHashNotMatch = errors.New("verify order: orderbook hash not match")
	ErrOrderTreeHashNotMatch = errors.New("verify order: ordertree hash not match")

	// supported order types
	MatchingOrderType = map[string]bool{
		Market: true,
		Limit:  true,
	}
)
View Source
var (
	TokenMappingSlot = map[string]uint64{
		"balances": 0,
	}
	RelayerMappingSlot = map[string]uint64{
		"CONTRACT_OWNER":       0,
		"MaximumRelayers":      1,
		"MaximumTokenList":     2,
		"RELAYER_LIST":         3,
		"RELAYER_COINBASES":    4,
		"RESIGN_REQUESTS":      5,
		"RELAYER_ON_SALE_LIST": 6,
		"RelayerCount":         7,
		"MinimumDeposit":       8,
	}
	RelayerStructMappingSlot = map[string]*big.Int{
		"_deposit":    big.NewInt(0),
		"_fee":        big.NewInt(1),
		"_fromTokens": big.NewInt(2),
		"_toTokens":   big.NewInt(3),
		"_index":      big.NewInt(4),
		"_owner":      big.NewInt(5),
	}
)
View Source
var EmptyExchangeOnject = exchangeObject{
	Nonce:   0,
	AskRoot: EmptyHash,
	BidRoot: EmptyHash,
}
View Source
var EmptyHash = common.Hash{}
View Source
var EmptyOrder = OrderItem{
	Quantity: Zero,
}
View Source
var EmptyOrderList = orderList{
	Volume: nil,
	Root:   EmptyHash,
}
View Source
var MaxTrieCacheGen = uint16(120)

Trie cache generation limit after which to evic trie nodes from memory.

View Source
var Zero = big.NewInt(0)

Functions

func AddTokenBalance

func AddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error

func CheckAddTokenBalance

func CheckAddTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error)

func CheckRelayerFee

func CheckRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateDB) error

func CheckSubRelayerFee

func CheckSubRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateDB, mapBalances map[common.Address]*big.Int) (*big.Int, error)

func CheckSubTokenBalance

func CheckSubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB, mapBalances map[common.Address]map[common.Address]*big.Int) (*big.Int, error)

func GetBaseTokenAtIndex

func GetBaseTokenAtIndex(relayer common.Address, statedb *state.StateDB, index uint64) common.Address

func GetBaseTokenLength

func GetBaseTokenLength(relayer common.Address, statedb *state.StateDB) uint64

func GetCoinbaseFeeList

func GetCoinbaseFeeList(statedb *state.StateDB) map[common.Address]*big.Int

GetCoinbaseFeeList get add coinbase fee

func GetExRelayerFee

func GetExRelayerFee(relayer common.Address, statedb *state.StateDB) *big.Int

func GetLocMappingAtKey

func GetLocMappingAtKey(key common.Hash, slot uint64) *big.Int

func GetQuoteTokenAtIndex

func GetQuoteTokenAtIndex(relayer common.Address, statedb *state.StateDB, index uint64) common.Address

func GetQuoteTokenLength

func GetQuoteTokenLength(relayer common.Address, statedb *state.StateDB) uint64

func GetRelayerOwner

func GetRelayerOwner(relayer common.Address, statedb *state.StateDB) common.Address

func GetTokenBalance

func GetTokenBalance(addr common.Address, token common.Address, statedb *state.StateDB) *big.Int

func IsValidRelayer

func IsValidRelayer(statedb *state.StateDB, address common.Address) bool

func SetSubRelayerFee

func SetSubRelayerFee(relayer common.Address, balance *big.Int, fee *big.Int, statedb *state.StateDB)

func SetTokenBalance

func SetTokenBalance(addr common.Address, balance *big.Int, token common.Address, statedb *state.StateDB) error

func SubRelayerFee

func SubRelayerFee(relayer common.Address, fee *big.Int, statedb *state.StateDB) error

func SubTokenBalance

func SubTokenBalance(addr common.Address, value *big.Int, token common.Address, statedb *state.StateDB) error

func ToBigInt

func ToBigInt(s string) *big.Int

func VerifyPair

func VerifyPair(statedb *state.StateDB, exchangeAddress, baseToken, quoteToken common.Address) error

Types

type Database

type Database interface {
	// OpenTrie opens the main account trie.
	OpenTrie(root common.Hash) (Trie, error)

	// OpenStorageTrie opens the storage trie of an account.
	OpenStorageTrie(addrHash, root common.Hash) (Trie, error)

	// CopyTrie returns an independent copy of the given trie.
	CopyTrie(Trie) Trie

	// ContractCode retrieves a particular contract's code.
	ContractCode(addrHash, codeHash common.Hash) ([]byte, error)

	// ContractCodeSize retrieves a particular contracts code's size.
	ContractCodeSize(addrHash, codeHash common.Hash) (int, error)

	// TrieDB retrieves the low level trie database used for data storage.
	TrieDB() *trie.Database
}

Database wraps access to tries and contract code.

func NewDatabase

func NewDatabase(db ethdb.Database) Database

NewDatabase creates a backing store for state. The returned database is safe for concurrent use and retains cached trie nodes in memory. The pool is an optional intermediate trie-node memory pool between the low level storage layer and the high level trie abstraction.

type DumpOrderList

type DumpOrderList struct {
	Volume *big.Int
	Orders map[*big.Int]*big.Int
}

type OrderItem

type OrderItem struct {
	Quantity        *big.Int       `json:"quantity,omitempty"`
	Price           *big.Int       `json:"price,omitempty"`
	ExchangeAddress common.Address `json:"exchangeAddress,omitempty"`
	UserAddress     common.Address `json:"userAddress,omitempty"`
	BaseToken       common.Address `json:"baseToken,omitempty"`
	QuoteToken      common.Address `json:"quoteToken,omitempty"`
	Status          string         `json:"status,omitempty"`
	Side            string         `json:"side,omitempty"`
	Type            string         `json:"type,omitempty"`
	Hash            common.Hash    `json:"hash,omitempty"`
	TxHash          common.Hash    `json:"txHash,omitempty"`
	Signature       *Signature     `json:"signature,omitempty"`
	FilledAmount    *big.Int       `json:"filledAmount,omitempty"`
	Nonce           *big.Int       `json:"nonce,omitempty"`
	PairName        string         `json:"pairName,omitempty"`
	CreatedAt       time.Time      `json:"createdAt,omitempty"`
	UpdatedAt       time.Time      `json:"updatedAt,omitempty"`
	OrderID         uint64         `json:"orderID,omitempty"`
	// *OrderMeta
	NextOrder []byte `json:"-"`
	PrevOrder []byte `json:"-"`
	OrderList []byte `json:"-"`
	Key       string `json:"key"`
}

OrderItem : info that will be store in database

func (*OrderItem) ComputeOrderCancelHash

func (o *OrderItem) ComputeOrderCancelHash() common.Hash

func (*OrderItem) GetBSON

func (o *OrderItem) GetBSON() (interface{}, error)

func (*OrderItem) SetBSON

func (o *OrderItem) SetBSON(raw bson.Raw) error

func (*OrderItem) VerifyBasicOrderInfo

func (o *OrderItem) VerifyBasicOrderInfo() error

func (*OrderItem) VerifyOrder

func (o *OrderItem) VerifyOrder(state *state.StateDB) error

verify orderItem

type OrderItemBSON

type OrderItemBSON struct {
	Quantity        string           `json:"quantity,omitempty" bson:"quantity"`
	Price           string           `json:"price,omitempty" bson:"price"`
	ExchangeAddress string           `json:"exchangeAddress,omitempty" bson:"exchangeAddress"`
	UserAddress     string           `json:"userAddress,omitempty" bson:"userAddress"`
	BaseToken       string           `json:"baseToken,omitempty" bson:"baseToken"`
	QuoteToken      string           `json:"quoteToken,omitempty" bson:"quoteToken"`
	Status          string           `json:"status,omitempty" bson:"status"`
	Side            string           `json:"side,omitempty" bson:"side"`
	Type            string           `json:"type,omitempty" bson:"type"`
	Hash            string           `json:"hash,omitempty" bson:"hash"`
	TxHash          string           `json:"txHash,omitempty" bson:"txHash"`
	Signature       *SignatureRecord `json:"signature,omitempty" bson:"signature"`
	FilledAmount    string           `json:"filledAmount,omitempty" bson:"filledAmount"`
	Nonce           string           `json:"nonce,omitempty" bson:"nonce"`
	PairName        string           `json:"pairName,omitempty" bson:"pairName"`
	CreatedAt       time.Time        `json:"createdAt,omitempty" bson:"createdAt"`
	UpdatedAt       time.Time        `json:"updatedAt,omitempty" bson:"updatedAt"`
	OrderID         string           `json:"orderID,omitempty" bson:"orderID"`
	NextOrder       string           `json:"nextOrder,omitempty" bson:"nextOrder"`
	PrevOrder       string           `json:"prevOrder,omitempty" bson:"prevOrder"`
	OrderList       string           `json:"orderList,omitempty" bson:"orderList"`
	Key             string           `json:"key" bson:"key"`
}

type Signature

type Signature struct {
	V byte
	R common.Hash
	S common.Hash
}

Signature struct

func (*Signature) MarshalSignature

func (s *Signature) MarshalSignature() ([]byte, error)

MarshalSignature marshals the signature struct to []byte

func (*Signature) Verify

func (s *Signature) Verify(hash common.Hash) (common.Address, error)

Verify returns the address that corresponds to the given signature and signed message

type SignatureRecord

type SignatureRecord struct {
	V byte   `json:"V" bson:"V"`
	R string `json:"R" bson:"R"`
	S string `json:"S" bson:"S"`
}

type TomoXManagedState

type TomoXManagedState struct {
	*TomoXStateDB
	// contains filtered or unexported fields
}

func ManageState

func ManageState(statedb *TomoXStateDB) *TomoXManagedState

TomoXManagedState returns a new managed state with the statedb as it's backing layer

func (*TomoXManagedState) GetNonce

func (ms *TomoXManagedState) GetNonce(addr common.Hash) uint64

GetNonce returns the canonical nonce for the managed or unmanaged orderId.

Because GetNonce mutates the DB, we must take a write lock.

func (*TomoXManagedState) HasAccount

func (ms *TomoXManagedState) HasAccount(addr common.Hash) bool

HasAccount returns whether the given address is managed or not

func (*TomoXManagedState) NewNonce

func (ms *TomoXManagedState) NewNonce(addr common.Hash) uint64

NewNonce returns the new canonical nonce for the managed orderId

func (*TomoXManagedState) RemoveNonce

func (ms *TomoXManagedState) RemoveNonce(addr common.Hash, n uint64)

RemoveNonce removed the nonce from the managed state and all future pending nonces

func (*TomoXManagedState) SetNonce

func (ms *TomoXManagedState) SetNonce(addr common.Hash, nonce uint64)

SetNonce sets the new canonical nonce for the managed state

func (*TomoXManagedState) SetState

func (ms *TomoXManagedState) SetState(statedb *TomoXStateDB)

SetState sets the backing layer of the managed state

type TomoXStateDB

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

StateDBs within the ethereum protocol are used to store anything within the merkle trie. StateDBs take care of caching and storing nested states. It's the general query interface to retrieve: * Contracts * Accounts

func New

func New(root common.Hash, db Database) (*TomoXStateDB, error)

Create a new state from a given trie.

func (*TomoXStateDB) CancelOrder

func (self *TomoXStateDB) CancelOrder(orderBook common.Hash, order *OrderItem) error

func (*TomoXStateDB) Commit

func (s *TomoXStateDB) Commit() (root common.Hash, err error)

Commit writes the state to the underlying in-memory trie database.

func (*TomoXStateDB) Copy

func (self *TomoXStateDB) Copy() *TomoXStateDB

Copy creates a deep, independent copy of the state. Snapshots of the copied state cannot be applied to the copy.

func (*TomoXStateDB) Database

func (self *TomoXStateDB) Database() Database

Database retrieves the low level database supporting the lower level trie ops.

func (*TomoXStateDB) DumpAskTrie

func (self *TomoXStateDB) DumpAskTrie(orderBook common.Hash) (map[*big.Int]DumpOrderList, error)

func (*TomoXStateDB) DumpBidTrie

func (self *TomoXStateDB) DumpBidTrie(orderBook common.Hash) (map[*big.Int]DumpOrderList, error)

func (*TomoXStateDB) Empty

func (self *TomoXStateDB) Empty(addr common.Hash) bool

Empty returns whether the state object is either non-existent or empty according to the EIP161 specification (balance = nonce = code = 0)

func (*TomoXStateDB) Error

func (self *TomoXStateDB) Error() error

func (*TomoXStateDB) Exist

func (self *TomoXStateDB) Exist(addr common.Hash) bool

Exist reports whether the given orderId address exists in the state. Notably this also returns true for suicided exchanges.

func (*TomoXStateDB) Finalise

func (s *TomoXStateDB) Finalise()

Finalise finalises the state by removing the self destructed objects and clears the journal as well as the refunds.

func (*TomoXStateDB) GetBestAskPrice

func (self *TomoXStateDB) GetBestAskPrice(orderBook common.Hash) (*big.Int, *big.Int)

func (*TomoXStateDB) GetBestBidPrice

func (self *TomoXStateDB) GetBestBidPrice(orderBook common.Hash) (*big.Int, *big.Int)

func (*TomoXStateDB) GetBestOrderIdAndAmount

func (self *TomoXStateDB) GetBestOrderIdAndAmount(orderBook common.Hash, price *big.Int, side string) (common.Hash, *big.Int, error)

func (*TomoXStateDB) GetNonce

func (self *TomoXStateDB) GetNonce(addr common.Hash) uint64

func (*TomoXStateDB) GetOrNewStateExchangeObject

func (self *TomoXStateDB) GetOrNewStateExchangeObject(addr common.Hash) *stateExchanges

Retrieve a state object or create a new state object if nil.

func (*TomoXStateDB) GetOrder

func (self *TomoXStateDB) GetOrder(orderBook common.Hash, orderId common.Hash) OrderItem

func (*TomoXStateDB) GetPrice

func (self *TomoXStateDB) GetPrice(addr common.Hash) *big.Int

func (*TomoXStateDB) GetVolume

func (self *TomoXStateDB) GetVolume(orderBook common.Hash, price *big.Int, orderType string) *big.Int

func (*TomoXStateDB) InsertOrderItem

func (self *TomoXStateDB) InsertOrderItem(orderBook common.Hash, orderId common.Hash, order OrderItem)

func (*TomoXStateDB) IntermediateRoot

func (s *TomoXStateDB) IntermediateRoot() common.Hash

IntermediateRoot computes the current root hash of the state trie. It is called in between transactions to get the root hash that goes into transaction receipts.

func (*TomoXStateDB) MarkStateExchangeObjectDirty

func (self *TomoXStateDB) MarkStateExchangeObjectDirty(addr common.Hash)

MarkStateAskObjectDirty adds the specified object to the dirty map to avoid costly state object cache iteration to find a handful of modified ones.

func (*TomoXStateDB) RevertToSnapshot

func (self *TomoXStateDB) RevertToSnapshot(revid int)

RevertToSnapshot reverts all state changes made since the given revision.

func (*TomoXStateDB) SetNonce

func (self *TomoXStateDB) SetNonce(addr common.Hash, nonce uint64)

func (*TomoXStateDB) SetPrice

func (self *TomoXStateDB) SetPrice(addr common.Hash, price *big.Int)

func (*TomoXStateDB) Snapshot

func (self *TomoXStateDB) Snapshot() int

Snapshot returns an identifier for the current revision of the state.

func (*TomoXStateDB) SubAmountOrderItem

func (self *TomoXStateDB) SubAmountOrderItem(orderBook common.Hash, orderId common.Hash, price *big.Int, amount *big.Int, side string) error

type TomoXTrie

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

TomoXTrie wraps a trie with key hashing. In a secure trie, all access operations hash the key using keccak256. This prevents calling code from creating long chains of nodes that increase the access time.

Contrary to a regular trie, a TomoXTrie can only be created with New and must have an attached database. The database also stores the preimage of each key.

TomoXTrie is not safe for concurrent use.

func NewTomoXTrie

func NewTomoXTrie(root common.Hash, db *trie.Database, cachelimit uint16) (*TomoXTrie, error)

NewTomoXTrie creates a trie with an existing root node from a backing database and optional intermediate in-memory node pool.

If root is the zero hash or the sha3 hash of an empty string, the trie is initially empty. Otherwise, New will panic if db is nil and returns MissingNodeError if the root node cannot be found.

Accessing the trie loads nodes from the database or node pool on demand. Loaded nodes are kept around until their 'cache generation' expires. A new cache generation is created by each call to Commit. cachelimit sets the number of past cache generations to keep.

func (*TomoXTrie) Commit

func (t *TomoXTrie) Commit(onleaf trie.LeafCallback) (root common.Hash, err error)

Commit writes all nodes and the secure hash pre-images to the trie's database. Nodes are stored with their sha3 hash as the key.

Committing flushes nodes from memory. Subsequent Get calls will load nodes from the database.

func (*TomoXTrie) Copy

func (t *TomoXTrie) Copy() *TomoXTrie

func (*TomoXTrie) Delete

func (t *TomoXTrie) Delete(key []byte)

Delete removes any existing value for key from the trie.

func (*TomoXTrie) Get

func (t *TomoXTrie) Get(key []byte) []byte

Get returns the value for key stored in the trie. The value bytes must not be modified by the caller.

func (*TomoXTrie) GetKey

func (t *TomoXTrie) GetKey(shaKey []byte) []byte

GetKey returns the sha3 preimage of a hashed key that was previously used to store a value.

func (*TomoXTrie) Hash

func (t *TomoXTrie) Hash() common.Hash

func (*TomoXTrie) NodeIterator

func (t *TomoXTrie) NodeIterator(start []byte) trie.NodeIterator

NodeIterator returns an iterator that returns nodes of the underlying trie. Iteration starts at the key after the given start key.

func (*TomoXTrie) Prove

func (t *TomoXTrie) Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error

Prove constructs a merkle proof for key. The result contains all encoded nodes on the path to the value at key. The value itself is also included in the last node and can be retrieved by verifying the proof.

If the trie does not contain a value for key, the returned proof contains all nodes of the longest existing prefix of the key (at least the root node), ending with the node that proves the absence of the key.

func (*TomoXTrie) Root

func (t *TomoXTrie) Root() []byte

func (*TomoXTrie) TryDelete

func (t *TomoXTrie) TryDelete(key []byte) error

TryDelete removes any existing value for key from the trie. If a node was not found in the database, a MissingNodeError is returned.

func (*TomoXTrie) TryGet

func (t *TomoXTrie) TryGet(key []byte) ([]byte, error)

TryGet returns the value for key stored in the trie. The value bytes must not be modified by the caller. If a node was not found in the database, a MissingNodeError is returned.

func (*TomoXTrie) TryGetBestLeftKeyAndValue

func (t *TomoXTrie) TryGetBestLeftKeyAndValue() ([]byte, []byte, error)

TryGetBestLeftKey returns the value of max left leaf If a node was not found in the database, a MissingNodeError is returned.

func (*TomoXTrie) TryGetBestRightKeyAndValue

func (t *TomoXTrie) TryGetBestRightKeyAndValue() ([]byte, []byte, error)

TryGetBestRightKey returns the value of max left leaf If a node was not found in the database, a MissingNodeError is returned.

func (*TomoXTrie) TryUpdate

func (t *TomoXTrie) TryUpdate(key, value []byte) error

TryUpdate associates key with value in the trie. Subsequent calls to Get will return value. If value has length zero, any existing value is deleted from the trie and calls to Get will return nil.

The value bytes must not be modified by the caller while they are stored in the trie.

If a node was not found in the database, a MissingNodeError is returned.

func (*TomoXTrie) Update

func (t *TomoXTrie) Update(key, value []byte)

Update associates key with value in the trie. Subsequent calls to Get will return value. If value has length zero, any existing value is deleted from the trie and calls to Get will return nil.

The value bytes must not be modified by the caller while they are stored in the trie.

type Trie

type Trie interface {
	TryGet(key []byte) ([]byte, error)
	TryGetBestLeftKeyAndValue() ([]byte, []byte, error)
	TryGetBestRightKeyAndValue() ([]byte, []byte, error)
	TryUpdate(key, value []byte) error
	TryDelete(key []byte) error
	Commit(onleaf trie.LeafCallback) (common.Hash, error)
	Hash() common.Hash
	NodeIterator(startKey []byte) trie.NodeIterator
	GetKey([]byte) []byte // TODO(fjl): remove this when TomoXTrie is removed
	Prove(key []byte, fromLevel uint, proofDb ethdb.Putter) error
}

Trie is a Ethereum Merkle Trie.

Jump to

Keyboard shortcuts

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