-
Notifications
You must be signed in to change notification settings - Fork 30
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Mock ingest transactions & produce blocks #325
Merged
willmeister
merged 15 commits into
plasma-group:master
from
willmeister:feat/323/MockIngestTransactionsAndProduceBlocks
Jul 22, 2019
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
cf08834
Initial commit of Aggregator StateUpdate Ingestion
willmeister b1b7791
Adds:
willmeister e7117ff
- Added BlockManager, Block DB CommitmentContract, and probably other…
willmeister 8a2682e
Adding async-mutex lib and adding mutual exclusion around BlockDB blo…
willmeister afaf746
Adding BlockManager tests and handling mutual exclusion in Block Subm…
willmeister 9b60b71
Adding test to make sure empty blocks are not submitted
willmeister 3d91ac8
- Adding tests for BlockDB
willmeister 0dc31ef
Changing tslint rule to be repo-wide
willmeister 1c8f514
Adding examples and comments in rangesSpanRange for clarity
willmeister 2c7c789
Adding error details
willmeister 7ce5099
renaming rangesSpanRange to doRangesSpanRange, removing unused import
willmeister 9c70d45
removoing `witness` from Aggregator.ingestTransaction(...) and updati…
willmeister dee7a3b
Fixing wallet nonce race condition in Deposit tests by creating a sep…
willmeister 37b9f0c
fixing linting issues
willmeister 8a26d52
Increasing default test timeout from 2 seconds to 5 seconds
willmeister File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import BigNum = require('bn.js') | ||
|
||
import { Aggregator } from '../../types/aggregator' | ||
import { StateManager } from '../../types/ovm' | ||
import { | ||
BlockTransaction, | ||
BlockTransactionCommitment, | ||
Transaction, | ||
TransactionResult, | ||
} from '../../types/serialization' | ||
import { doRangesSpanRange, sign } from '../utils' | ||
import { BlockManager } from '../../types/block-production' | ||
|
||
export class DefaultAggregator implements Aggregator { | ||
private readonly publicKey: string = | ||
'TODO: figure out public key storage and access' | ||
private readonly privateKey: string = | ||
'TODO: figure out private key storage and access' | ||
|
||
public constructor( | ||
private readonly stateManager: StateManager, | ||
private readonly blockManager: BlockManager | ||
) {} | ||
|
||
public async ingestTransaction( | ||
transaction: Transaction | ||
): Promise<BlockTransactionCommitment> { | ||
const blockNumber: BigNum = await this.blockManager.getNextBlockNumber() | ||
|
||
const { | ||
stateUpdate, | ||
validRanges, | ||
}: TransactionResult = await this.stateManager.executeTransaction( | ||
transaction, | ||
blockNumber, | ||
'' // Note: This function call will change, so just using '' so it compiles | ||
) | ||
|
||
if (!doRangesSpanRange(validRanges, transaction.range)) { | ||
throw Error( | ||
`Cannot ingest Transaction that is not valid across its entire range. | ||
Valid Ranges: ${JSON.stringify(validRanges)}. | ||
Transaction: ${JSON.stringify(transaction)}.` | ||
) | ||
} | ||
|
||
await this.blockManager.addPendingStateUpdate(stateUpdate) | ||
|
||
const blockTransaction: BlockTransaction = { | ||
blockNumber, | ||
transaction, | ||
} | ||
|
||
return { | ||
blockTransaction, | ||
witness: sign(this.privateKey, blockTransaction), | ||
} | ||
} | ||
|
||
public async getPublicKey(): Promise<any> { | ||
return this.publicKey | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './aggregator' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,151 @@ | ||
/* External Imports */ | ||
import BigNum = require('bn.js') | ||
import { Mutex } from 'async-mutex' | ||
|
||
import { BaseKey, BaseRangeBucket } from '../db' | ||
import { BlockDB } from '../../types/block-production' | ||
import { KeyValueStore, RangeStore } from '../../types/db' | ||
import { StateUpdate } from '../../types/serialization' | ||
import { MAX_BIG_NUM, ONE, ZERO } from '../utils' | ||
import { GenericMerkleIntervalTree } from './merkle-interval-tree' | ||
import { deserializeStateUpdate, serializeStateUpdate } from '../serialization' | ||
|
||
const KEYS = { | ||
NEXT_BLOCK: Buffer.from('nextblock'), | ||
BLOCK: new BaseKey('b', ['buffer']), | ||
} | ||
|
||
/** | ||
* Simple BlockDB implementation. | ||
*/ | ||
export class DefaultBlockDB implements BlockDB { | ||
private readonly blockMutex: Mutex | ||
|
||
/** | ||
* Initializes the database wrapper. | ||
* @param vars the KeyValueStore to store variables in | ||
* @param blocks the KeyValueStore to store Blocks in | ||
*/ | ||
constructor( | ||
private readonly vars: KeyValueStore, | ||
private readonly blocks: KeyValueStore | ||
) { | ||
this.blockMutex = new Mutex() | ||
} | ||
|
||
/** | ||
* @returns the next plasma block number. | ||
*/ | ||
public async getNextBlockNumber(): Promise<BigNum> { | ||
// TODO: Cache this when it makes sense | ||
const buf = await this.vars.get(KEYS.NEXT_BLOCK) | ||
return !buf ? ONE : new BigNum(buf, 'be') | ||
} | ||
|
||
/** | ||
* Adds a state update to the list of updates to be published in the next | ||
* plasma block. | ||
* @param stateUpdate State update to publish in the next block. | ||
* @returns a promise that resolves once the update has been added. | ||
*/ | ||
public async addPendingStateUpdate(stateUpdate: StateUpdate): Promise<void> { | ||
await this.blockMutex.runExclusive(async () => { | ||
const block = await this.getNextBlockStore() | ||
const start = stateUpdate.range.start | ||
const end = stateUpdate.range.end | ||
|
||
if (await block.hasDataInRange(start, end)) { | ||
throw new Error( | ||
'Block already contains a state update over that range.' | ||
) | ||
} | ||
|
||
const value = Buffer.from(serializeStateUpdate(stateUpdate)) | ||
await block.put(start, end, value) | ||
}) | ||
} | ||
|
||
/** | ||
* @returns the list of state updates waiting to be published in the next | ||
* plasma block. | ||
*/ | ||
public async getPendingStateUpdates(): Promise<StateUpdate[]> { | ||
const blockNumber = await this.getNextBlockNumber() | ||
return this.getStateUpdates(blockNumber) | ||
} | ||
|
||
/** | ||
* Computes the Merkle Interval Tree root of a given block. | ||
* @param blockNumber Block to compute a root for. | ||
* @returns the root of the block. | ||
*/ | ||
public async getMerkleRoot(blockNumber: BigNum): Promise<Buffer> { | ||
const stateUpdates = await this.getStateUpdates(blockNumber) | ||
|
||
const leaves = stateUpdates.map((stateUpdate) => { | ||
// TODO: Actually encode this. | ||
const encodedStateUpdate = serializeStateUpdate(stateUpdate) | ||
return { | ||
start: stateUpdate.range.start, | ||
end: stateUpdate.range.end, | ||
data: encodedStateUpdate, | ||
} | ||
}) | ||
const tree = new GenericMerkleIntervalTree(leaves) | ||
return tree.root().hash | ||
} | ||
|
||
/** | ||
* Finalizes the next plasma block so that it can be published. | ||
* | ||
* Note: The execution of this function is serialized internally, | ||
* but to be of use, the caller will most likely want to serialize | ||
* their calls to it as well. | ||
*/ | ||
public async finalizeNextBlock(): Promise<void> { | ||
await this.blockMutex.runExclusive(async () => { | ||
const prevBlockNumber: BigNum = await this.getNextBlockNumber() | ||
const nextBlockNumber: Buffer = prevBlockNumber.add(ONE).toBuffer('be') | ||
|
||
await this.vars.put(KEYS.NEXT_BLOCK, nextBlockNumber) | ||
}) | ||
} | ||
|
||
/** | ||
* Opens the RangeDB for a specific block. | ||
* @param blockNumber Block to open the RangeDB for. | ||
* @returns the RangeDB instance for the given block. | ||
*/ | ||
private async getBlockStore(blockNumber: BigNum): Promise<RangeStore> { | ||
const key = KEYS.BLOCK.encode([blockNumber.toBuffer('be')]) | ||
const bucket = this.blocks.bucket(key) | ||
return new BaseRangeBucket(bucket.db, bucket.prefix) | ||
} | ||
|
||
/** | ||
* @returns the RangeDB instance for the next block to be published. | ||
* | ||
* IMPORTANT: This function itself is safe from concurrency issues, but | ||
* if the caller is modifying the returned RangeStore or needs to | ||
* guarantee the returned next RangeStore is not stale, both the call | ||
* to this function AND any subsequent reads / writes should be run with | ||
* the blockMutex lock held to guarantee the expected behavior. | ||
*/ | ||
private async getNextBlockStore(): Promise<RangeStore> { | ||
const blockNumber = await this.getNextBlockNumber() | ||
return this.getBlockStore(blockNumber) | ||
} | ||
|
||
/** | ||
* Queries all of the state updates within a given block. | ||
* @param blockNumber Block to query state updates for. | ||
* @returns the list of state updates for that block. | ||
*/ | ||
private async getStateUpdates(blockNumber: BigNum): Promise<StateUpdate[]> { | ||
const block = await this.getBlockStore(blockNumber) | ||
const values = await block.get(ZERO, MAX_BIG_NUM) | ||
return values.map((value) => { | ||
return deserializeStateUpdate(value.value.toString()) | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import BigNum = require('bn.js') | ||
import { Mutex } from 'async-mutex' | ||
|
||
import { | ||
BlockDB, | ||
BlockManager, | ||
CommitmentContract, | ||
} from '../../types/block-production' | ||
import { StateUpdate } from '../../types/serialization' | ||
|
||
/** | ||
* Simple BlockManager implementation. | ||
*/ | ||
export class DefaultBlockManager implements BlockManager { | ||
private readonly blockSubmissionMutex: Mutex | ||
|
||
/** | ||
* Initializes the manager. | ||
* @param blockdb BlockDB instance to store/query data from. | ||
* @param commitmentContract Contract wrapper used to publish block roots. | ||
*/ | ||
constructor( | ||
private blockdb: BlockDB, | ||
private commitmentContract: CommitmentContract | ||
) { | ||
this.blockSubmissionMutex = new Mutex() | ||
} | ||
|
||
/** | ||
* @returns the next plasma block number. | ||
*/ | ||
public async getNextBlockNumber(): Promise<BigNum> { | ||
return this.blockdb.getNextBlockNumber() | ||
} | ||
|
||
/** | ||
* Adds a state update to the list of updates to be published in the next | ||
* plasma block. | ||
* @param stateUpdate State update to add to the next block. | ||
* @returns a promise that resolves once the update has been added. | ||
*/ | ||
public async addPendingStateUpdate(stateUpdate: StateUpdate): Promise<void> { | ||
await this.blockdb.addPendingStateUpdate(stateUpdate) | ||
} | ||
|
||
/** | ||
* @returns the state updates to be published in the next block. | ||
*/ | ||
public async getPendingStateUpdates(): Promise<StateUpdate[]> { | ||
return this.blockdb.getPendingStateUpdates() | ||
} | ||
|
||
/** | ||
* Finalizes the next block and submits the block root to Ethereum. | ||
* @returns a promise that resolves once the block has been published. | ||
*/ | ||
public async submitNextBlock(): Promise<void> { | ||
await this.blockSubmissionMutex.runExclusive(async () => { | ||
// Don't submit the block if there are no StateUpdates | ||
if ((await this.getPendingStateUpdates()).length === 0) { | ||
return | ||
} | ||
const blockNumber = await this.getNextBlockNumber() | ||
await this.blockdb.finalizeNextBlock() | ||
const root = await this.blockdb.getMerkleRoot(blockNumber) | ||
await this.commitmentContract.submitBlock(root) | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,5 @@ | ||
export * from './block-db' | ||
export * from './block-manager' | ||
export * from './merkle-interval-tree' | ||
export * from './state-interval-tree' | ||
export * from './plasma-block-tree' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice mutex!