Documentation ¶
Index ¶
- Constants
- Variables
- func CheckDuplicateDelegates(delegates [][]byte, addr *ethcommon.Address) error
- func ExportNoStateDB(w io.Writer, reader *NoState) (uint32, error)
- func GenerateNullifier(address ethcommon.Address, processID []byte) []byte
- func GetFriendlyResults(results []*models.QuestionResult) [][]*types.BigInt
- func ImportNoStateDB(r io.Reader, db *NoState) error
- func StateChildTreeCfg(name string) *statedb.TreeNonSingletonConfig
- func StateParentChildTreeCfg(parent, child string, key []byte) (statedb.TreeConfig, statedb.TreeConfig)
- func StateTreeCfg(name string) statedb.TreeConfig
- type Account
- func (a *Account) AddDelegate(addr common.Address) error
- func (a *Account) DelDelegate(addr common.Address) error
- func (a *Account) IsDelegate(addr common.Address) bool
- func (a *Account) Marshal() ([]byte, error)
- func (a *Account) Transfer(dest *Account, amount uint64) error
- func (a *Account) Unmarshal(data []byte) error
- type BeginBlock
- type CensusProperties
- type DBPair
- type DiskSnapshotInfo
- type EventListener
- type NoState
- type ProcessBlockRegistry
- func (pbr *ProcessBlockRegistry) DeleteStartBlock(pid []byte) error
- func (pbr *ProcessBlockRegistry) MaxEndBlock(fromBlock uint32) (uint32, error)
- func (pbr *ProcessBlockRegistry) MinStartBlock(fromBlock uint32) (uint32, error)
- func (pbr *ProcessBlockRegistry) SetStartBlock(pid []byte, startBlock uint32) error
- type SIK
- type SnapshotHeader
- type SnapshotHeaderTree
- type State
- func (v *State) AccountFromSignature(message, signature []byte) (*common.Address, *Account, error)
- func (v *State) AddEventListener(l EventListener)
- func (v *State) AddProcess(p *models.Process) error
- func (v *State) AddProcessKeys(tx *models.AdminTx) error
- func (v *State) AddValidator(validator *models.Validator) error
- func (s *State) AddVote(vote *Vote) error
- func (v *State) AssignSIKToElection(pid []byte, address common.Address) error
- func (v *State) BurnTxCost(from common.Address, cost uint64) error
- func (v *State) BurnTxCostIncrementNonce(accountAddress common.Address, txType models.TxType, cost uint64, ...) error
- func (v *State) CacheAdd(id [32]byte, vote *Vote)
- func (v *State) CacheDel(id [32]byte)
- func (v *State) CacheGet(id [32]byte) *Vote
- func (v *State) CacheGetCopy(id [32]byte) *Vote
- func (v *State) CacheHasNullifier(nullifier []byte) bool
- func (v *State) CachePurge(height uint32)
- func (v *State) CacheSize() int
- func (v *State) CancelProcess(pid []byte) error
- func (v *State) ChainID() string
- func (v *State) CleanEventListeners()
- func (v *State) Close() error
- func (v *State) CommittedHash() []byte
- func (v *State) ConsumeFaucetPayload(from common.Address, faucetPayload *models.FaucetPayload) error
- func (v *State) CountAccounts(committed bool) (uint64, error)
- func (v *State) CountProcesses(committed bool) (uint64, error)
- func (v *State) CountRegisterSIK(pid []byte) (uint32, error)
- func (v *State) CountSIKs(committed bool) (uint64, error)
- func (s *State) CountTotalVotes() (uint64, error)
- func (s *State) CountVotes(processID []byte, committed bool) (uint64, error)
- func (v *State) CreateAccount(accountAddress common.Address, infoURI string, delegates [][]byte, ...) error
- func (v *State) CurrentHeight() uint32
- func (s *State) EnvelopeList(processID []byte, from, listSize int, committed bool) (nullifiers [][]byte)
- func (v *State) EventListeners() []EventListener
- func (v *State) ExpiredSIKRoot(candidateRoot []byte) bool
- func (v *State) FaucetNonce(key []byte, committed bool) (bool, error)
- func (v *State) FetchValidSIKRoots() error
- func (v *State) GetAccount(address common.Address, committed bool) (*Account, error)
- func (v *State) GetProcessResults(pid []byte) ([][]*types.BigInt, error)
- func (v *State) IncreaseRegisterSIKCounter(pid []byte) error
- func (v *State) IncrementAccountProcessIndex(accountAddress common.Address) error
- func (v *State) InitChainMintBalance(to common.Address, amount uint64) error
- func (v *State) InvalidateSIK(address common.Address) error
- func (s *State) IterateVotes(processID []byte, committed bool, callback func(vote *models.StateDBVote) bool) error
- func (v *State) LastHeight() (uint32, error)
- func (v *State) ListProcessIDs(committed bool) ([][]byte, error)
- func (v *State) ListSnapshots() []DiskSnapshotInfo
- func (v *State) MainTreeView() *statedb.TreeView
- func (v *State) MaxProcessSize() (uint64, error)
- func (v *State) MintBalance(tx *vochaintx.TokenTransfer) error
- func (v *State) NetworkCapacity() (uint64, error)
- func (s *State) NoState(withTxLock bool) *NoState
- func (v *State) OnBeginBlock(bb BeginBlock)
- func (v *State) PrepareCommit() ([]byte, error)
- func (v *State) Process(pid []byte, committed bool) (*models.Process, error)
- func (v *State) PurgeRegisterSIK(pid []byte) error
- func (v *State) PurgeSIKsByElection(pid []byte) error
- func (v *State) RemoveValidator(validator *models.Validator) error
- func (v *State) RevealProcessKeys(tx *models.AdminTx) error
- func (v *State) Rollback()
- func (v *State) SIKFromAddress(address common.Address) (SIK, error)
- func (v *State) SIKGenProof(address common.Address) ([]byte, []byte, error)
- func (v *State) SIKRoot() ([]byte, error)
- func (v *State) Save() ([]byte, error)
- func (v *State) SetAccount(accountAddress common.Address, account *Account) error
- func (v *State) SetAccountDelegate(accountAddr common.Address, delegateAddrs [][]byte, txType models.TxType) error
- func (v *State) SetAccountInfoURI(accountAddress common.Address, infoURI string) error
- func (v *State) SetAddressSIK(address common.Address, newSIK SIK) error
- func (v *State) SetCacheSize(size int)
- func (v *State) SetChainID(chID string)
- func (v *State) SetElectionPriceCalc() error
- func (v *State) SetFaucetNonce(key []byte) error
- func (v *State) SetHeight(height uint32)
- func (v *State) SetMaxProcessSize(size uint64) error
- func (v *State) SetNetworkCapacity(capacity uint64) error
- func (v *State) SetProcessCensus(pid, censusRoot []byte, censusURI string, commit bool) error
- func (v *State) SetProcessResults(pid []byte, result *models.ProcessResult) error
- func (v *State) SetProcessStatus(pid []byte, newstatus models.ProcessStatus, commit bool) error
- func (v *State) SetTxBaseCost(txType models.TxType, cost uint64) error
- func (v *State) Snapshot() (string, error)
- func (v *State) TransferBalance(tx *vochaintx.TokenTransfer, burnTxCost bool) error
- func (v *State) TxBaseCost(txType models.TxType, committed bool) (uint64, error)
- func (v *State) TxCounter() int32
- func (v *State) TxCounterAdd()
- func (v *State) UpdateProcess(p *models.Process, pid []byte) error
- func (v *State) UpdateSIKRoots() error
- func (v *State) ValidSIKRoots() [][]byte
- func (v *State) Validator(address common.Address, committed bool) (*models.Validator, error)
- func (v *State) Validators(committed bool) (map[string]*models.Validator, error)
- func (s *State) Vote(processID, nullifier []byte, committed bool) (*models.StateDBVote, error)
- func (s *State) VoteExists(processID, nullifier []byte, committed bool) (bool, error)
- type StateSnapshot
- func (s *StateSnapshot) AddTree(name, parent string, root []byte)
- func (s *StateSnapshot) Create(filePath string) error
- func (s *StateSnapshot) EndTree()
- func (s *StateSnapshot) FetchNextTree() error
- func (s *StateSnapshot) Header() *SnapshotHeader
- func (s *StateSnapshot) Open(filePath string) error
- func (s *StateSnapshot) Path() string
- func (s *StateSnapshot) Read(b []byte) (int, error)
- func (s *StateSnapshot) ReadAll() ([]byte, error)
- func (s *StateSnapshot) Save() error
- func (s *StateSnapshot) SetChainID(chainID string)
- func (s *StateSnapshot) SetHeight(height uint32)
- func (s *StateSnapshot) SetMainRoot(root []byte)
- func (s *StateSnapshot) SetNoStateSize(size uint32)
- func (s *StateSnapshot) TreeHeader() *SnapshotHeaderTree
- func (s *StateSnapshot) Write(b []byte) (int, error)
- type Vote
- type VotePackage
- type VoterID
- type VoterIDType
Constants ¶
const ( TreeProcess = "Processes" TreeExtra = "Extra" TreeValidators = "Validators" TreeAccounts = "Accounts" TreeFaucet = "FaucetNonce" TreeSIK = "CensusSIK" ChildTreeVotes = "Votes" )
const ( // SIKROOT_HYSTERESIS_BLOCKS constant defines the number of blocks that the // vochain will consider a sikRoot valid. In this way, any new sikRoot will be // valid for at least for this number of blocks. If the gap between the last // two valid roots is greater than the value of this constant, the oldest will // be valid until a new sikroot is calculated. // TODO: Move the definition to the right place SIKROOT_HYSTERESIS_BLOCKS = 32 )
Variables ¶
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_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", models.TxType_SET_ACCOUNT_SIK: "c_setAccountSIK", models.TxType_DEL_ACCOUNT_SIK: "c_delAccountSIK", models.TxType_REGISTER_SIK: "c_registerSIK", models.TxType_SET_ACCOUNT_VALIDATOR: "c_setAccountValidator", } 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
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") ErrRegisteredValidSIK = fmt.Errorf("address already has a valid sik") ErrSIKAlreadyInvalid = fmt.Errorf("sik is already invalidated") ErrSIKSubTree = fmt.Errorf("error getting SIK deep sub tree") ErrSIKGet = fmt.Errorf("error getting SIK") ErrSIKIterate = fmt.Errorf("error iterating over SIKs") ErrSIKNotFound = fmt.Errorf("SIK not found") ErrSIKSet = fmt.Errorf("error setting new SIK") ErrSIKDelete = fmt.Errorf("error deleting new SIK") ErrSIKRootsGet = fmt.Errorf("error getting current valid SIK root") ErrSIKRootsSet = fmt.Errorf("error setting new SIK roots") ErrSIKRootsDelete = fmt.Errorf("error deleting old SIK roots") )
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, }), "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, }), "CensusSIK": statedb.NewTreeSingletonConfig(statedb.TreeParams{ HashFunc: arbo.HashFunctionPoseidon, KindID: "sik", MaxLevels: censustree.DefaultMaxLevels, ParentLeafGetRoot: rootLeafGetRoot, ParentLeafSetRoot: rootLeafSetRoot, }), } // ChildTrees contains the configuration for the state trees dependent on a main tree. ChildTrees = map[string]*statedb.TreeNonSingletonConfig{ "Votes": statedb.NewTreeNonSingletonConfig(statedb.TreeParams{ HashFunc: arbo.HashFunctionSha256, KindID: "votes", MaxLevels: 256, ParentLeafGetRoot: processGetVotesRoot, ParentLeafSetRoot: processSetVotesRoot, }), } )
var BurnAddress = common.HexToAddress("0xffffffffffffffffffffffffffffffffffffffff")
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}, }
var (
ErrProcessChildLeafRootUnknown = fmt.Errorf("process child leaf root is unknown")
)
Functions ¶
func CheckDuplicateDelegates ¶
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 ExportNoStateDB ¶ added in v1.9.0
ExportNoStateDB exports the no state db to a gob encoder and writes it to the given writer.
func GenerateNullifier ¶
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 ImportNoStateDB ¶ added in v1.9.0
ImportNoStateDB imports the no state db from a gob decoder and writes it to the given db updater.
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 ¶
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 ¶
AddDelegate adds an address to the list of delegates for an account
func (*Account) DelDelegate ¶
DelDelegate removes an address from the list of delegates for an account
func (*Account) IsDelegate ¶
IsDelegate checks if an address is a delegate for an account
type BeginBlock ¶ added in v1.9.0
type CensusProperties ¶
type DiskSnapshotInfo ¶ added in v1.9.0
type EventListener ¶
type EventListener interface { OnVote(vote *Vote, txIndex int32) OnNewTx(tx *vochaintx.Tx, 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) OnSpendTokens(addr []byte, txType models.TxType, cost uint64, reference string) OnCensusUpdate(pid, censusRoot []byte, censusURI string) Commit(height uint32) (err error) OnBeginBlock(BeginBlock) 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 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 NoState ¶ added in v1.9.0
type NoState struct {
// contains filtered or unexported fields
}
NoState is a wrapper around the state database for nostate operations.
func (*NoState) Has ¶ added in v1.9.0
Has returns true if the nostate database contains the given key.
type ProcessBlockRegistry ¶ added in v1.9.0
type ProcessBlockRegistry struct {
// contains filtered or unexported fields
}
ProcessBlockRegistry struct allows to keep in track the block number when the current on going processes start. This information is important to know the on going election with the biggest endBlock, that is used to check if an account can change its SIK yet or not. Read more about this mechanism on vochain/state/sik.go
func (*ProcessBlockRegistry) DeleteStartBlock ¶ added in v1.9.0
func (pbr *ProcessBlockRegistry) DeleteStartBlock(pid []byte) error
DeleteStartBlock method deletes the record on the key-value database associated to the processes subtree for the process ID provided.
func (*ProcessBlockRegistry) MaxEndBlock ¶ added in v1.9.0
func (pbr *ProcessBlockRegistry) MaxEndBlock(fromBlock uint32) (uint32, error)
MaxEndBlock returns the maximun end block of the current on going processes from the no-state db associated to the process sub tree.
func (*ProcessBlockRegistry) MinStartBlock ¶ added in v1.9.0
func (pbr *ProcessBlockRegistry) MinStartBlock(fromBlock uint32) (uint32, error)
MinStartBlock returns the minimun start block of the current on going processes from the no-state db associated to the process sub tree.
func (*ProcessBlockRegistry) SetStartBlock ¶ added in v1.9.0
func (pbr *ProcessBlockRegistry) SetStartBlock(pid []byte, startBlock uint32) error
SetStartBlock method creates a new record on the key-value database associated to the processes subtree for the process ID and the startBlock number provided.
type SIK ¶ added in v1.9.0
type SIK []byte
SIK type abstracts a slice of bytes that contains the Secret Identity Key value of a user
func (SIK) DecodeInvalidatedHeight ¶ added in v1.9.0
DecodeInvalidatedHeight funtion returns the decoded height uint32 from the leaf value that contains an invalidated SIK.
func (SIK) InvalidateAt ¶ added in v1.9.0
InvalidateAt function sets the current SIK value to the encoded value of the height provided, ready to use in the SIK subTree as leaf value to invalidate it. The encoded value will have 32 bytes:
- The initial 28 bytes must be zero.
- The remaining 4 bytes must contain the height encoded in LittleEndian
type SnapshotHeader ¶
type SnapshotHeader struct { Version int Root []byte ChainID string Height uint32 NoStateSize uint32 Trees []SnapshotHeaderTree }
SnapshotHeader is the header structure of StateSnapshot containing the list of merkle trees.
type SnapshotHeaderTree ¶
SnapshotHeaderTree represents a merkle tree of the StateSnapshot.
type State ¶
type State struct { DisableVoteCache atomic.Bool // electionPriceCalc is the calculator for the election price ElectionPriceCalc *electionprice.Calculator ProcessBlockRegistry *ProcessBlockRegistry // contains filtered or unexported fields }
State represents the state of the vochain application
func (*State) AccountFromSignature ¶
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) AddProcess ¶
AddProcess adds a new process to the vochain. Adding a process with a ProcessId that already exists will return an error.
func (*State) AddProcessKeys ¶
AddProcessKeys adds the keys to the process
func (*State) AddValidator ¶
AddValidator adds a tendemint validator. If it exists, it will be updated.
func (*State) AddVote ¶
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) AssignSIKToElection ¶ added in v1.9.0
AssignSIKToElection function persists the relation between a created SIK (without registered account) and the election where the SIK is valid. This relation allows to remove all SIKs when the election ends.
func (*State) BurnTxCost ¶
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, cost uint64, reference string) error
BurnTxCostIncrementNonce reduces the transaction cost from the account balance and increments nonce. If cost is set to 0, the cost is calculated from the tx type base cost. Reference is optional and can be used to store a reference to the transaction that caused the burn.
func (*State) CacheGetCopy ¶
CacheGetCopy fetch an existing vote from the local cache and returns a copy which is thread-safe for writing.
func (*State) CacheHasNullifier ¶
CacheHasNullifier fetch an existing vote from the local cache.
func (*State) CachePurge ¶
CachePurge removes the old cache saved votes
func (*State) CancelProcess ¶
CancelProcess sets the process canceled attribute to true
func (*State) CleanEventListeners ¶
func (v *State) CleanEventListeners()
CleanEventListeners removes all event listeners.
func (*State) CommittedHash ¶ added in v1.10.0
CommittedHash returns the hash of the last committed vochain StateDB
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) CountAccounts ¶ added in v1.9.0
CountAccounts returns the overall number of accounts the vochain has
func (*State) CountProcesses ¶
CountProcesses returns the overall number of processes the vochain has
func (*State) CountRegisterSIK ¶ added in v1.9.0
CountRegisterSIK method returns the number of RegisterSIKTx associated to the provided electionId (or processID)
func (*State) CountSIKs ¶ added in v1.9.0
CountSIKs returns the overall number of SIKs the vochain has
func (*State) CountTotalVotes ¶ added in v1.8.0
CountTotalVotes return the global vote count. When committed is false, the operation is executed also on not yet committed data from the currently open StateDB transaction. When committed is true, the operation is executed on the last committed version.
func (*State) CountVotes ¶
CountVotes returns the number of votes registered for a given process id When committed is false, the operation is executed also on not yet committed data from the currently open StateDB transaction. When committed is true, the operation is executed on the last committed 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 ¶
CurrentHeight returns the current state height (block count).
func (*State) EnvelopeList ¶
func (s *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 committed data from the currently open StateDB transaction. When committed is true, the operation is executed on the last committed version.
func (*State) EventListeners ¶
func (v *State) EventListeners() []EventListener
EventListeners returns the list of subscribed event listeners.
func (*State) ExpiredSIKRoot ¶ added in v1.9.0
ExpiredSIKRoot returns if the provided siksRoot is still valid or not, checking if it is included into the list of current valid sik roots.
func (*State) FaucetNonce ¶
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) FetchValidSIKRoots ¶ added in v1.9.0
FetchValidSIKRoots updates the list of current valid SIK roots in the current state. It reads the roots from the key-value database associated to the SIK's subtree.
func (*State) GetAccount ¶
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) GetProcessResults ¶
GetProcessResults returns a friendly representation of the results stored in the State (if any).
func (*State) IncreaseRegisterSIKCounter ¶ added in v1.9.0
IncreaseRegisterSIKCounter method allows to keep in track the number of RegisterSIK actions by electionId (or processID). This helps to prevent attacks using the free tx of RegisterSIKTx. If the desired election has not any RegisterSIKTx associated, it will initialize the counter.
func (*State) IncrementAccountProcessIndex ¶
IncrementAccountProcessIndex increments the process index by one and stores the value
func (*State) InitChainMintBalance ¶
func (*State) InvalidateSIK ¶ added in v1.9.0
InvalidateSIK function removes logically the registered SIK for the address provided. If it is not registered, it returns an error. If it is, it will encode the current height and set it as the SIK value to invalidate it and prevent it from being updated until all processes created before that height have finished.
func (*State) IterateVotes ¶
func (s *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 ¶
LastHeight returns the last committed height (block count). We match the StateDB Version with the height via the Commits done in Save.
func (*State) ListProcessIDs ¶
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 ¶
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
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) NetworkCapacity ¶ added in v1.8.0
NetworkCapacity returns the total capacity (in votes per block) of the network.
func (*State) NoState ¶ added in v1.9.0
NoState is a wrapper around the state database that allows to write and read data without affecting the state hash.
It is safe to use concurrently also with other NoState instances if withTxLock parameter is set to true. Be aware that the NoState operations use the state.Tx mutex, so if the lock is acquired while calling NoState and withTxLock is set to true, it will deadlock.
The NoState transaction is committed or discarted with the state transaction at Save() or Rollback().
func (*State) OnBeginBlock ¶ added in v1.9.0
func (v *State) OnBeginBlock(bb BeginBlock)
func (*State) PrepareCommit ¶ added in v1.10.0
PrepareCommit prepares the state for commit. It returns the new root hash.
func (*State) PurgeRegisterSIK ¶ added in v1.9.0
PurgeRegisterSIK method removes the counter of RegisterSIKTx for the provided electionId (or processID)
func (*State) PurgeSIKsByElection ¶ added in v1.9.0
PurgeSIKsByElection function iterates over the stored relations between a process and a SIK without account and remove both of them, the SIKs and also the relation.
func (*State) RemoveValidator ¶
RemoveValidator removes a tendermint validator identified by its validator.Address
func (*State) RevealProcessKeys ¶
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) SIKFromAddress ¶ added in v1.9.0
SIKFromAddress function return the current SIK value associated to the provided address.
func (*State) SIKGenProof ¶ added in v1.9.0
SIKGenProof returns the proof of the provided address in the SIKs tree. The first returned value is the leaf value and the second the proof siblings.
func (*State) Save ¶
Save persistent save of vochain mem trees. It returns the new root hash. It also notifies the event listeners. Save should usually be called after PrepareCommit().
func (*State) SetAccount ¶
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 ¶
SetAccountInfoURI sets a given account infoURI
func (*State) SetAddressSIK ¶ added in v1.9.0
SetAddressSIK function creates or update the SIK of the provided address in the state. It covers the following cases:
- It checks if already exists a valid SIK for the provided address and if so it returns an error.
- If no SIK exists for the provided address, it will create one with the value provided.
- If it exists but it is not valid, overwrite the stored value with the provided one.
func (*State) SetCacheSize ¶
SetCacheSize sets the size for the vote LRU cache.
func (*State) SetChainID ¶
SetChainID sets the state chainID (blockchain identifier)
func (*State) SetElectionPriceCalc ¶ added in v1.8.0
SetElectionPriceCalc sets the election price calculator with the current network capacity and base price.
func (*State) SetFaucetNonce ¶
SetFaucetNonce stores an already used faucet nonce in the FaucetNonce subtree
func (*State) SetMaxProcessSize ¶ added in v1.6.0
SetMaxProcessSize sets the global maximum number voters allowed in an election.
func (*State) SetNetworkCapacity ¶ added in v1.8.0
SetNetworkCapacity sets the total capacity (in votes per block) of the network.
func (*State) SetProcessCensus ¶
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) error
SetProcessResults sets the results for a given process and calls the event listeners.
func (*State) SetProcessStatus ¶
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) SetTxBaseCost ¶ added in v1.8.0
SetTxBaseCost sets the given transaction cost
func (*State) Snapshot ¶
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) TxBaseCost ¶ added in v1.8.0
TxBaseCost returns the base cost of a given transaction When committed is false, the operation is executed also on not yet committed data from the currently open StateDB transaction. When committed is true, the operation is executed on the last committed version.
func (*State) TxCounterAdd ¶
func (v *State) TxCounterAdd()
TxCounterAdd adds to the atomic transaction counter
func (*State) UpdateProcess ¶
UpdateProcess updates an existing process
func (*State) UpdateSIKRoots ¶ added in v1.9.0
UpdateSIKRoots keep on track the last valid SIK Merkle Tree roots to support voting to already registered users when an election is on going and new users are registered. When a new sikRoot is generated, the sikRoot’s from an older block than the current block minus the hysteresis blocks will be deleted:
If exists a sikRoot for the minimun hysteresis block number (currentBlock - hysteresis), just remove all the roots with a lower block number.
If it does not exist, remove all roots with a lower block number except for the next lower sikRoot. It is because it still being validate for a period.
func (*State) ValidSIKRoots ¶ added in v1.9.0
ValidSIKRoots method returns the current valid SIK roots that are cached in the current State. It is thread safe, but the returned value should not be modified by the caller.
func (*State) Validator ¶
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 ¶
Validators returns a list of the chain validators When committed is false, the operation is executed also on not yet committed data from the currently open StateDB transaction. When committed is true, the operation is executed on the last committed version.
func (*State) Vote ¶
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 committed data from the currently open StateDB transaction. When committed is true, the operation is executed on the last committed version.
func (*State) VoteExists ¶
VoteExists returns true if the envelope identified with voteID exists When committed is false, the operation is executed also on not yet committed data from the currently open StateDB transaction. When committed is true, the operation is executed on the last committed version.
type StateSnapshot ¶
type StateSnapshot struct {
// contains filtered or unexported fields
}
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][noState][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 opposed 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) SetNoStateSize ¶ added in v1.9.0
func (s *StateSnapshot) SetNoStateSize(size uint32)
SetNoStateSize sets the noState database size
func (*StateSnapshot) TreeHeader ¶
func (s *StateSnapshot) TreeHeader() *SnapshotHeaderTree
TreeHeader returns the header for the current 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) Hash ¶
Hash returns the hash of the vote. Only the fields that are an essential part of the vote are hashed.
func (*Vote) WeightBytes ¶
WeightBytes returns the vote weight as a byte slice. If the weight is nil, it returns a byte slice of 1.
type VotePackage ¶ added in v1.8.0
VotePackage represents the payload of a vote (usually base64 encoded).
func NewVotePackage ¶ added in v1.8.0
func NewVotePackage(votes []int) *VotePackage
NewVotePackage creates a new vote package with the given vote slice.
func (*VotePackage) Decode ¶ added in v1.8.0
func (vp *VotePackage) Decode(data []byte) error
Decode decodes the json encoded vote package.
func (*VotePackage) Encode ¶ added in v1.8.0
func (vp *VotePackage) Encode() ([]byte, error)
Encode returns the json encoded vote package.
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 NewVoterID ¶ added in v1.7.0
func NewVoterID(voterIDType VoterIDType, key []byte) VoterID
NewVoterID creates a new VoterID from a VoterIDType and a key.
func (VoterID) Address ¶
Address returns the voterID Address depending on the VoterIDType. Returns nil if the VoterIDType is not supported or the address cannot be obtained.
func (VoterID) Bytes ¶ added in v1.7.0
Bytes returns the bytes of the VoterID without the first byte which indicates the type.
func (VoterID) Type ¶
func (v VoterID) Type() VoterIDType
Type returns the VoterID type defined in VoterIDTypeName
func (VoterID) VoterIDTypeToString ¶
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 VoterIDTypeZkSnark VoterIDType = 2 )
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package electionprice provides a mechanism for calculating the price of an election based on its characteristics.
|
Package electionprice provides a mechanism for calculating the price of an election based on its characteristics. |