Package convex.core
Class State
- All Implemented Interfaces:
IAssociative<Keyword,
,ACell> IValidated
,IWriteable
,Map<Keyword,
ACell>
Class representing the immutable state of the CVM
State transitions are represented by blocks of transactions, according to the logic: s[n+1] = s[n].applyBlock(b[n])
State contains the following elements - Map of AccountStatus for every
Address - Map of PeerStatus for every Peer Address - Global values - Schedule
data structure
"State. You're doing it wrong" - Rich Hickey
-
Nested Class Summary
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final State
An empty Statestatic final Index
<AccountKey, PeerStatus> static final int
static final int
static final int
static final int
static final int
Symbols for global values in :globals Vectorstatic final int
Fields inherited from class convex.core.data.ARecord
DEFAULT_VALUE
Fields inherited from class convex.core.data.ADataStructure
count
Fields inherited from class convex.core.data.ACell
cachedRef, memorySize
-
Method Summary
Modifier and TypeMethodDescriptionaddActor()
Adds a new Actor Account.applyBlock
(SignedData<Block> signedBlock) Applies a signed Block to the current state, i.e.applyTimeUpdate
(long newTimestamp) Updates the State based on passage of time.applyTransaction
(SignedData<? extends ATransaction> signedTransaction) Applies a signed transaction to the State.Applies a transaction to the State.checkBlock
(SignedData<Block> signedBlock) Checks if a block is valid for application to the current stateComputes the weighted stake for each peer.long
Compute the total funds existing within this state.long
Compute the total memory allowance, including the memory pool.static State
create
(AVector<AccountStatus> accounts, Index<AccountKey, PeerStatus> peers, AVector<ACell> globals, Index<ABlob, AVector<ACell>> schedule) Create a Stateint
encode
(byte[] bs, int pos) Writes this Cell's encoding to a byte array, including a tag byte which will be written first.int
encodeRaw
(byte[] bs, int pos) Writes this Cell's encoding to a byte array, excluding the tag byte.boolean
Checks for equality with another Cell.boolean
Tests if this State is equal to anotherint
Estimate the encoded data size for this Cell.Gets the record field content for a given key, or null if not found.getAccount
(Address target) Gets the AccountStatus for a given account, or null if not found.Get all Accounts in this StategetBalance
(Address address) Gets the balance of a specific address, or null if the Address does not existint
Method to calculate the encoding length of a Cell.getEnvironment
(Address addr) Gets the environment for a given account, or null if not found.Gets the RecordFormat instance that describes this Record's layoutGets the Global Fees accumulated in the StateGets globals.Gets the current Juice pricedouble
getPeer
(AccountKey peerAddress) Gets the PeerStatus record for the given Address, or null if it does not existgetPeers()
Gets the map of Peers for this StategetRef
(int i) Gets a numbered child Ref from within this Cell.int
Gets the number of Refs contained within this Cell.Gets the current schedule data structure for this statebyte
getTag()
Gets the tag byte for this record type.Gets the current global timestamp from this state.boolean
hasAccount
(Address address) boolean
Returns true if this Cell is in a canonical representation.Look up an Address from CNSGets the next available address for allocation, i.e.putAccount
(Address address, AccountStatus accountStatus) Returns this state after updating the given accountstatic State
Reads a State from an encoding.scheduleOp
(long time, Address address, AOp<?> op) Schedules an operation with the given timestamp and Op in this statestatic State
statesAsOfRange
(AVector<State> states, CVMLong timestamp, long interval, int count) updateMemoryPool
(long cvx, long mem) updateRefs
(IRefFunction func) Updates all Refs in this object using the given function.void
validate()
Validates the complete structure of this object.void
Validates the local structure and invariants of this cell.withAccounts
(AVector<AccountStatus> newAccounts) Updates the Accounts in this StatewithBalance
(Address address, long newBalance) withGlobalFees
(CVMLong newFees) Update Global FeeswithPeer
(AccountKey peerKey, PeerStatus updatedPeer) Updates the specified peer statuswithPeers
(Index<AccountKey, PeerStatus> newPeers) Updates the Peers in this StatewithTimestamp
(long timestamp) Updates the State with a new timestampMethods inherited from class convex.core.data.ARecord
accumulateEntrySet, accumulateKeySet, accumulateValues, assoc, assocEntry, containsKey, containsValue, dissoc, dissoc, empty, entryAt, entrySet, forEach, get, getEntry, getEntryByHash, getKeyRefEntry, getKeys, getType, getValuesArray, isCVMValue, keySet, reduceEntries, reduceValues, toCanonical, toHashMap, values
Methods inherited from class convex.core.data.AMap
clear, conj, containsKey, containsKeyRef, containsValue, entryVector, filterValues, get, get, get, getElementRef, merge, print, put, putAll, remove, slice, slice
Methods inherited from class convex.core.data.ADataStructure
checkIndex, conjAll, count, isDataValue, isEmpty, size, toCVMString
Methods inherited from class convex.core.data.ACell
attachMemorySize, attachRef, cachedEncoding, cachedHash, calcMemorySize, createEncoding, createRef, equals, genericEquals, getCanonical, getChildRefs, getEncoding, getHash, getMemorySize, getMemorySize, getRef, hashCode, isEmbedded, toString
Methods inherited from class convex.core.data.AObject
attachEncoding, print, print
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface java.util.Map
compute, computeIfAbsent, computeIfPresent, equals, getOrDefault, hashCode, isEmpty, merge, putIfAbsent, remove, replace, replace, replaceAll, size
-
Field Details
-
EMPTY_SCHEDULE
-
EMPTY_PEERS
-
GLOBAL_SYMBOLS
-
GLOBAL_TIMESTAMP
public static final int GLOBAL_TIMESTAMP- See Also:
-
GLOBAL_FEES
public static final int GLOBAL_FEES- See Also:
-
GLOBAL_JUICE_PRICE
public static final int GLOBAL_JUICE_PRICE- See Also:
-
GLOBAL_MEMORY_MEM
public static final int GLOBAL_MEMORY_MEM- See Also:
-
GLOBAL_MEMORY_CVX
public static final int GLOBAL_MEMORY_CVX- See Also:
-
GLOBAL_PROTOCOL
public static final int GLOBAL_PROTOCOL- See Also:
-
EMPTY
An empty State
-
-
Method Details
-
get
-
getRefCount
public int getRefCount()Description copied from class:ACell
Gets the number of Refs contained within this Cell. This number is final / immutable for any given instance and is defined by the Cell encoding rules. Contained Refs may be either external or embedded.- Overrides:
getRefCount
in classACell
- Returns:
- The number of Refs in this Cell
-
getRef
Description copied from class:ACell
Gets a numbered child Ref from within this Cell. WARNING: May need to convert to a canonical instance -
updateRefs
Description copied from class:ACell
Updates all Refs in this object using the given function. The function *must not* change the hash value of Refs, in order to ensure structural integrity of modified data structures. The implementation *should* re-attach any original encoding in order to prevent re-encoding or surplus hashing This is a building block for a very sneaky trick that enables use to do a lot of efficient operations on large trees of smart references. Must return the same object if no Refs are altered.- Overrides:
updateRefs
in classACell
- Parameters:
func
- Ref update function- Returns:
- Cell with updated Refs
-
create
public static State create(AVector<AccountStatus> accounts, Index<AccountKey, PeerStatus> peers, AVector<ACell> globals, Index<ABlob, AVector<ACell>> schedule) Create a State- Parameters:
accounts
- Accountspeers
- Peersglobals
- Globalsschedule
- Schedule (may be null)- Returns:
- New State instance
-
encode
public int encode(byte[] bs, int pos) Description copied from class:ACell
Writes this Cell's encoding to a byte array, including a tag byte which will be written first. Cell must be canonical, or else an error may occur.- Specified by:
encode
in interfaceIWriteable
- Specified by:
encode
in classACell
- Parameters:
bs
- A byte array to which to write the encodingpos
- The offset into the byte array- Returns:
- New position after writing
-
encodeRaw
public int encodeRaw(byte[] bs, int pos) Description copied from class:ACell
Writes this Cell's encoding to a byte array, excluding the tag byte. -
getEncodingLength
public int getEncodingLength()Description copied from class:ACell
Method to calculate the encoding length of a Cell. May be overridden to avoid creating encodings during memory size calculations. This reduces hashing!- Overrides:
getEncodingLength
in classACell
- Returns:
- Exact encoding length of this Cell
-
estimatedEncodingSize
public int estimatedEncodingSize()Description copied from interface:IWriteable
Estimate the encoded data size for this Cell. Used for quickly sizing buffers. Implementations should try to return a size that is highly likely to contain the entire object when encoded, including the tag byte. Should not traverse soft Refs, i.e. must be usable on arbitrary partial data structures- Specified by:
estimatedEncodingSize
in interfaceIWriteable
- Overrides:
estimatedEncodingSize
in classARecord
- Returns:
- The estimated size for the binary representation of this object.
-
read
Reads a State from an encoding. Assumes tag byte already read.- Parameters:
b
- Blob to read frompos
- start position in Blob- Returns:
- Decoded State
- Throws:
BadFormatException
- If a State could not be read
-
getAccounts
Get all Accounts in this State- Returns:
- Vector of Accounts
-
getPeers
Gets the map of Peers for this State- Returns:
- A map of addresses to PeerStatus records
-
getBalance
-
withBalance
-
applyBlock
Applies a signed Block to the current state, i.e. the State Transition function- Parameters:
signedBlock
- Signed Block to apply- Returns:
- The BlockResult from applying the given Block to this State
-
checkBlock
Checks if a block is valid for application to the current state- Parameters:
signedBlock
- Signed Block- Returns:
- BlockResult instance if an error occurred, or nil if checks pass
-
applyTimeUpdate
Updates the State based on passage of time. Note: while this can be applied independently, normal correct State updates should go via `applyBlock`- Parameters:
newTimestamp
- New timestamp to apply- Returns:
- Updates State
-
applyScheduledTransactions
-
applyTransaction
public ResultContext applyTransaction(SignedData<? extends ATransaction> signedTransaction) throws BadSignatureException Applies a signed transaction to the State. SECURITY: Checks digital signature and correctness of account key- Returns:
- ResultContext containing the result of the transaction
- Throws:
BadSignatureException
-
applyTransaction
Applies a transaction to the State. There are three phases in application of a transaction:- Preparation for accounting, with
prepareTransaction
- Functional application of the transaction with ATransaction.apply(....)
- Completion of accounting, with completeTransaction
- Parameters:
t
- Transaction to apply- Returns:
- Context containing the updated chain State (may be exceptional)
- Preparation for accounting, with
-
isCanonical
public boolean isCanonical()Description copied from class:ACell
Returns true if this Cell is in a canonical representation. Non-canonical objects may be used on a temporary internal basis, they should be converted to canonical representations for general purpose use.- Overrides:
isCanonical
in classARecord
- Returns:
- true if the object is in canonical format, false otherwise
-
computeStakes
Computes the weighted stake for each peer. Adds a single entry for the null key, containing the total stake- Returns:
- Map of Stakes
-
withAccounts
Updates the Accounts in this State- Parameters:
newAccounts
- New Accounts vector- Returns:
- Updated State
-
putAccount
Returns this state after updating the given account- Parameters:
address
- Address of Account to updateaccountStatus
- New Account Status- Returns:
- Updates State, or this state if Account was unchanged
- Throws:
IndexOutOfBoundsException
- if Address represents an illegal account position
-
getAccount
Gets the AccountStatus for a given account, or null if not found.- Parameters:
target
- Address to look up. Must not be null- Returns:
- The AccountStatus for the given account, or null.
-
getEnvironment
-
withPeers
Updates the Peers in this State- Parameters:
newPeers
- New Peer Map- Returns:
- Updated State
-
getTag
-
addActor
Adds a new Actor Account. The actor will be the last Account in the resulting State, and will have a default empty Actor environment.- Returns:
- The updated state with the Actor Account added.
-
computeTotalFunds
public long computeTotalFunds()Compute the total funds existing within this state. Should be constant! 1,000,000,000,000,000,000 in full deployment mode- Returns:
- The total value of all funds
-
computeTotalMemory
public long computeTotalMemory()Compute the total memory allowance, including the memory pool.- Returns:
- The total amount of CVM memory available
-
validate
Description copied from interface:IValidated
Validates the complete structure of this object. It is necessary to ensure all child Refs are validated, so the general contract for validate is:- Call super.validate() - which will indirectly call validateCell()
- Call validate() on any contained cells in this class
- Specified by:
validate
in interfaceIValidated
- Overrides:
validate
in classACell
- Throws:
InvalidDataException
- If the data Value is invalid in any way
-
validateCell
Description copied from class:ACell
Validates the local structure and invariants of this cell. Called by validate() super implementation. Should validate directly contained data, but should not validate all other structure of this cell. In particular, should not traverse potentially missing child Refs.- Specified by:
validateCell
in classACell
- Throws:
InvalidDataException
- If the Cell is invalid
-
getTimestamp
Gets the current global timestamp from this state.- Returns:
- The timestamp from this state.
-
getJuicePrice
-
scheduleOp
-
getSchedule
-
getGlobalFees
-
withGlobalFees
-
getPeer
Gets the PeerStatus record for the given Address, or null if it does not exist- Parameters:
peerAddress
- Address of Peer to check- Returns:
- PeerStatus
-
withPeer
Updates the specified peer status- Parameters:
peerKey
- Peer KeyupdatedPeer
- New Peer Status- Returns:
- Updated state
-
nextAddress
Gets the next available address for allocation, i.e. the lowest Address that does not yet exist in this State.- Returns:
- Next address available
-
lookupCNS
-
getGlobals
-
withTimestamp
Updates the State with a new timestamp- Parameters:
timestamp
- New timestamp- Returns:
- Updated State
-
equals
Description copied from class:ACell
Checks for equality with another Cell. In general, Cells are considered equal if they have the same canonical representation, i.e. an identical encoding with the same hash value. Subclasses SHOULD override this if they have a more efficient equals implementation. MUST NOT require reads from Store. -
equals
Tests if this State is equal to another- Parameters:
a
- State to compare with- Returns:
- true if equal, false otherwise
-
getFormat
Description copied from class:ARecord
Gets the RecordFormat instance that describes this Record's layout -
getGlobalMemoryValue
-
getGlobalMemoryPool
-
getMemoryPrice
public double getMemoryPrice() -
updateMemoryPool
-
hasAccount
-
statesAsOfRange
-
stateAsOf
-