Package convex.core
Class State
- All Implemented Interfaces:
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
FieldsFields inherited from class convex.core.data.ARecord
DEFAULT_VALUE, format
Fields inherited from class convex.core.data.ADataStructure
count
Fields inherited from class convex.core.data.ACell
cachedRef, EMPTY_ARRAY
-
Method Summary
Modifier and TypeMethodDescriptionapplyBlock(Block block)
Block level state transition function Updates the state by applying a given block of transactionsApplies a transaction to the State.Computes the weighted stake for each peer.long
Compute the total funds existing within this state.static State
create(AVector<AccountStatus> accounts, BlobMap<AccountKey,PeerStatus> peers, AVector<ACell> globals, BlobMap<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 the raw fields of this record in declared orderboolean
Checks this map for equality with another map.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 existlong
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 Global Fees accumulated in the StateGets globals.Gets the current Juice pricegetPeer(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
Returns true if this Cell is in a canonical representation for message writing.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
read(ByteBuffer bb)
Reads a State from a ByteBuffer encoding.scheduleOp(long time, Address address, AOp<?> op)
Schedules an operation with the given timestamp and Op in this stateDeploys a new Actor in the current state.protected State
Updates all values in this record, in declared field order.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(BlobMap<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, equalsKeys, forEach, get, getEntry, getEntryByHash, getFormat, getKeyRefEntry, getKeys, getType, getValuesArray, isCVMValue, keySet, reduceEntries, reduceValues, toCanonical, toHashMap, updateRefs, values
Methods inherited from class convex.core.data.AMap
clear, conj, containsKey, containsKeyRef, entryVector, equals, filterValues, get, get, getElementRef, print, put, putAll, remove
Methods inherited from class convex.core.data.ADataStructure
conjAll, count, isEmpty, size, toCVMString
Methods inherited from class convex.core.data.ACell
announce, announce, attachMemorySize, attachRef, cachedEncoding, cachedHash, calcMemorySize, createAnnounced, createEncoding, createPersisted, createPersisted, createRef, equals, getCanonical, getChildRefs, getEncoding, getHash, getMemorySize, getRef, hashCode, isCompletelyEncoded, isEmbedded, mark, mark, toString, write
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
An empty State
-
-
Method Details
-
get
Description copied from class:ARecord
Gets the record field content for a given key, or null if not found. -
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 classARecord
- Returns:
- The number of Refs in this Cell
-
getRef
Description copied from class:ACell
Gets a numbered child Ref from within this Cell. -
updateAll
Description copied from class:ARecord
Updates all values in this record, in declared field order. Returns this if all values are identical. -
create
public static State create(AVector<AccountStatus> accounts, BlobMap<AccountKey,PeerStatus> peers, AVector<ACell> globals, BlobMap<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:ARecord
Writes the raw fields of this record in declared order -
getEncodingLength
public long 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 likely to contain the entire object when represented in binary format, including the tag byte.- 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 a ByteBuffer encoding. Assumes tag byte already read.- Parameters:
bb
- ByteBuffer to decode from- Returns:
- The State decoded
- 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
Gets the balance of a specific address, or null if the Address does not exist- Parameters:
address
- Address to check- Returns:
- Long balance, or null if Account does not exist
-
withBalance
-
applyBlock
Block level state transition function Updates the state by applying a given block of transactions- Parameters:
block
- Block to Apply- Returns:
- The BlockResult from applying the given Block to this State
-
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
- Type Parameters:
T
- Type of transaction result- 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 for message writing. Non-canonical objects may be used on a temporary internal basis, they must always be converted to canonical representations for external use (e.g. Encoding).- 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
-
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
Gets the environment for a given account, or null if not found.- Parameters:
addr
- Address of account to obtain- Returns:
- The environment of the given account, or null if not found.
-
withPeers
Updates the Peers in this State- Parameters:
newPeers
- New Peer Map- Returns:
- Updated State
-
getTag
public byte getTag()Description copied from class:ARecord
Gets the tag byte for this record type. The Tag is the byte used to identify the record in the binary encoding. -
tryAddActor
Deploys a new Actor in the current state. Returns the updated state. The actor will be the last Account.- Returns:
- The updated state with the Actor deployed.
-
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
-
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 Valie 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
Gets the current Juice price- Returns:
- Juice Price
-
scheduleOp
Schedules an operation with the given timestamp and Op in this state- Parameters:
time
- Timestamp at which to execute the scheduled opaddress
- AccountAddress to schedule op forop
- Op to execute in schedule- Returns:
- The updated State
-
getSchedule
Gets the current schedule data structure for this state- Returns:
- The schedule data structure.
-
getGlobalFees
Gets the Global Fees accumulated in the State- Returns:
- Global Fees
-
withGlobalFees
Update Global Fees- Parameters:
newFees
- New Fees- Returns:
- Updated State
-
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
Look up an Address from CNS- Parameters:
name
- CNS name String- Returns:
- Address from CNS, or null if not found
-
getGlobals
Gets globals.- Returns:
- Vector of global values
-
withTimestamp
Updates the State with a new timestamp- Parameters:
timestamp
- New timestamp- Returns:
- Updated State
-
equals
Description copied from class:AMap
Checks this map for equality with another map. In general, maps should be considered equal if they have the same canonical representation, i.e. the same hash value. Subclasses may override this this they have a more efficient equals implementation or a more specific definition of equality. -
equals
Tests if this State is equal to another- Parameters:
a
- State to compare with- Returns:
- true if equal, false otherwise
-