state

package
v1.10.1 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2023 License: AGPL-3.0 Imports: 32 Imported by: 1

Documentation

Index

Constants

View Source
const (
	TreeProcess    = "Processes"
	TreeExtra      = "Extra"
	TreeValidators = "Validators"
	TreeAccounts   = "Accounts"
	TreeFaucet     = "FaucetNonce"
	TreeSIK        = "CensusSIK"
	ChildTreeVotes = "Votes"
)
View Source
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

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_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

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")
	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")
)
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,
		}),

		"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,
		}),
	}
)
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 unknown")
)

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 ExportNoStateDB added in v1.9.0

func ExportNoStateDB(w io.Writer, reader *NoState) (uint32, error)

ExportNoStateDB exports the no state db to a gob encoder and writes it to the given writer.

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 ImportNoStateDB added in v1.9.0

func ImportNoStateDB(r io.Reader, db *NoState) error

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

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 BeginBlock added in v1.9.0

type BeginBlock struct {
	Height   int64
	Time     time.Time
	DataHash []byte
}

type CensusProperties

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

type DBPair added in v1.9.0

type DBPair struct {
	Key   []byte
	Value []byte
}

DBPair is a key value pair for the no state db.

type DiskSnapshotInfo added in v1.9.0

type DiskSnapshotInfo struct {
	ModTime time.Time
	Height  uint32
	Size    int64
}

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) Delete added in v1.9.0

func (ns *NoState) Delete(key []byte) error

Delete deletes a key-value pair from the nostate database.

func (*NoState) Get added in v1.9.0

func (ns *NoState) Get(key []byte) ([]byte, error)

Get retrieves a value from the nostate database.

func (*NoState) Has added in v1.9.0

func (ns *NoState) Has(key []byte) (bool, error)

Has returns true if the nostate database contains the given key.

func (*NoState) Iterate added in v1.9.0

func (ns *NoState) Iterate(prefix []byte, callback func(k, v []byte) bool) error

Iterate iterates over all the nostate database keys with the given prefix.

func (*NoState) Set added in v1.9.0

func (ns *NoState) Set(key, value []byte) error

Set sets a key-value pair in the nostate database.

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

func (s SIK) DecodeInvalidatedHeight() uint32

DecodeInvalidatedHeight funtion returns the decoded height uint32 from the leaf value that contains an invalidated SIK.

func (SIK) InvalidateAt added in v1.9.0

func (s SIK) InvalidateAt(height uint32) SIK

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

func (SIK) String added in v1.9.0

func (s SIK) String() string

String function return the human readable version of the current SIK, if it is a valid one, return the SIK value as hex. If it is already invalidated, return the decoded height.

func (SIK) Valid added in v1.9.0

func (s SIK) Valid() bool

Valid function returns if the current SIK is a valid one or not.

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

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

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 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) 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) AddValidator

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

AddValidator adds a tendemint validator. If it exists, it will be updated.

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) AssignSIKToElection added in v1.9.0

func (v *State) AssignSIKToElection(pid []byte, address common.Address) error

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

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, 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) 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 state chainID (blockchain identifier)

func (*State) CleanEventListeners

func (v *State) CleanEventListeners()

CleanEventListeners removes all event listeners.

func (*State) Close

func (v *State) Close() error

Close closes the vochain StateDB.

func (*State) CommittedHash added in v1.10.0

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

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

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

CountAccounts returns the overall number of accounts the vochain has

func (*State) CountProcesses

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

CountProcesses returns the overall number of processes the vochain has

func (*State) CountRegisterSIK added in v1.9.0

func (v *State) CountRegisterSIK(pid []byte) (uint32, error)

CountRegisterSIK method returns the number of RegisterSIKTx associated to the provided electionId (or processID)

func (*State) CountSIKs added in v1.9.0

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

CountSIKs returns the overall number of SIKs the vochain has

func (*State) CountTotalVotes added in v1.8.0

func (s *State) CountTotalVotes() (uint64, error)

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

func (s *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 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

func (v *State) CurrentHeight() uint32

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

func (v *State) ExpiredSIKRoot(candidateRoot []byte) bool

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

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) FetchValidSIKRoots added in v1.9.0

func (v *State) FetchValidSIKRoots() error

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

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) 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) IncreaseRegisterSIKCounter added in v1.9.0

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

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

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

IncrementAccountProcessIndex increments the process index by one and stores the value

func (*State) InitChainMintBalance

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

func (*State) InvalidateSIK added in v1.9.0

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

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

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

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

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) NetworkCapacity added in v1.8.0

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

NetworkCapacity returns the total capacity (in votes per block) of the network.

func (*State) NoState added in v1.9.0

func (s *State) NoState(withTxLock bool) *NoState

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

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

PrepareCommit prepares the state for commit. It returns the new root hash.

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) PurgeRegisterSIK added in v1.9.0

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

PurgeRegisterSIK method removes the counter of RegisterSIKTx for the provided electionId (or processID)

func (*State) PurgeSIKsByElection added in v1.9.0

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

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

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

RemoveValidator removes a tendermint validator identified by its validator.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) SIKFromAddress added in v1.9.0

func (v *State) SIKFromAddress(address common.Address) (SIK, error)

SIKFromAddress function return the current SIK value associated to the provided address.

func (*State) SIKGenProof added in v1.9.0

func (v *State) SIKGenProof(address common.Address) ([]byte, []byte, error)

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) SIKRoot added in v1.9.0

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

SIKRoot returns the last root hash of the SIK merkle tree.

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. Save should usually be called after PrepareCommit().

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) SetAddressSIK added in v1.9.0

func (v *State) SetAddressSIK(address common.Address, newSIK SIK) error

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

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 state chainID (blockchain identifier)

func (*State) SetElectionPriceCalc added in v1.8.0

func (v *State) SetElectionPriceCalc() error

SetElectionPriceCalc sets the election price calculator with the current network capacity and base price.

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 (not committed) 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) SetNetworkCapacity added in v1.8.0

func (v *State) SetNetworkCapacity(capacity uint64) error

SetNetworkCapacity sets the total capacity (in votes per block) of the network.

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) error

SetProcessResults sets the results for a given process and calls the event listeners.

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) SetTxBaseCost added in v1.8.0

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

SetTxBaseCost 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) TxBaseCost added in v1.8.0

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

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) 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) UpdateSIKRoots added in v1.9.0

func (v *State) UpdateSIKRoots() error

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

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

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

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 committed data from the currently open StateDB transaction. When committed is true, the operation is executed on the last committed version.

func (*State) Vote

func (s *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 committed data from the currently open StateDB transaction. When committed is true, the operation is executed on the last committed version.

func (*State) VoteExists

func (s *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 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.

func (*StateSnapshot) Write

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

Write implements the io.Writer interface. Writes a chunk 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 VotePackage added in v1.8.0

type VotePackage struct {
	Nonce string `json:"nonce,omitempty"`
	Votes []int  `json:"votes"`
}

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

func (v VoterID) Address() []byte

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

func (v VoterID) Bytes() []byte

Bytes returns the bytes of the VoterID without the first byte which indicates the type.

func (VoterID) IsNil

func (v VoterID) IsNil() bool

IsNil returns true if the VoterID is empty.

func (VoterID) Nil

func (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
	VoterIDTypeZkSnark   VoterIDType = 2
)

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.

Jump to

Keyboard shortcuts

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