state

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2023 License: AGPL-3.0 Imports: 28 Imported by: 1

Documentation

Index

Constants

View Source
const (
	TreeProcess                    = "Processes"
	TreeExtra                      = "Extra"
	TreeOracles                    = "Oracles"
	TreeValidators                 = "Validators"
	TreeAccounts                   = "Accounts"
	TreeFaucet                     = "FaucetNonce"
	ChildTreeCensus                = "Census"
	ChildTreeCensusPoseidon        = "CensusPoseidon"
	ChildTreePreRegisterNullifiers = "PreRegisterNullifiers"
	ChildTreeVotes                 = "Votes"
)

Variables

View Source
var (
	TxTypeCostToStateKey = map[models.TxType]string{
		models.TxType_SET_PROCESS_STATUS:         "c_setProcessStatus",
		models.TxType_SET_PROCESS_CENSUS:         "c_setProcessCensus",
		models.TxType_SET_PROCESS_QUESTION_INDEX: "c_setProcessResults",
		models.TxType_SET_PROCESS_RESULTS:        "c_setProcessQuestionIndex",
		models.TxType_REGISTER_VOTER_KEY:         "c_registerKey",
		models.TxType_NEW_PROCESS:                "c_newProcess",
		models.TxType_SEND_TOKENS:                "c_sendTokens",
		models.TxType_SET_ACCOUNT_INFO_URI:       "c_setAccountInfoURI",
		models.TxType_CREATE_ACCOUNT:             "c_createAccount",
		models.TxType_ADD_DELEGATE_FOR_ACCOUNT:   "c_addDelegateForAccount",
		models.TxType_DEL_DELEGATE_FOR_ACCOUNT:   "c_delDelegateForAccount",
		models.TxType_COLLECT_FAUCET:             "c_collectFaucet",
	}
	ErrTxCostNotFound = fmt.Errorf("transaction cost is not set")
)

TxTypeCostToStateKey translates models.TxType to a string which the State uses as a key internally under the Extra tree

View Source
var (
	ErrVoteNotFound         = fmt.Errorf("vote not found")
	ErrProcessNotFound      = fmt.Errorf("process not found")
	ErrAccountNonceInvalid  = fmt.Errorf("invalid account nonce")
	ErrAccountNotExist      = fmt.Errorf("account does not exist")
	ErrBalanceOverflow      = fmt.Errorf("balance overflow")
	ErrNotEnoughBalance     = fmt.Errorf("not enough balance to transfer")
	ErrAccountBalanceZero   = fmt.Errorf("zero balance account not valid")
	ErrAccountAlreadyExists = fmt.Errorf("account already exists")
	ErrInvalidURILength     = fmt.Errorf("invalid URI length")
)
View Source
var (
	// MainTrees contains the configuration for the singleton state trees
	MainTrees = map[string]statedb.TreeConfig{

		"Extra": statedb.NewTreeSingletonConfig(statedb.TreeParams{
			HashFunc:          arbo.HashFunctionSha256,
			KindID:            "xtra",
			MaxLevels:         256,
			ParentLeafGetRoot: rootLeafGetRoot,
			ParentLeafSetRoot: rootLeafSetRoot,
		}),

		"Oracles": statedb.NewTreeSingletonConfig(statedb.TreeParams{
			HashFunc:          arbo.HashFunctionSha256,
			KindID:            "oracs",
			MaxLevels:         256,
			ParentLeafGetRoot: rootLeafGetRoot,
			ParentLeafSetRoot: rootLeafSetRoot,
		}),

		"Validators": statedb.NewTreeSingletonConfig(statedb.TreeParams{
			HashFunc:          arbo.HashFunctionSha256,
			KindID:            "valids",
			MaxLevels:         256,
			ParentLeafGetRoot: rootLeafGetRoot,
			ParentLeafSetRoot: rootLeafSetRoot,
		}),

		"Processes": statedb.NewTreeSingletonConfig(statedb.TreeParams{
			HashFunc:          arbo.HashFunctionSha256,
			KindID:            "procs",
			MaxLevels:         256,
			ParentLeafGetRoot: rootLeafGetRoot,
			ParentLeafSetRoot: rootLeafSetRoot,
		}),

		"Accounts": statedb.NewTreeSingletonConfig(statedb.TreeParams{
			HashFunc:          arbo.HashFunctionSha256,
			KindID:            "balan",
			MaxLevels:         256,
			ParentLeafGetRoot: rootLeafGetRoot,
			ParentLeafSetRoot: rootLeafSetRoot,
		}),

		"FaucetNonce": statedb.NewTreeSingletonConfig(statedb.TreeParams{
			HashFunc:          arbo.HashFunctionSha256,
			KindID:            "faucet",
			MaxLevels:         256,
			ParentLeafGetRoot: rootLeafGetRoot,
			ParentLeafSetRoot: rootLeafSetRoot,
		}),
	}

	// ChildTrees contains the configuration for the state trees dependent on a main tree.
	ChildTrees = map[string]*statedb.TreeNonSingletonConfig{

		"Census": statedb.NewTreeNonSingletonConfig(statedb.TreeParams{
			HashFunc:          arbo.HashFunctionSha256,
			KindID:            "cen",
			MaxLevels:         256,
			ParentLeafGetRoot: processGetCensusRoot,
			ParentLeafSetRoot: processSetCensusRoot,
		}),

		"CensusPoseidon": statedb.NewTreeNonSingletonConfig(statedb.TreeParams{
			HashFunc:          arbo.HashFunctionPoseidon,
			KindID:            "cenPos",
			MaxLevels:         64,
			ParentLeafGetRoot: processGetCensusRoot,
			ParentLeafSetRoot: processSetCensusRoot,
		}),

		"PreRegisterNullifiers": statedb.NewTreeNonSingletonConfig(statedb.TreeParams{
			HashFunc:          arbo.HashFunctionSha256,
			KindID:            "prNul",
			MaxLevels:         256,
			ParentLeafGetRoot: processGetPreRegisterNullifiersRoot,
			ParentLeafSetRoot: processSetPreRegisterNullifiersRoot,
		}),

		"Votes": statedb.NewTreeNonSingletonConfig(statedb.TreeParams{
			HashFunc:          arbo.HashFunctionSha256,
			KindID:            "votes",
			MaxLevels:         256,
			ParentLeafGetRoot: processGetVotesRoot,
			ParentLeafSetRoot: processSetVotesRoot,
		}),
	}
)
View Source
var BurnAddress = common.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff")
View Source
var CensusOrigins = map[models.CensusOrigin]CensusProperties{
	models.CensusOrigin_OFF_CHAIN_TREE: {Name: "offchain tree",
		NeedsDownload: true, NeedsURI: true, AllowCensusUpdate: true},
	models.CensusOrigin_OFF_CHAIN_TREE_WEIGHTED: {
		Name: "offchain weighted tree", NeedsDownload: true, NeedsURI: true,
		WeightedSupport: true, AllowCensusUpdate: true,
	},
	models.CensusOrigin_ERC20: {Name: "erc20", NeedsDownload: true,
		WeightedSupport: true, NeedsIndexSlot: true},
	models.CensusOrigin_OFF_CHAIN_CA: {Name: "ca", WeightedSupport: true,
		NeedsURI: true, AllowCensusUpdate: true},
}
View Source
var (
	ErrProcessChildLeafRootUnknown = fmt.Errorf("process child leaf root is unkown")
)

Functions

func CheckDuplicateDelegates

func CheckDuplicateDelegates(delegates [][]byte, addr *ethcommon.Address) error

CheckDuplicateDelegates checks if the given delegates are not duplicated if addr is not nill will check if the addr is present in the delegates

func GenerateNullifier

func GenerateNullifier(address ethcommon.Address, processID []byte) []byte

GenerateNullifier generates the nullifier of a vote (hash(address+processId)) This function assumes address and processID are correct.

func GetFriendlyResults

func GetFriendlyResults(results []*models.QuestionResult) [][]*types.BigInt

GetFriendlyResults returns the results of a process in a human friendly format.

func StateChildTreeCfg

func StateChildTreeCfg(name string) *statedb.TreeNonSingletonConfig

StateChildTreeCfg returns the state merkle child tree with name.

func StateParentChildTreeCfg

func StateParentChildTreeCfg(parent, child string, key []byte) (statedb.TreeConfig, statedb.TreeConfig)

StateParentChildTreeCfg returns the parent and its child tree under the key leaf.

func StateTreeCfg

func StateTreeCfg(name string) statedb.TreeConfig

StateTreeCfg returns the state merkle tree with name.

Types

type Account

type Account struct {
	models.Account
}

Account represents an amount of tokens, usually attached to an address. Account includes a Nonce which needs to be incremented by 1 on each transfer, an external URI link for metadata and a list of delegated addresses allowed to use the account on its behalf (in addition to himself).

func (*Account) AddDelegate

func (a *Account) AddDelegate(addr common.Address) error

AddDelegate adds an address to the list of delegates for an account

func (*Account) DelDelegate

func (a *Account) DelDelegate(addr common.Address) error

DelDelegate removes an address from the list of delegates for an account

func (*Account) IsDelegate

func (a *Account) IsDelegate(addr common.Address) bool

IsDelegate checks if an address is a delegate for an account

func (*Account) Marshal

func (a *Account) Marshal() ([]byte, error)

Marshal encodes the Account and returns the serialized bytes.

func (*Account) Transfer

func (a *Account) Transfer(dest *Account, amount uint64) error

Transfer moves amount from the origin Account to the dest Account.

func (*Account) Unmarshal

func (a *Account) Unmarshal(data []byte) error

Unmarshal decode a set of bytes.

type CensusProperties

type CensusProperties struct {
	Name              string
	AllowCensusUpdate bool
	NeedsDownload     bool
	NeedsIndexSlot    bool
	NeedsURI          bool
	WeightedSupport   bool
}

type ErrHaltVochain

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

func (ErrHaltVochain) Error

func (e ErrHaltVochain) Error() string

func (ErrHaltVochain) Unwrap

func (e ErrHaltVochain) Unwrap() error

type EventListener

type EventListener interface {
	OnVote(vote *Vote, txIndex int32)
	OnNewTx(tx *vochaintx.VochainTx, blockHeight uint32, txIndex int32)
	OnProcess(pid, eid []byte, censusRoot, censusURI string, txIndex int32)
	OnProcessStatusChange(pid []byte, status models.ProcessStatus, txIndex int32)
	OnCancel(pid []byte, txIndex int32)
	OnProcessKeys(pid []byte, encryptionPub string, txIndex int32)
	OnRevealKeys(pid []byte, encryptionPriv string, txIndex int32)
	OnProcessResults(pid []byte, results *models.ProcessResult, txIndex int32)
	OnProcessesStart(pids [][]byte)
	OnSetAccount(addr []byte, account *Account)
	OnTransferTokens(tx *vochaintx.TokenTransfer)
	Commit(height uint32) (err error)
	Rollback()
}

EventListener is an interface used for executing custom functions during the events of the block creation process. The order in which events are executed is: Rollback, OnVote, Onprocess, On..., Commit. The process is concurrency safe, meaning that there cannot be two sequences happening in parallel.

If Commit() returns ErrHaltVochain, the error is considered a consensus failure and the blockchain will halt.

If OncProcessResults() returns an error, the results transaction won't be included in the blockchain. This event relays on the event handlers to decide if results are valid or not since the Vochain State do not validate results.

type RollingCensus

type RollingCensus struct {
	CensusID string
	DumpData []byte
	DumpRoot []byte
	// IndexKeys [][]byte
	Type models.Census_Type
}

type SnapshotHeader

type SnapshotHeader struct {
	Version int
	Root    []byte
	ChainID string
	Height  uint32
	Trees   []SnapshotHeaderTree
}

SnapshotHeader is the header structure of StateSnapshot containing the list of merkle trees.

type SnapshotHeaderTree

type SnapshotHeaderTree struct {
	Name   string
	Size   uint32
	Parent string
	Root   []byte
}

SnapshotHeaderTree represents a merkle tree of the StateSnapshot.

type State

type State struct {

	// Store contains the StateDB.  We match every StateDB commit version
	// with the block height.
	Store *statedb.StateDB

	// Tx must always be accessed via mutex because there will be
	// concurrent operations on it.  In particular, while the Tx is being
	// written serially via Tendermint DeliverTx (which updates the StateDB
	// by processing Vochain transactions), parallel calls of Tendermint
	// CheckTx happen (which read the temporary state kept in the Tx to
	// validate Vochain transactions).
	Tx treeTxWithMutex

	DisableVoteCache atomic.Bool
	// contains filtered or unexported fields
}

State represents the state of the vochain application

func NewState

func NewState(dbType, dataDir string) (*State, error)

NewState creates a new State

func (*State) AccountFromSignature

func (v *State) AccountFromSignature(message, signature []byte) (*common.Address, *Account, error)

AccountFromSignature extracts an address from a signed message and returns an account if exists

func (*State) AddEventListener

func (v *State) AddEventListener(l EventListener)

AddEventListener adds a new event listener, to receive method calls on block events as documented in EventListener.

func (*State) AddOracle

func (v *State) AddOracle(address common.Address) error

AddOracle adds a trusted oracle given its address if not exists

func (*State) AddProcess

func (v *State) AddProcess(p *models.Process) error

AddProcess adds a new process to the vochain. Adding a process with a ProcessId that already exists will return an error.

func (*State) AddProcessKeys

func (v *State) AddProcessKeys(tx *models.AdminTx) error

AddProcessKeys adds the keys to the process

func (*State) AddToRollingCensus

func (v *State) AddToRollingCensus(pid []byte, key []byte, weight *big.Int) error

AddToRollingCensus adds a new key to an existing rolling census. NOTE: weight value is not used.

func (*State) AddValidator

func (v *State) AddValidator(validator *models.Validator) error

AddValidator adds a tendemint validator if it is not already added

func (*State) AddVote

func (s *State) AddVote(vote *Vote) error

AddVote adds a new vote to a process and call the even listeners to OnVote. If the vote already exists it will be overwritten and overwrite counter will be increased. Note that the vote is not committed to the StateDB until the StateDB transaction is committed. Note that the vote is not verified, so it is the caller responsibility to verify the vote.

func (*State) BurnTxCost

func (v *State) BurnTxCost(from common.Address, cost uint64) error

BurnTxCost burns the cost of a transaction if cost is set to 0 just return

func (*State) BurnTxCostIncrementNonce

func (v *State) BurnTxCostIncrementNonce(accountAddress common.Address, txType models.TxType) error

BurnTxCostIncrementNonce reduces the transaction cost from the account balance and increments nonce

func (*State) CacheAdd

func (v *State) CacheAdd(id [32]byte, vote *Vote)

CacheAdd adds a new vote proof to the local cache

func (*State) CacheDel

func (v *State) CacheDel(id [32]byte)

CacheDel deletes an existing vote proof from the local cache

func (*State) CacheGet

func (v *State) CacheGet(id [32]byte) *Vote

CacheGet fetch an existing vote from the local cache and returns it.

func (*State) CacheGetCopy

func (v *State) CacheGetCopy(id [32]byte) *Vote

CacheGetCopy fetch an existing vote from the local cache and returns a copy which is thread-safe for writing.

func (*State) CacheHasNullifier

func (v *State) CacheHasNullifier(nullifier []byte) bool

CacheHasNullifier fetch an existing vote from the local cache.

func (*State) CachePurge

func (v *State) CachePurge(height uint32)

CachePurge removes the old cache saved votes

func (*State) CacheSize

func (v *State) CacheSize() int

CacheSize returns the current size of the vote cache

func (*State) CancelProcess

func (v *State) CancelProcess(pid []byte) error

CancelProcess sets the process canceled attribute to true

func (*State) ChainID

func (v *State) ChainID() string

ChainID gets the blockchain identifier.

func (*State) CleanEventListeners

func (v *State) CleanEventListeners()

CleanEventListeners removes all event listeners.

func (*State) Close

func (v *State) Close() error

func (*State) ConsumeFaucetPayload

func (v *State) ConsumeFaucetPayload(from common.Address, faucetPayload *models.FaucetPayload) error

ConsumeFaucetPayload consumes a given faucet payload storing its key to the FaucetNonce tree so it can only be used once

func (*State) CountProcesses

func (v *State) CountProcesses(committed bool) (uint64, error)

CountProcesses returns the overall number of processes the vochain has

func (*State) CountVotes

func (v *State) CountVotes(processID []byte, committed bool) (uint64, error)

CountVotes returns the number of votes registered for a given process id When committed is false, the operation is executed also on not yet commited data from the currently open StateDB transaction. When committed is true, the operation is executed on the last commited version.

func (*State) CreateAccount

func (v *State) CreateAccount(accountAddress common.Address, infoURI string, delegates [][]byte, initialBalance uint64) error

CreateAccount creates an account

func (*State) CurrentHeight

func (v *State) CurrentHeight() uint32

CurrentHeight returns the current state height (block count).

func (*State) DumpRollingCensus

func (v *State) DumpRollingCensus(pid []byte) (*RollingCensus, error)

func (*State) EnvelopeList

func (v *State) EnvelopeList(processID []byte, from, listSize int,
	committed bool) (nullifiers [][]byte)

EnvelopeList returns a list of registered envelopes nullifiers given a processId When committed is false, the operation is executed also on not yet commited data from the currently open StateDB transaction. When committed is true, the operation is executed on the last commited version.

func (*State) EventListeners

func (v *State) EventListeners() []EventListener

EventListeners returns the list of subscribed event listeners.

func (*State) FaucetNonce

func (v *State) FaucetNonce(key []byte, committed bool) (bool, error)

FaucetNonce returns true if the key is found in the subtree key == hash(address, nonce) committed is relative to the state on which the function is executed

func (*State) GetAccount

func (v *State) GetAccount(address common.Address, committed bool) (*Account, error)

GetAccount retrieves the Account for an address. Returns a nil account and no error if the account does not exist. Committed is relative to the state on which the function is executed.

func (*State) GetPreRegisterAddrUsedWeight

func (v *State) GetPreRegisterAddrUsedWeight(pid []byte, addr common.Address) (*big.Int, error)

GetPreRegisterAddrUsedWeight returns the weight used by the address for a process ID on pre-register census

func (*State) GetProcessResults

func (v *State) GetProcessResults(pid []byte) ([][]*types.BigInt, error)

GetProcessResults returns a friendly representation of the results stored in the State (if any).

func (*State) GetRollingCensusRoot

func (v *State) GetRollingCensusRoot(pid []byte, committed bool) ([]byte, error)

GetRollingCensusRoot returns the last rolling census root for a process id

func (*State) GetRollingCensusSize

func (v *State) GetRollingCensusSize(pid []byte, committed bool) (uint64, error)

func (*State) IncrementAccountProcessIndex

func (v *State) IncrementAccountProcessIndex(accountAddress common.Address) error

IncrementAccountProcessIndex increments the process index by one and stores the value

func (*State) IncrementTreasurerNonce

func (v *State) IncrementTreasurerNonce() error

IncrementTreasurerNonce increments the treasurer nonce

func (*State) InitChainMintBalance

func (v *State) InitChainMintBalance(to common.Address, amount uint64) error

func (*State) IsOracle

func (v *State) IsOracle(addr common.Address) (bool, error)

IsOracle returns true if the address is a valid oracle

func (*State) IsTreasurer

func (v *State) IsTreasurer(addr common.Address) (bool, error)

IsTreasurer returns true if the given address matches the Treasurer address

func (*State) IterateVotes

func (v *State) IterateVotes(processID []byte, committed bool, callback func(vote *models.StateDBVote) bool) error

IterateVotes iterates over all the votes of a process. The callback function is executed for each vote. Once the callback returns true, the iteration stops.

func (*State) LastHeight

func (v *State) LastHeight() (uint32, error)

LastHeight returns the last commited height (block count). We match the StateDB Version with the height via the Commits done in Save.

func (*State) ListProcessIDs

func (v *State) ListProcessIDs(committed bool) ([][]byte, error)

ListProcessIDs returns the full list of process identifiers (pid).

func (*State) ListSnapshots

func (v *State) ListSnapshots() []diskSnapshotInfo

ListSnapshots returns the list of the current state snapshots stored in disk.

func (*State) MainTreeView

func (v *State) MainTreeView() *statedb.TreeView

MainTreeView is a thread-safe function to obtain a pointer to the last opened mainTree as a TreeView.

func (*State) MaxProcessSize added in v1.6.0

func (v *State) MaxProcessSize() (uint64, error)

MaxProcessSize returns the global maximum number voters allowed in an election.

func (*State) MintBalance

func (v *State) MintBalance(tx *vochaintx.TokenTransfer) error

MintBalance increments the existing acc of address by amount

func (*State) Oracles

func (v *State) Oracles(committed bool) ([]common.Address, error)

Oracles returns the current oracles list When committed is false, the operation is executed also on not yet commited data from the currently open StateDB transaction. When committed is true, the operation is executed on the last commited version.

func (*State) Process

func (v *State) Process(pid []byte, committed bool) (*models.Process, error)

Process returns a process info given a processId if exists

func (*State) PurgeRollingCensus

func (s *State) PurgeRollingCensus(pid []byte) error

PurgeRollingCensus removes a rolling census from the permanent store If the census does not exist, it does nothing.

func (*State) RemoveOracle

func (v *State) RemoveOracle(address common.Address) error

RemoveOracle removes a trusted oracle given its address if exists

func (*State) RemoveValidator

func (v *State) RemoveValidator(address []byte) error

RemoveValidator removes a tendermint validator identified by its address

func (*State) RevealProcessKeys

func (v *State) RevealProcessKeys(tx *models.AdminTx) error

RevealProcessKeys reveals the keys of a process

func (*State) Rollback

func (v *State) Rollback()

Rollback rollbacks to the last persistent db data version

func (*State) Save

func (v *State) Save() ([]byte, error)

Save persistent save of vochain mem trees. It returns the new root hash. It also notifies the event listeners.

func (*State) SetAccount

func (v *State) SetAccount(accountAddress common.Address, account *Account) error

SetAccount sets the given account data to the state

func (*State) SetAccountDelegate

func (v *State) SetAccountDelegate(accountAddr common.Address,
	delegateAddrs [][]byte,
	txType models.TxType) error

SetAccountDelegate sets a set of delegates for a given account

func (*State) SetAccountInfoURI

func (v *State) SetAccountInfoURI(accountAddress common.Address, infoURI string) error

SetAccountInfoURI sets a given account infoURI

func (*State) SetCacheSize

func (v *State) SetCacheSize(size int)

SetCacheSize sets the size for the vote LRU cache.

func (*State) SetChainID

func (v *State) SetChainID(chID string)

SetChainID sets the blockchain identifier.

func (*State) SetFaucetNonce

func (v *State) SetFaucetNonce(key []byte) error

SetFaucetNonce stores an already used faucet nonce in the FaucetNonce subtree

func (*State) SetHeight

func (v *State) SetHeight(height uint32)

SetHeight sets the height for the current block.

func (*State) SetMaxProcessSize added in v1.6.0

func (v *State) SetMaxProcessSize(size uint64) error

SetMaxProcessSize sets the global maximum number voters allowed in an election.

func (*State) SetPreRegisterAddrUsedWeight

func (v *State) SetPreRegisterAddrUsedWeight(pid []byte, addr common.Address, weight *big.Int) error

SetPreRegisterAddrUsedWeight sets the used weight for a pre-register address.

func (*State) SetProcessCensus

func (v *State) SetProcessCensus(pid, censusRoot []byte, censusURI string, commit bool) error

SetProcessCensus sets the census for a given process, only if that process enables dynamic census

func (*State) SetProcessResults

func (v *State) SetProcessResults(pid []byte, result *models.ProcessResult, commit bool) error

SetProcessResults sets the results for a given process

func (*State) SetProcessStatus

func (v *State) SetProcessStatus(pid []byte, newstatus models.ProcessStatus, commit bool) error

SetProcessStatus changes the process status to the one provided. One of ready, ended, canceled, paused, results. Transition checks are handled inside this function, so the caller does not need to worry about it.

func (*State) SetTreasurer

func (v *State) SetTreasurer(address common.Address, nonce uint32) error

SetTreasurer saves the Treasurer address to the state

func (*State) SetTxCost

func (v *State) SetTxCost(txType models.TxType, cost uint64) error

SetTxCost sets the given transaction cost

func (*State) Snapshot

func (v *State) Snapshot() (string, error)

Snapshot performs a snapshot of the last committed state for all trees. The snapshot is stored in disk and the file path is returned.

func (*State) TransferBalance

func (v *State) TransferBalance(tx *vochaintx.TokenTransfer, burnTxCost bool) error

TransferBalance transfers balance from origin address to destination address, and updates the state with the new values (including nonce). If origin address acc is not enough, ErrNotEnoughBalance is returned.

func (*State) Treasurer

func (v *State) Treasurer(committed bool) (*models.Treasurer, error)

Treasurer returns the address and the Treasurer nonce When committed is false, the operation is executed also on not yet commited data from the currently open StateDB transaction. When committed is true, the operation is executed on the last commited version.

func (*State) TxCost

func (v *State) TxCost(txType models.TxType, committed bool) (uint64, error)

TxCost returns the cost of a given transaction When committed is false, the operation is executed also on not yet commited data from the currently open StateDB transaction. When committed is true, the operation is executed on the last commited version.

func (*State) TxCounter

func (v *State) TxCounter() int32

TxCounter returns the current tx count

func (*State) TxCounterAdd

func (v *State) TxCounterAdd()

TxCounterAdd adds to the atomic transaction counter

func (*State) UpdateProcess

func (v *State) UpdateProcess(p *models.Process, pid []byte) error

UpdateProcess updates an existing process

func (*State) Validator

func (v *State) Validator(address common.Address, committed bool) (*models.Validator, error)

Validator returns an existing validator identified by the given signing address. If the validator is not found, returns nil and no error.

func (*State) Validators

func (v *State) Validators(committed bool) (map[string]*models.Validator, error)

Validators returns a list of the chain validators When committed is false, the operation is executed also on not yet commited data from the currently open StateDB transaction. When committed is true, the operation is executed on the last commited version.

func (*State) VerifyTreasurer

func (v *State) VerifyTreasurer(addr common.Address, txNonce uint32) error

VerifyTreasurer checks is an address is the treasurer and the nonce provided is the expected one

func (*State) Vote

func (v *State) Vote(processID, nullifier []byte, committed bool) (*models.StateDBVote, error)

Vote returns the stored vote if exists. Returns ErrProcessNotFound if the process does not exist, ErrVoteNotFound if the vote does not exist. When committed is false, the operation is executed also on not yet commited data from the currently open StateDB transaction. When committed is true, the operation is executed on the last commited version.

func (*State) VoteCount

func (v *State) VoteCount(committed bool) (uint64, error)

VoteCount return the global vote count. When committed is false, the operation is executed also on not yet commited data from the currently open StateDB transaction. When committed is true, the operation is executed on the last commited version.

func (*State) VoteExists

func (v *State) VoteExists(processID, nullifier []byte, committed bool) (bool, error)

VoteExists returns true if the envelope identified with voteID exists When committed is false, the operation is executed also on not yet commited data from the currently open StateDB transaction. When committed is true, the operation is executed on the last commited version.

func (*State) WorkingHash

func (v *State) WorkingHash() []byte

WorkingHash returns the hash of the vochain StateDB (mainTree.Root)

type StateSnapshot

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

A StateSnapshot is a copy in a specific point in time of the blockchain state. The state is supposed to be a list of nested merkle trees. The StateSnapshot contains the methods for building a single file snapshot of the state containing multiple trees. The implementation allows the encoding and decoding of snapshots.

The structure of the snapshot encoded file is:

[headerLen][header][tree1][tree2][treeN]

- headerlen is a fixed 32 bytes little endian number indicating the size of the header.

- header is the Gob encoded structure containing the information of the trees (size, name, etc.).

- treeN is the raw bytes dump of all trees.

func (*StateSnapshot) AddTree

func (s *StateSnapshot) AddTree(name, parent string, root []byte)

AddTree adds a new tree to the snapshot. `Create` needs to be called first.

func (*StateSnapshot) Create

func (s *StateSnapshot) Create(filePath string) error

Create starts the creation of a new snapshot as a disk file. This method must be called only once and its operation is oposed to `Open`.

func (*StateSnapshot) EndTree

func (s *StateSnapshot) EndTree()

EndTree finishes the addition of a tree. This method should be called after `AddTree`.

func (*StateSnapshot) FetchNextTree

func (s *StateSnapshot) FetchNextTree() error

FetchNextTree prepares everything for reading the next tree. Returns io.EOF when there are no more trees.

func (*StateSnapshot) Header

func (s *StateSnapshot) Header() *SnapshotHeader

Header returns the header for the snapshot containing the information about all the merkle trees.

func (*StateSnapshot) Open

func (s *StateSnapshot) Open(filePath string) error

Open reads an existing snapshot file and decodes the header. After calling this method everything is ready for reading the first merkle tree. No need to execute `FetchNextTree` until io.EOF is reached.

This method performs the opposite operation of `Create`, one of both needs to be called (but not both).

func (*StateSnapshot) Path

func (s *StateSnapshot) Path() string

Path returns the file path of the snapshot file currently used.

func (*StateSnapshot) Read

func (s *StateSnapshot) Read(b []byte) (int, error)

Read implements the io.Reader interface. Returns io.EOF error when no more bytes available in the current three.

func (*StateSnapshot) ReadAll

func (s *StateSnapshot) ReadAll() ([]byte, error)

ReadAll reads the full content of the current tree and returns its bytes. io.EOF error is returned if the bytes have been already read.

func (*StateSnapshot) Save

func (s *StateSnapshot) Save() error

Save builds the snapshot started with `Create` and stores in disk its contents. After calling this method the snapshot is finished. `EndTree` must be called before saving.

func (*StateSnapshot) SetChainID

func (s *StateSnapshot) SetChainID(chainID string)

SetChainID sets the blockchain identifier for the snapshot.

func (*StateSnapshot) SetHeight

func (s *StateSnapshot) SetHeight(height uint32)

SetHeight sets the blockchain height for the snapshot.

func (*StateSnapshot) SetMainRoot

func (s *StateSnapshot) SetMainRoot(root []byte)

SetMainRoot sets the root for the mail merkle tree of the state.

func (*StateSnapshot) TreeHeader

func (s *StateSnapshot) TreeHeader() *SnapshotHeaderTree

TreeHeader returns the header for the current tree.

func (*StateSnapshot) Write

func (s *StateSnapshot) Write(b []byte) (int, error)

Write implements the io.Writer interface. Writes a chunck of bytes as part of the current merkle tree.

type Vote

type Vote struct {
	ProcessID            types.HexBytes
	Nullifier            types.HexBytes
	Height               uint32
	VotePackage          []byte
	EncryptionKeyIndexes []uint32
	Weight               *big.Int
	VoterID              VoterID
	Overwrites           uint32
}

Vote represents a vote in the Vochain state.

func (*Vote) DeepCopy

func (v *Vote) DeepCopy() *Vote

DeepCopy returns a deep copy of the Vote struct.

func (*Vote) Hash

func (v *Vote) Hash() []byte

Hash returns the hash of the vote. Only the fields that are an essential part of the vote are hashed.

func (*Vote) WeightBytes

func (v *Vote) WeightBytes() []byte

WeightBytes returns the vote weight as a byte slice. If the weight is nil, it returns a byte slice of 1.

type VoterID

type VoterID []byte

VoterID is the indentifier of a voter. The first byte of the slice indicates one of the supported identifiers For example for an Ethereum public key the VoterID is [1, pubkb0, pubkb1, ...] where pubkb0 is the first byte of the Ethereum public key

func (VoterID) Address

func (v VoterID) Address() ([]byte, error)

Address returns the voterID Address depending on the VoterIDType

func (VoterID) IsNil

func (v VoterID) IsNil() bool

IsNil returns true if the VoterID is empty

func (VoterID) Nil

func (v VoterID) Nil() []byte

Nil returns the default value for VoterID which is a non-nil slice

func (VoterID) Type

func (v VoterID) Type() VoterIDType

Type returns the VoterID type defined in VoterIDTypeName

func (VoterID) VoterIDTypeToString

func (v VoterID) VoterIDTypeToString() string

VoterIDTypeToString returns the string representation of the VoterIDType

type VoterIDType

type VoterIDType = uint8

VoterIDType represents the type of a voterID

const (
	VoterIDTypeUndefined VoterIDType = 0
	VoterIDTypeECDSA     VoterIDType = 1
)

Jump to

Keyboard shortcuts

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