# L2 client spec(chamber spec) This client spec of OVM. A whole document is [here](https://hackmd.io/@syuhei/HJRKfUOwr). ### Modules - [clients](https://hackmd.io/3003WCghTou-oXGBcTmuUg?view#L2-Clients): Plasma aggregator and light client implementation, we will add other L2 client here in the future - [ovm](https://github.com/cryptoeconomicslab/wakkanay/tree/master/src/ovm): core OVM implementation - [db](https://github.com/cryptoeconomicslab/wakkanay/tree/master/src/db): general use case databases. KeyValueStore and RangeDb. - [events](https://github.com/cryptoeconomicslab/wakkanay/tree/master/src/events): EventWatcher polling contract events from Ethereum. - [contract](https://github.com/cryptoeconomicslab/wakkanay/tree/master/src/contract): Contract API. we may use Web3 like library for implementing this. - [network](https://github.com/cryptoeconomicslab/wakkanay/tree/master/src/network): L2 network interface and implementation. would be Pubsub model. - wallet: Key Management ## Primitive Types We have several primitive types for inner representation. ### Bytes ### Address ### Integer ### BigNumber BigNumber = max uint256(L1 dependent) ### List ### Tuple ### Struct ### Range ``` struct Range { start: BigNumber, end: BigNumber } ``` ## Data Structure ### Basic data structure. #### Property ``` struct Property { address: Address, inputs: Bytes[] } ``` ### Plasma data structure #### StateUpdate ``` struct StateUpdate { blockNumber: Integer, depositContractAddress: Address, range: Range, stateObject: Property } Property({ address: StateUpdate.address, inputs: [blockNumber, depositContractAddress, range, stateObject] }) ``` #### Block ``` Block: { blockNumber: Integer stateUpdatesMap: Map<Address, StateUpdate[]> } ``` #### Transaction ``` struct Transaction { deprecatedBlockNumber: Integer, depositContractAddress: Address, range: Range, stateObject: Property } ``` # L2 Clients Developed in [lite client](https://github.com/cryptoeconomicslab/wakkanay-plasma-light-client) and [aggregator](https://github.com/cryptoeconomicslab/wakkanay-plasma-aggregator). ## Common Class ### StateManager Manage StateUpdates which have been verified by Merkle Tree. * getAllVerifiedStateUpdate * getVerifiedStateUpdates(depositContractAddress: Address, start: Integer, end: Integer) * putVerifiedStateUpdate(stateUpdate: StateUpdate) ## Plasma client Plasma Cash's lite client to send a transaction and recieve a transaction verifying coin history. ## Plasma aggregator Plasma aggregator client collects transactions in BlockManager and constructs their Merkle tree. The aggregator submits Merkle Root to Commitment Contract. ### BlockManager * enqueueTransaction(transaction: Transaction) * enqueueStateUpdate(stateUpdate: StateUpdate) * submitBlock * `getBlock(blockNumber: Integer): Promise<Block>` ### HTTP endpoint * POST `/send_tx` * recieve transaction and calculate stateupdate, then returns 201(CREATED) status code. * returns 422 when invalid transaction * returns 422 when not enough amount # Core Database Developed in `db`. Core Databases are general purpose database such as KeyValueStore or RangeDb. RangeDb is a special form of KVS which can handle record using range(start: u64, end: u64) as a key. ## KeyValueStore * `put(key: Bytes, value: Bytes): Promise<void>` * `get(key: Bytes): Promise<Bytes | null>` * `del(key: Bytes): Promise<void>` * `iter(bound: Bytes)`: Creates iterator with bound key. Iterator seek greater than equal bound. * `bucket(name: Bytes)`: Returns bucket instance with bucket name. Bucket just appends a prefix to key but connecting one database. ### Iterator * next(): Promise<{key: Bytes, value: Bytes}> ### RangeDb * `put(start: Integer, end: Integer, value: Bytes): Promise<void>` * `get(start: Integer, end: Integer): Promise<Bytes[]>` * `bucket(name: Bytes): Bucket` `start` and `end` must support 256bit integer. ## Local information Database The database for local information. local infomation is described in [this article](https://medium.com/plasma-group/introducing-the-ovm-db253287af50). We call these database WitnessDatabase. moved WitnessDatabase to [here](https://github.com/cryptoeconomicslab/wakkanay/blob/master/src/ovm/deciders/getWitnesses.ts). We use "hint-data" to query witness database. The format is "type:bucket:key". ### SignedByDb ``` struct SignedByRecord { address, message, signature } ``` A key is address + Hash(message). ### TransactionDb ### RangeAtBlockDb # Network # Core OVM decider https://github.com/cryptoeconomicslab/wakkanay/tree/master/src/ovm OVM decider system check a property is true or false. This system include various deciders and each decider load witness from database to decide. The list of deciders. ### Logical Connective and quantifier * ForAllSuchThat * ThereExistsSuchThat * And * Or * Not ### Atomic deciders * Equal * IsContained * IsSameAmount * ISLessThan * IsValidSignature * VerifyInclusion * ... ## Data Structure ### Decision ``` struct Decision { outcome: bool, challenges: Challenge[] } ``` ### Challenge It stands for validChallenge of a property. e.g.) Challenge of `Not(P)` is `Challenge` ``` struct Challenge { challengeInput: Bytes | null, challengeProperty: Property } ``` ## getWitness `getWitnesses` function get witnesses from database by hint string. ### The format of hint `bucket,type,param` type is KEY, RANGE, ITER or NUMBER. bucket is db bucket where witnesses are stored. THe format of param is different by `type`. For `KEY`, param is hex string of key of KVS db. For `RANGE`, param is L1 specific encoded Range data(hex). For `ITER`, the format is same as `KEY`. For `NUMBER`, param is `${s}-${e}`: s and e are hex string of numbers. # Wallet ### getBalance(): Balance ```json { amount: 10000, decimal: 3, unit: "gwei" } ``` ### sign(message) ### veryfySignature(message, signature, address) ## WalletFactory * We want to inject testnet and dev network. * Switch L1 by environment variable. ### createFromPrivateKey(privateKey: Bytes) Create a wallet instance from private key. ### createFromEncryptedJson(json: string, password: string) Create a wallet instance from encrypted JSON data and a password. Encrypted JSON should be stored at a user's device such as PC or smartphone. The password is provided by the user every time the user opens the wallet. The purpose of this password is for encrypting privatekey. So even if user lost their smartphone, nobody can’t peek(spy?) the password. ### getMetaMaskWallet() Return a wallet instance connecting to Metamask extension. # Contract Wrapper Contract API. we may use Web3 like library for implementing this. - CommitmentContract - DepositContract(Plasma) - AdjudicatorContract - ERC20 - PlasmaPredicate These are minimal requirement. We need more contract wrapper contract repo is [here](https://github.com/cryptoeconomicslab/ovm-contracts) ## CommitmentContract ### submitRoot(root: Bytes32, blockNumber: Integer) ### getEventWatcher() Gets EventWatcher instance connecting to Commitment Contract. ## DepositContract ### deposit(amount: Integer, initialState: Property) ### finalizeCheckpoint(checkpoint: Property) ### finalizeExit(exit: Property, depositedRangeId: Integer) ### subscribeCheckpointFinalized ```js subscribeCheckpointFinalized( handler: (checkpointId: Bytes, checkpoint: [Range, Property]) => void ): void ``` ### subscribeExitFinalized ```js subscribeExitFinalized( handler: (exitId: Bytes) => void ): void ``` ## AdjudicatorContract ### claimProperty(property: Property) ### decideClaimTrue ### subscribePropertyClaimed ``` subscribePropertyClaimed( handler: (claimedProperty: Property, createdBlock: Integer) => void ) ``` # Event Watcher Polling ethereum events. Default polling interval is 10000 seconds, but we can set interval in constructor. ## EventWatcher class ### Constructor ``` constructor(endpoint: URL, targetContract: Address, contractInterface: ContractInterface, options: EventWatcherOptions) ``` `ContractInterface` is created by ethereum contract abi, and most web3 library has this class. It is used by pasing log bytes. options has only polling interval as `interval`. ### addHandler(event: string, handler: EventHandler): void Add handler for a contract event. ### removeHandler(event: string): void Unsubscribe an event and remove all handlers. ### initPolling(errorHandler?: ErrorHandler): void Start polling. ### EventHandler function ``` (event: Log) => void ``` We should think EventHandler argument shouldbe raw log byte data or parsed log data. If EventHandler pass raw log bytes, contractInterface isn't required in EventWatcher's constructor. ### Implementation * https://github.com/cryptoeconomicslab/wakkanay/tree/master/src/events #### Events examples? * BlockSubmitted * ClaimDecided * CheckpointFinalizedEvent * ExitFinalizedEvent Also you can check [contracts](https://github.com/cryptoeconomicslab/ovm-contracts/tree/master/contracts).